5👍
✅
You don’t need to pass the user to the form, so don’t override the get_form
method. You have already excluded the user field
from the model form by setting fields
in your view, so you shouldn’t need a custom model form either.
It should be enough to override the form_valid
method, and set the user when the form is saved.
from django.http import HttpResponseRedirect
class CreateMeasurement(CreateView):
model = Measurement
fields = ['date']
success_url = reverse_lazy('list_measurements')
def form_valid(self, form):
obj = form.save(commit=False)
obj.user = self.request.user
obj.save()
return HttpResponseRedirect(self.get_success_url())
Source:stackexchange.com