当前位置: 动力学知识库 > 问答 > 编程问答 >

django - invalid literal for int() with base 10: '' -> not understanding what this error means in my project

问题描述:

I'm trying to create a website with Django. I want an index displaying rubriques, and when you click on a rubrique, the articles of this rubrique show.

Here is my models.py :

class Rubrique(models.Model):

nom = models.CharField(max_length=200)

resume = models.CharField(max_length=200)

Here is my urls.py :

urlpatterns = patterns('',

url(r'^$', views.index, name='index'),

url(r'^(?i)(?P<rubrique_id>)[a-z]+/$',

views.rubriques, name='rubriques'),

url(r'^(?i)(?P<rubrique_id>)[a-z]+/(?P<article_id>)[a-z]+/$',

views.articles, name='articles'),

)

Here is my views.py :

def rubriques(request, rubrique_id):

rubrique = get_object_or_404(Rubrique, pk=rubrique_id) <-- The error points this line

return render(request, 'rubriques/rubrique.html', {'rubrique': rubrique})

Aaand here is the error :

ValueError at /rubriques/sport/

invalid literal for int() with base 10: ''

The sport rubrique exists, and my template should be ok. What's wrong ? I have troubles with Django...

网友答案:

pk field is a number by default, as in your model.

You have this in your url (?P<rubrique_id>)[a-z]+ -> letters, not a number.

I don't know how are you calling your urls... but that's wrong for sure.

If you want to pass the signatures by its name, set the field as primary key:

class Rubrique(models.Model):
    nom = models.CharField(max_length=200, primary_key=True)
    resume = models.CharField(max_length=200)

or, another option, change the lookup code:

rubrique = get_object_or_404(Rubrique, nom=rubrique_id)

You should set it as unique in this last case:

class Rubrique(models.Model):
     nom = models.CharField(max_length=200, unique=True)
     resume = models.CharField(max_length=200)
网友答案:

You have not declared any primary key field in the model, so Django automatically created an integer field to serve as primary key, so alias pk points to an autocreated field. It should be

class Rubrique(models.Model):
    nom = models.CharField(max_length=200, primary_key=True)
    resume = models.CharField(max_length=200)

Refer to Django model field documentation and Automatic primary keys for details

分享给朋友:
您可能感兴趣的文章:
随机阅读: