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

Django: Set initial value for ForiegnKey in a CreateView

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

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

我的看法如下。我认为通过在 initial 中包含 instructor 值会在我提交

时传递配置文件实例
# 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 constraint failed: myapp_course.instructor_id

如果要设置 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())

查看有关 what does save(commit=False) do.

的 django 文档

同时查看有关 form_valid 函数和 how forms are handled in class based views.

的 django 文档