[Answer]-Django models, how to set object owner while saving

1👍

a little change to your model:

owner = models.ForeignKey(User, related_name="owners_friend")

and your views.py

@login_required(login_url='/yourloginurl/')
def save_newfriend(request):
   owner = request.user
   # process friend_form_data       
   new_friend = owner.owners_friend.create(friend=friend_form_data)

this way, you dont need to assign the owner explicitly since you are creating Friend from owner’s object so to speak

Leave a comment