Django TypeError get_object_or_404()至少需要一个参数(0给定) [英] Django TypeError get_object_or_404() takes at least 1 argument (0 given)

查看:565
本文介绍了Django TypeError get_object_or_404()至少需要一个参数(0给定)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做博客和学习django。我正在尝试纳入包含短号和发帖的网址。



当我点击管理面板中的查看网站链接时,我收到这个错误:
NoReverseMatch at / admin / r / 7/2 /反向为'article'与参数'(u'test-post-3','2')'和关键字参数'{}'未找到。 0模式尝试:[]



当我手动输入url,我得到这个错误:
TypeError在/ articles / test-post-3 ,2 / get_object_or_404()至少需要一个参数(0)
这是我的代码:



views.py:


来自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

#在这里创建您的意见。

from article.models import Content

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

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:

$ b $来自django.conf.urls导入模式的b

 文章导入视图中的


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导入模型
从django.db.models导入永久链接
从django.utils import timezone
import datetime
#在这里创建您的模型。


class内容(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()
现在返回 - datetime.timedelta(days = 1) < = self.published_date< = now
was_published_recently.admin_order_field ='published_date'
was_published_recently.boolean = True
w as_published_recently.short_description ='最近发布?'

main urls.py:

$ b $来自django.conf.urls的import




从django.contrib导入admin
admin.autodiscover ()

urlpatterns = patterns('',
#示例:
#url(r'^ $','thebluntist.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)),

pre>

解决方案

您的使用不当 get_object_or_404


Docstring:


get_object_or_404(klass,* args,** kwargs)


使用 get()返回一个对象,或者引发一个 Http404 异常如果对象
不存在

klass 可能是模型经理,或 QuerySet 对象。所有其他传递的
参数和关键字参数都在 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)) / code>


I'm making a blog and learning django as I go. I'm trying to incorporate urls that include both sluglines and post ids.

When I click on the "view on site" link in the admin panel, I get this error: NoReverseMatch at /admin/r/7/2/ Reverse for 'article' with arguments '(u'test-post-3', '2')' and keyword arguments '{}' not found. 0 pattern(s) tried: []

When I manually enter the url, I get this error: TypeError at /articles/test-post-3,2/ get_object_or_404() takes at least 1 argument (0 given) Here's my code:

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)),
)

解决方案

You have a bad usage of get_object_or_404:

Docstring:

get_object_or_404(klass, *args, **kwargs)

Uses get() to return an object, or raises a Http404 exception if the object does not exist.

klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query.

Note: Like with get(), an MultipleObjectsReturned will be raised if more than one object is found.

You can make as following:

  • 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))

这篇关于Django TypeError get_object_or_404()至少需要一个参数(0给定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆