I am trying to render out my generic create view for django and I cannot do so as I am getting the error "ValueError at /teacher/add/" "Field 'id' expected a number but got 'add'." I am not sure what the problem would be here.
models.py
from django.db import models
from django.urls import reverse
# Create your models here.
DEPARTMENT_CHOICES = [
('Social Studies', 'Social Studies'),
('Math', 'Math'),
('Science', 'Science'),
]
class Department(models.Model):
name = models.CharField(choices=DEPARTMENT_CHOICES, max_length=300)
def __str__(self):
return self.name
class Teacher(models.Model):
name = models.CharField(max_length=300)
# delete dept == delete teacher
department = models.ForeignKey(Department, on_delete=models.CASCADE)
tenure = models.BooleanField()
def __str__(self):
return f'{self.name} teaches {self.department}'
# dont need success url if get_absolute_url on create and update view
def get_absolute_url(self):
return reverse('teacher-detail', kwargs={'pk': self.pk})
urls.py
urlpatterns = [
path('teacher/add/', TeacherCreateView.as_view(), name='teacher-add'),
]
views.py
class TeacherCreateView(CreateView):
model = Teacher
fields = ['name']
CodePudding user response:
You likely have another URL pattern before the TeacherCreateView
that captures the add
, and thus will fire a different view. This could for example look like:
urlpatterns = [
path('teacher/<pk>/', TeacherDetailView.as_view(), name='teacher'),
# …,
path('teacher/add/', TeacherCreateView.as_view(), name='teacher-add'),
# …
]
as a result <pk>
will capture add
and thus fire the DetailView
instead. You should make the pk
more restrictive and work with an <int:…>
path converter:
urlpatterns = [
path('teacher/<int:pk>/', TeacherDetailView.as_view(), name='teacher'),
# …
path('teacher/add/', TeacherCreateView.as_view(), name='teacher-add'),
# …
]