【问题标题】:How to fix valueerror invalid literal error in django?如何修复 django 中的 valueerror 无效文字错误?
【发布时间】:2012-10-11 03:17:51
【问题描述】:

当我尝试在 /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..." 行。

【问题讨论】:

    标签: python django url view model


    【解决方案1】:

    在您看来,category 必须是一个整数,或者是一个可以转换为类似 int('5') 的 int 的字符串。您必须访问一个不将类别限制为整数的 url:

    foosite.com/category/social/
    

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

    要解决这个问题,您要么必须重新设置 url 模式以仅允许数字,要么更改查询的完成方式。

    # 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 查找类别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 2019-04-03
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多