urls.py #coding=utf-8 '''定义learning_logs的URL模式''' from django.conf.urls import url from . import views urlpatterns = [ #主页 url(r'^$',views.index,name='index'), #显示所有的主题 url(r'^topics/$',views.topics,name='topics'), #特定主题的详细页面 url(r'^topics/(?P<topics_id>\d+)/$',views.topic,name='topic'), ]
views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from .models import Topic # Create your views here. def index(request): '''学习笔记的主页''' return render(request,'learning_logs/index.html') def topics(request): '''显示所有的主题''' topics=Topic.objects.order_by('date_added') context={'topics':topics} return render(request,'learning_logs/topics.html',context) def topic(request,topic_id): '''显示单个主题及其所有条目''' topic=Topic.objects.get(id=topic_id) entries=topic.entry_set.order_by('-date_added') context={'topic':topic,'entries':entries} return render(request,'learning_logs/topic.html',context)
models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Topic(models.Model): '''用户学习的主题''' text=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) def __unicode__(self): '''返回模型的字符串表示''' return self.text class Entry(models.Model): '''学到的有关某个主题的具体知识''' topic=models.ForeignKey(Topic) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural='entries' def __unicode__(self): '''返回模型的字符串表示''' return self.text[:50]+"..."
urls.py中将?P<topic_id>匹配到的值存储到topics_id中
views.py接受正则表达式(?P<topic_id>\d+)捕获的值,使用get来获取到指定主题
urls.py与views.py中的参数需保持一致,上面代码中urls.py中的参数为topics_id,views.py中的参数为topic_id,所有报错
参考:https://stackoverflow.com/questions/37254829/django-got-an-unexpected-keyword-argument-id