Mehi
Mehi

Reputation: 5

invalid literal for int() with base 10 in django?

I wrote this code :

views.py:

class IndexView(TemplateView):
    template_name = 'index.html'

class SchoolListView(ListView):
    context_object_name = 'schools'
    model = models.School

class SchoolDetailView(DetailView):
    context_object_name = 'school_detail'
    model = models.School
    template_name = 'nineapp/school_detail.html'

class SchoolCreateView(CreateView):
    fields = ('name', 'principal', 'location')
    model  = models.School

models.py:

class School(models.Model):
    #ppk       = models.IntegerField(default=0 , primary_key=True)
    name      = models.CharField(max_length=256)
    principal = models.CharField(max_length=256)
    location  = models.CharField(max_length=256)

    def __str__(self):
        return self.name


class Student(models.Model):
    name   = models.CharField(max_length=256)
    age    = models.CharField(max_length=256)
    school = models.ForeignKey(School, related_name='students', on_delete=models.CASCADE)

    def __str__(self):
        return self.name

urls.py:

urlpatterns = [
    url(r'^$', views.SchoolListView.as_view(), name='list'),
    url(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'),
    url(r'^createsc/(?P<pk>[-\w]+)$', views.SchoolCreateView.as_view(), name='createsc'),
]

this program is working correctly but when i want to go the createsc/ I've got this error: invalid literal for int() with base 10: 'createsc'

please help me.

Upvotes: 0

Views: 250

Answers (1)

user2390182
user2390182

Reputation: 73498

"createsc/" already matches the preceding url of the detail view which tries to use "createsc" as a primary key for its object retrieval. Either give your urls unique prefixes, e.g.:

urlpatterns = [
    # ...
    url(r'^detail/(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'),
    url(r'^createsc/(?P<pk>[-\w]+)$', views.SchoolCreateView.as_view(), name='createsc'),
]

or be more specific with your regexes. After all pks will consist of digits only:

urlpatterns = [
    # ...
    url(r'^(?P<pk>\d+)/$', views.SchoolDetailView.as_view(), name='detail'),
    url(r'^createsc/(?P<pk>\d+)$', views.SchoolCreateView.as_view(), name='createsc'),
]

The create view really doesn't need the pk group at all as the pk is not known in advance:

    url(r'^createsc/$', views.SchoolCreateView.as_view(), name='createsc'),

should be fine.

Upvotes: 1

Related Questions