如何在django中修复valueerror无效的文字错误?

时间:2012-10-11 03:17:51

标签: python django url view model

当我尝试在/ category / social /打开一个页面时,我收到此错误:invalid literal for int() with base 10: 'social'

def all_partners(request,category):
    p = Content.objects.filter(category_id=category)
    return render_to_response('reserve/templates/category.html', {'p':p},
        context_instance=RequestContext(request))


class ContentCategory(models.Model):
    content_category = models.CharField('User-friendly name', max_length =  200)
    def __unicode__(self):
        return self.content_category

class Content(models.Model):
    category = models.ForeignKey(ContentCategory)
    external = models.CharField('User-friendly name', max_length =  200, null=True, blank=True)
    host = models.CharField('Video host', max_length = 200, null=True, blank=True)
    slug = models.CharField('slug', max_length = 200, null=True, blank=True)
    def __unicode__(self):
        return self.slug

url(r'^category/(?P<category>[-\w]+)/$', 'all_partners'),

有关如何解决此问题的任何想法?我认为错误发生在"p = Content..."行。

1 个答案:

答案 0 :(得分:0)

在您的视图中,category必须是一个整数,或者可以转换为类似int('5')的int的字符串。您必须转到不限制类别为整数的网址:

foosite.com/category/social/

因此,如果url的最后一部分映射到category参数,那么在视图中,在查询中,它会尝试将social强制转换为整数,这会引发错误。

要解决此问题,您必须重新绑定网址格式以仅允许数字或更改查询的完成方式。

# urls.py
url(r'^category/(?P<category>\d+)/$', 'all_partners'),

def all_partners(request,category):
    p = Content.objects.filter(category__content_category=category)
    return render_to_response('reserve/templates/category.html', {'p':p},
        context_instance=RequestContext(request))

然后将按名称而不是id来查找类别。