[Answer]-Trouble saving userpic to UserProfile in Django: null value in column "user_id" violates not-null constraint

1👍

Turns out I was going about it all wrong and was creating new profiles rather than adding to an existing one. The problem was fixed by replacing the following lines in views.py:

newuserpic=UserProfile(userpic=request.FILES['userpic'])
newuserpic.save()

…with this:

newuserpic=request.FILES['userpic']
current_profile.userpic=newuserpic
current_profile.save()

Now I’m having issues getting the pic to display properly on the user’s home page, but that’s a whole separate issue that probably has to do with my MEDIA_URL – at least the pic is getting saved properly now!

👤csihar

0👍

In your view.py you have the following code:

if form.is_valid():
   newuserpic=UserProfile(userpic=request.FILES['userpic'])
   newuserpic.save()

but you do not seem to associate the new profile with a user, I suspect this is why the error is raised. Something like

newuserpic.user = request.user

…might do the trick. I’m posting this answer just by reading your code, so please be gentle 🙂

EDIT: If you want to edit the existing profile of the current user instead of creating a new one you should do the following in your view:

if form.is_valid():
   u_profile=request.user.get_profile()
   u_profile.userpic = request.FILES['userpic']
   u_profile.save()

We first access the user profile, then edit the userpic property and finally save it.

Leave a comment