在一個應用程序中我有兩個模型,命名爲課程和步驟。每一步都屬於一門課程,每門課程都有很多步驟。但是,我在爲步驟創建詳細視圖時遇到了問題。例如,當我轉到url'http://127.0.0.1:8000/courses/1'時,它應該顯示course.objects.get(pk=1)
的步驟。然而,我回來的只是當然的頁面,即http://127.0.0.1:8000/courses'。DetailView模板不顯示數據
型號
from django.db import models
# Create your models here.
class Course(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length= 255)
description = models.TextField()
def __str__(self):
return self.title
class Step(models.Model):
title = models.CharField(max_length = 255)
description = models.TextField()
order = models.IntegerField()
course = models.ForeignKey(Course)
def __str__(self):
return self.title
網址
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.course_list),
url(r'(?P<pk>\d+)/$', views.course_detail)
]
查看
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from .models import Course, Step
def course_list(request):
courses = Course.objects.all()
return render(request, 'courses/course_list.html', {'courses': courses})
def course_detail(request, pk):
course = Course.objects.get(pk=pk)
return render(request, 'courses/course_detail.html', {'course': course})
course_detail.html
{% extends 'layout.html' %}
{% block title %}{{course.title}}{% endblock %}
{% block content %}
<article>
<h2>{{ course.title }} %</h2>
{{course.description}}
<section>
{% for step in course.step_set.all %}
<h3>{{ step.title }}</h3>
{{step.description}}
{% endfor %}
</section>
</article>
{% endblock %}
名主要的url
from django.conf.urls import url, include
from django.contrib import admin
from courses.views import course_list
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^courses/', course_list),
url(r'^admin/', admin.site.urls),
url(r'^$', views.hello_world),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
我似乎不承認我哪裏錯了
我想這個'urls.py'是你的「課程」應用程序的一個。你的主'urls.py'文件中有什麼? –
剛剛添加了我的主要urls.py文件 – electro7912
那裏!問題是你的主'urls.py'不包含應用程序中的'urls.py',它只是解決從'courses /'開始到'course_list'視圖的每條路徑。我會添加一個答案。 –