[Fixed]-Django 1.8: add user to Modelform in views: not null constraint failed

1👍

You shouldn’t do form.user = request.user.username, because form.user won’t add the user to the form. You should capture the object that form.save(commit=false) returns, then assign the user to that object and save it.

Also you cannot assign a user field with username, username is only a string not User object. You should do this instead:

if form.is_valid():
    userprofile = form.save(commit=False)
    userprofile.user = request.user
    userprofile.save()

Leave a comment