首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修复django中的valueerror无效文字错误?

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

Stack Overflow用户
提问于 2012-10-11 11:17:51
回答 1查看 101关注 0票数 0

当我试图在/category/ invalid literal for int() with base 10: 'social' /上打开一个页面时,我得到了这样的错误:社交。

代码语言:javascript
复制
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..."行中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-11 11:25:47

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

代码语言:javascript
复制
foosite.com/category/social/

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

要解决这个问题,你要么重新设置url模式,使其只允许数字,要么改变查询的方式。

代码语言:javascript
复制
# urls.py
url(r'^category/(?P<category>\d+)/$', 'all_partners'),

代码语言:javascript
复制
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来查找类别。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12831664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档