【问题标题】:Django, viewing models from different appDjango,查看来自不同应用程序的模型
【发布时间】:2016-10-15 09:02:07
【问题描述】:

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

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

我想在views.py中我的home应用程序中对此做一些事情,例如在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 %}

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

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

【问题讨论】:

  • 您的代码很好,应该可以工作。您确定您使用的数据库与您的应用在运行 Video.objects.all() 时使用的数据库相同吗?
  • 您可以与文件和文件夹共享您的项目层次结构吗?
  • 是的,我确定。我不确定为什么它没有显示任何内容。我什至尝试在视频应用程序中运行此代码,但仍然没有显示视频。但是当我去 python manage.py shell 时。我导入 video.models 并显示 2 个对象
  • 我的项目如下 1. - - - ,我似乎不知道如何在这里做一个正确的缩进,但是项目名称,主页,和视频在同一级别
  • 在 settings.py 中发布您的 TEMPLATES 变量

标签: django import views models


【解决方案1】:

我决定删除项目并重新开始,但这次我使用类视图而不是函数视图。我不确定为什么它没有运行,但使用类视图它就像一个魅力。所以类视图中的等价物尽可能简单。

 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]

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 是的,我的设置中有这个。
    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2011-02-14
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多