[Fixed]-Django: Set initial value for ForiegnKey in a CreateView

1👍

If you want to set the initial value of instructor field, you shouldn’t exclude it from the form. You could instead make the field hidden.

Or you could include that in the exclude list, but then you shouldn’t override get_initial method, but do the assignment manually:

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())

Check django doc about what does save(commit=False) do.

Also check django doc about form_valid function and how forms are handled in class based views.

Leave a comment