我對Django非常陌生,目前我正嘗試爲幾個我最喜歡的導演創建一個電影數據庫。我一直在關注教程視頻,並且我正在試圖讓我的詳細視圖爲每位導演顯示所有添加的電影。但是當我進入導演時,它不會顯示他們的電影。Django模板不顯示模型項目
總監/ models.py
from django.db import models
class Director(models.Model):
photo = models.CharField(max_length=250, default='none')
name = models.CharField(max_length=250)
born = models.CharField(max_length=250)
birth_date = models.CharField(max_length=20)
married = models.CharField(max_length=1)
def __str__(self):
return self.name
class Films(models.Model):
director = models.ForeignKey(Director, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
year = models.IntegerField(default=0)
rating = models.DecimalField(max_digits=2, decimal_places=1, default=0)
budget = models.CharField(max_length=20)
def __str__(self):
return self.title
總監/ urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<name_id>[0-9]+)/$', views.detail, name='detail'),
]
總監/ views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Director, Films
def index(request):
all_directors = Director.objects.all()
return render(request, 'director/index.html', {'all_directors': all_directors})
def detail(request, name_id):
try:
direct = Director.objects.get(pk=name_id)
except Director.DoesNotExist:
raise Http404("Director not found")
return render(request, 'director/detail.html', {'direct': direct})
總監/ detail.html
<h3 align="center"> {{ direct }} </h3><br>
<img src="{{ director.photo }}">
<h4>Film List</h4>
<ul>
{% for films in director.films_set.all %}
<li>{{ direct.title }} - {{ direct.rating }}</li>
{% endfor %}
</ul>
當我運行服務器並進入頁面時,我點擊了一個導演,它所說的是導演名稱和「電影列表」。請告知如何解決此問題,非常感謝任何幫助!
在Django中,你通常會使用單'Film'代替'Films'(就像你有'Director'而不是'Directors'一樣)。 – Alasdair