Django,从不同的应用程序查看模型(Django, viewing models from different app)

我是python编程和django的新手,我得到了基础知识。 我用两个应用程序,家庭和视频创建了一个项目。 在我的视频models.py中,我有以下数据:

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

我想在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)

在我的home.html中

{% 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 %}

我的home.html总是返回“没有视频显示”

但是当我在我的视频应用程序中查询Video.objects.all()时,它发现2个对象。 任何帮助表示赞赏。

I am super new to python programming and django and i got the basics out of the way. I created a project with two apps, home and video. In my video models.py i have the following data:

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

I want to do something with this in my home app in the views.py, such as display the data in an html page and currently it is set up as followed:

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)

in my home.html

{% 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 always returns "no videos to display"

But when i query Video.objects.all() in my video app it finds 2 objects. any help is appreciated.

最满意答案

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

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', ], }, }, ]

I decided to delete the project and started over brand new but this time I used class views instead of function views. I'm not exactly sure why it didn't run but using class views it worked like a charm. So the equivalent in class views as simple as possible is.

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]

更多推荐