In a discussion with yuji-tomita-tomita, he suggested the following, which I would like to share:
The first method is based on its source code by sending user kwarg to the form using get_form_kwargs , then you should change your model model to look like this:
class MyModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = self.kwargs.pop('user', None) super(MyModelForm, self).__init__(*args, **kwargs)
Thus, the original __init__ function receives the arguments that it expects.
But the preferred method that he proposed was:
class MyView(CreateView): def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return super(MyView, self).form_valid(form)
It works very well. When the form.save(commit=False) method executes, it fills self.instance in the form object with the same model instance, it returns to our obj variable. When you update obj by doing obj.user = self.request.user and saving it, the form object has a reference to that exact same object, and therefore the form object is already completed here. When you pass it to the original form_valid CreateView method, it has all the data and will be successfully inserted into the database.
If anyone has another way to do this, I would love to hear about it!
source share