views:

261

answers:

2

My question is very similar to this question: http://stackoverflow.com/questions/862522/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?

+3  A: 

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
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
Remember to check if the user it logged in in your view.The <code>@login_required</code> decorator is quite nice for this :-)
Klette
Well, you could insert the user_id into a hidden field in the form, but this is the way in normally done.
Klette
Right-O, What do you think about the answer from piquadrat?
TheLizardKing
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
A: 

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

if form.is_valid():
    form.instance.user = request.user
    form.save()
    return redirect('home')
piquadrat