Django没有正确验证基于类的视图

时间:2016-08-19 16:46:12

标签: django django-forms django-views django-class-based-views django-validation

在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方法的任何想法?

PS:我按照https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#models-and-request-user

的基于类的视图表单验证的示例

0 个答案:

没有答案