Django: TypeError topic() got an unexpected keyword argument 'topics_id'
阿新 • • 發佈:2019-01-30
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