2012-10-11 43 views
0

我收到此錯誤:invalid literal for int() with base 10: 'social'當我嘗試在/ category/social /中打開頁面時。如何修復django中的valueerror無效字面錯誤?

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..."行。

回答

0

在你看來,category必須是一個整數或一個字符串,可以被鑄造爲一個int,如int('5')。你必須去不限制類別的URL是一個整數:

foosite.com/category/social/ 

如果URL映射到category參數的最後部分,然後在視圖中,在查詢中,它會嘗試如此將social轉換爲整數,這會引發錯誤。

要解決它,你必須restring 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。

相關問題