在Django 1.9在线学习应用程序中,我使用基于类的基于视图的CreateView
以及其他一些mixins创建了一个表单。以“拥有者”的形式能够创建一个新课程,但在表单提交后,我收到以下错误:
IntegrityError at /course/create/
NOT NULL constraint failed: courses_course.owner_id
我意识到我收到了错误,因为表单没有保存owner
,这是Course
模型的一部分。我知道所有者没有保存,因为该应用甚至没有在form_valid
课程中输入我的OwnerEditMixin
方法。 (我的控制台没有在方法中打印form validating ...
消息。)
以下是我视图中的代码:
from django.core.urlresolvers import reverse_lazy
from django.views.generic.edit import CreateView
from .models import Course
from django.contrib.auth.mixins import LoginRequiredMixin, \
PermissionRequiredMixin
class OwnerMixin(object):
def get_queryset(self):
qs = super(OwnerMixin, self).get_queryset()
return qs.filter(owner=self.request.user)
class OwnerEditMixin(object):
def form_valid(self, form):
print('form validating ...')
form.instance.owner = self.request.user
return super(OwnerEditMixin, self).form_valid(form)
class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin):
model = Course
class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin):
fields = ['subject', 'title', 'slug', 'overview']
success_url = reverse_lazy('manage_course_list')
template_name = 'courses/manage/course/form.html'
class CourseCreateView(OwnerCourseEditMixin, CreateView,
PermissionRequiredMixin):
permission_required = 'courses.add_course'
相关的模板代码在这里:
<form action="." method="post">
{{ form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Save course"></p>
</form>
为什么基于类的视图不能调用我的form_valid
方法的任何想法?