我是一个不成熟的django网站开发人员。我和Django有一个问答。这个错误是“cats()得到了一个意外的关键字参数'pk'”。 请看我的代码并帮助我。
Request Method: GET
Request URL: http://127.0.0.1:8000/1
Django Version: 1.6.5
Exception Type: TypeError
Exception Value:
cats() got an unexpected keyword argument 'pk'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response, line 112
Python Executable: /usr/bin/python
Python Version: 2.7.6
models.py
from django.db import models
from taggit.managers import TaggableManager
class Category(models.Model):
title = models.CharField(max_length=40)
def __unicode__(self):
return self.title
class Post (models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
date = models.DateTimeField()
tags = TaggableManager ()
cats = models.ManyToManyField(Category)
def __unicode__ (self):
return self.title
urls.py
from django.conf.urls import include, url, patterns
from django.views.generic import ListView, DetailView
from blog.models import Post, Category
urlpatterns = patterns('blog.views',
url(r'^$',ListView.as_view(
queryset = Post.objects.all().order_by("-date")[:2],
template_name="index.html")),
url(r'^(?P<pk>\d+)$', 'cats', name='cats'),
)
views.py
from blog.models import Post,Category
from django.shortcuts import render_to_response
from django.template import RequestContext
def cats(request):
queryset = Post.objects.all().order_by("-date")
navitem = Category.objects.all().order_by("title")
return render_to_response('post.html',{'queryset':queryset,'navitem':navitem},context_instance=RequestContext(request))
答案 0 :(得分:1)
问题出在 urls.py :
的这一行url(r'^(?P<pk>\d+)$', 'cats', name='cats')
您正在向视图发送不需要的参数。
您可以在视图参数中包含pk
参数,如下所示:
def cats(request, pk):
或者这个:
def cats(request, pk=None):
或者,更好的是,您可以在网址中使用不同的模式,而不是capturing它(因为您在视图中根本没有使用pk
值,您不需要为它创建一个变量),如下所示:
url(r'^(\d+)$', 'cats', name='cats')