[Answered ]-Using current user to initialize ForeignKey user in Django CreateView

2👍

The reason it doesn’t work is because you are missing a required field from your form class; recall that model form validation will also validate the model instance:

Validation on a ModelForm

There are two main steps involved in validating a ModelForm:

Validating the form
Validating the model instance

In your class, the inherited post method is calling is_valid():

def post(self, request, *args, **kwargs):
    """
    Handles POST requests, instantiating a form instance with the passed
    POST variables and then checked for validity.
    """
    form = self.get_form()
    if form.is_valid():
        return self.form_valid(form)
    else:
        return self.form_invalid(form)

You can see that it only calls form_valid() if is_valid() returns true; in your case it can’t return true because you have a required attribute missing.

You can solve this problem easily by making the user foreign key optional in your model.

Leave a comment