2

My question is very similar to this question: Django: Populate user ID when saving a model

Unfortunately I did not quite understand their answer.

When a user logs in I want them to be able to submit a link and I have a user_id foreign key that I just can't seem to get to populate.

def submit(request):
    if request.method == 'POST':
        form = AddLink(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = AddLink()

    return render_to_response('links/submit.html', {'form': form})

Everytime I submit my form it mentions:

null value in column "user_id" violates not-null constraint

Which I understand but what I don't know how to add user_id to the my form object. How can I access the currently logged in user's id and submit it along with my form data?

Community
  • 1
  • 1
TLK
  • 29
  • 1
  • 2

2 Answers2

12

You can do something like this:

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

commit=False allows you to modify the resulting object before it is actually saved to the database.

Klette
  • 286
  • 1
  • 9
  • I saw that... Is this the best way of doing it? Something like this seems really common and I figure their would of been something "automatic." – TheLizardKing Feb 08 '10 at 00:24
  • Remember to check if the user it logged in in your view. The @login_required decorator is quite nice for this :-) – Klette Feb 08 '10 at 00:25
  • Well, you could insert the user_id into a hidden field in the form, but this is the way in normally done. – Klette Feb 08 '10 at 00:26
  • Right-O, What do you think about the answer from piquadrat? – TheLizardKing Feb 08 '10 at 00:28
  • Well, it works :-) It's up to you which way seems best, both will work, but the commit=False method is the documented way of doing this. – Klette Feb 08 '10 at 00:34
  • @Klette: Inserting the user_id into a hidden form field is UNSAFE: a malicious user could insert a different user_id than his own. – Quant Metropolis Jun 08 '14 at 15:25
6

replace your if form.is_valid()-block with this:

if form.is_valid():
    form.instance.user = request.user
    form.save()
    return redirect('home')
Benjamin Wohlwend
  • 30,958
  • 11
  • 90
  • 100
  • I am using the way you suggested, an it works. What I am failing at, is to save user id in child model instance. I am using model forms and inline formset for creating related model instances. Any suggestions? – shaan Nov 08 '20 at 13:20