Django:在CreateView中设置ForiegnKey的初始值

时间:2016-06-07 18:37:53

标签: python django django-1.9

我正在尝试创建CreateView类型的视图。此视图将采用我创建的form_class = CourseForm并排除其中的某些字段。 instructor字段是foriegnKey,我不希望用户能够在表单中控制它。这是一个取决于已登录用户的字段。

# forms.py
class CourseForm(forms.ModelForm):
    class Meta:
        model = Course
        exclude = ['instructor', 'members', 'slug']
    # ...

我的观点如下。我认为通过在initial中包含教师值会在我提交

时传递配置文件实例
# views.py

@method_decorator(login_required, name='dispatch')
class CourseCreateView(CreateView):
    model = Course
    template_name = 'course_form.html'
    success_url = reverse_lazy('course-create-complete')

    form_class = CourseForm

    def get_initial(self):
        initial = super(CourseCreateView, self).get_initial()
        initial = initial.copy()
        profile = get_object_or_404(Profile, user__username=self.request.user)
        initial['instructor'] = profile
        return initial


# models.py

class Course(models.Model):
    instructor = models.ForeignKey(Profile, related_name="Instructor")
    # ... other fields

但问题是每当我提交表单时,我都会收到以下错误:

  

NOT NULL约束失败:myapp_course.instructor_id

1 个答案:

答案 0 :(得分:1)

如果您想设置instructor字段的初始值,则不应将其从表单中排除。您可以改为隐藏字段。

或者您可以在exclude列表中包含该内容,但是您不应该覆盖get_initial方法,而是手动执行分配:

class CourseCreateView(CreateView):
    def form_valid(self, form):
        self.object = form.save(commit=False)
        # create instructor based on self.request.user
        self.object.instructor = instructor
        self.object.save()
    return HttpResponseRedirect(self.get_success_url())

检查django doc what does save(commit=False) do.

另请查看有关form_valid功能和how forms are handled in class based views.

的django文档