我创建了带有类别,子类别和子子类别的模型。我有很多问题使其无法正常工作。 我的models.py:
class School(models.Model):
school_name = models.CharField(max_length = 100)
slug = AutoSlugField(populate_from = 'school_name', unique = True)
...
class Department(models.Model):
department_name = models.CharField(max_length = 100)
slug = AutoSlugField(populate_from = 'department_name', unique = True)
school = models.ForeignKey(School, on_delete = models.CASCADE)
...
class Professor(models.Model):
Professor_name = models.CharField(max_length = 100)
slug = models.SlugField()
department = models.ForeignKey(Department, on_delete = models.CASCADE)
...
我的views.py:
def department_list(request, category_slug):
category = get_object_or_404(School, slug = category_slug)
schools = School.objects.filter(school_name = category)
departments = Department.objects.filter(school = category)
context = {'schools':schools, 'departments': departments}
return render(request, 'main/department_list.html', context)
def professor_list(request, category_slug, department_slug):
category = get_object_or_404(School, slug = category_slug)
subcategory = get_object_or_404(Department, slug = department_slug)
schools = School.objects.filter(school_name = category)
departments = Department.objects.filter(school = category)
Professors = Professor.objects.filter(department = subcategory)
context = {'Professors ': Professors}
return render(request, 'main/Professor_list.html', context)
class DepartmentCreateView(CreateView):
model = Department
fields = ['department_name']
def get_context_data(self, **kwargs):
school = get_object_or_404(School, pk=self.kwargs['school_id'])
kwargs['school'] = school
return super().get_context_data(**kwargs)
def form_valid(self, form):
school = get_object_or_404(School, pk=self.kwargs['school_id'])
form.instance.school = school
return super().form_valid(form)
我的urls.py
urlpatterns = [
path('<category_slug>/', views.department_list, name = 'departments'),
path('<category_slug>/<department_slug>/', views.professor_list, name =
'Professors'),
path('<category_slug>/new/', DepartmentCreateView.as_view(), name =
'department-create'),
]
我的department_list视图有效,但是Professor_list和DepartmentCreateView似乎永远失败。我尝试到处寻找,但似乎无法弄清原因。有人可以给我建议吗?预先谢谢你!