Django TypeError get_object_or_404()至少需要1个参数(给定0)

时间:2014-10-20 22:49:16

标签: python django

我正在制作博客并学习django。我试图整合包含sluglines和post id的网址。

点击网站上的"视图"管理面板中的链接,我收到此错误: NoReverseMatch at / admin / r / 7/2 / Reverse for' article'有参数'(u' test-post-3',' 2')'和关键字参数' {}'未找到。尝试了0种模式:[]

当我手动输入网址时,出现此错误: / articles / test-post-3,2 / get_object_or_404()中的TypeError至少需要1个参数(给定0) 这是我的代码:

views.py:

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone

# Create your views here.

from articles.models import Content

class IndexView(generic.ListView):
    template_name = 'articles/index.html'
    context_object_name = 'latest_articles_list'

    def get_queryset(self):
        return Content.objects.filter(
            published_date__lte=timezone.now()
        ).order_by('-published_date')[:5]

def detail(request, slugline, id):
    article = get_object_or_404(pk=id)
    return render(request, 'articles/detail.html', {'article': article})

urls.py:

from django.conf.urls import patterns, url
from articles import views

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name = 'index'),
    #url(r'^(?P<slugline>[-\w\d]+), (?P<pk>\d+)/$', views.DetailView.as_view(), name='detail')
    url(r'^(?P<slugline>[-\w\d]+),(?P<id>\d+)/$', view=views.detail, name='article'),
)

models.py:

from django.db import models
from django.db.models import permalink
from django.utils import timezone
import datetime
# Create your models here.


class Content(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slugline = models.SlugField(max_length=100, unique=True)
    body = models.TextField()
    published_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.title

    @permalink
    def get_absolute_url(self):
        # return ('article', (), {
            # 'slugline': self.slugline,
            # 'id': self.id,
        # })
        from django.core.urlresolvers import reverse
        return reverse('article', args=[self.slugline, str(self.id)])

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.published_date <= now
    was_published_recently.admin_order_field = 'published_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

main urls.py:

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'the_Bluntist.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^articles/', include('articles.urls', namespace="articles")),
    url(r'^admin/', include(admin.site.urls)),
)

2 个答案:

答案 0 :(得分:2)

您使用get_object_or_404

  

文档字符串:

  get_object_or_404(klass, *args, **kwargs)

  使用get()返回对象,或者如果对象引发Http404异常   不存在。
  
klass可以是ModelManagerQuerySet对象。所有其他通过   get()查询中使用了参数和关键字参数。   

  注意:与get()一样,如果不止一个,则会引发MultipleObjectsReturned   找到了对象。

您可以制作如下:

  • article = get_object_or_404(Article, pk=id)
  • article = get_object_or_404(Article.objects, pk=id))
  • article = get_object_or_404(Article.objects.all(), pk=id))
  • article = get_object_or_404(Article.objects.filter(pk=id))

答案 1 :(得分:0)

article = get_object_or_404(pk=id)

您必须将模型传递给调用。 Documentation here

article = get_object_or_404(klass, pk=id)