Django,从不同的应用程序查看模型

wkftcu5l  于 2023-01-10  发布在  Go
关注(0)|答案(3)|浏览(104)

我是python编程和django的新手,我已经掌握了一些基本知识,我创建了一个包含两个应用程序的项目,home和video,在我的视频www.example.com中models.py我有以下数据:

class Video(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(blank=True, null=True)

我想在www.example.com中的家庭应用程序中对此进行一些views.py,例如在html页面中显示数据,当前设置如下:

from video.models import Video

def display_video(request):
    video_list = Video.objects.all()
    context = {'video_list': video_list}
    return render(request, 'home/home.html', context)

在我的主页

{% if video_list %}
 {% for video in video_list %}
  <p>{{ video.name }}</p>
  <p>{{ video.description }}</p>
 {% endfor %}
{% else %}
 <p>no videos to display</p>
{% endif %}

my home.html总是返回“没有视频可显示”
但是当我在我的视频应用程序中查询Video.objects.all()时,它找到了2个对象。任何帮助都将不胜感激。

vjrehmav

vjrehmav1#

我决定删除这个项目,重新开始,但这次我用类视图而不是函数视图。我不知道为什么它不能运行,但使用类视图它工作起来像一个魅力。因此,在类视图中尽可能简单的等价物是。

from video.models import Video

 class IndexView(generic.ListView):
   template_name = 'home/index.html'
   context_object_name = 'top_three'

   def get_queryset(self):
    return Video.objects.all()[:3]
njthzxwz

njthzxwz2#

在设置中,检查是否存在以下内容。

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]
g52tjvyc

g52tjvyc3#

不用上课对我很有效。我只是做了我们通常做的事情。

from django.shortcuts import render
from AllBlogs.models import Post        # getting this post form AllBlogs app 

# Create your views here.

def home (request):
    # sort posts according to date in descending order
    # only a single query is generated and then hit the database that's how this will not affect the performance of database
    latest_blogs = Post.objects.all().order_by("-date")[:3]   
    return render(request,'Home/home.html',{'blog':latest_blogs})

这是我的模板

<!--separated it from the home.html because we can use it in AllBlogs.html
and it  save our work and time by just including without copying the same data several times-->
{% load static %}
<li>
  <!--add field name which we used in models-->
    <article class="blog">
      <a href="{% url 'blogDetails_page' blog.slug %}">     <!--Different slug for different blog as slug will create a different url-->
        <!--dtl filter to add back or url dynamic url creation-->
        <image src="{% static 'images/'|add:blog.image_name %}" alt="{{blog.title}}">
        <div class="blog__content">
          <h3>{{blog.title}}</h3>
          <p>{{blog.excerpt}}</P>
        </div>
      </a>
    </article>
</li>

这是波斯特模型

# having post data 
class Post(models.Model):
    title = models.CharField(max_length=150)
    date = models.DateField(auto_now=True)    # put the date in the field at which time we are saving the data
    image_name = models.CharField(max_length=50)          # later on we upload files right now we get images from static folder
    excerpt = models.CharField(max_length=200)
    content = models.TextField(validators=[MinLengthValidator(10)])    # TextFields same like CharField
    slug = models.SlugField(unique=True, db_index=True)     # set it as unique because we are going to use it as a primary key
    author = models.ForeignKey(Author,on_delete=models.SET_NULL,related_name='posts',null=True)      # one to many relation 
    tags = models.ManyToManyField(Tag)              # ManyToManyRelation with tag

    # represent post entry by it post title
    def __str__(self):
        return self.title

相关问题