tags:

views:

1386

answers:

3

I have a model Question with a field called userid, before one ask a question, one needs to login, i want when saving to capture the user ID of the currently logged-in user and assign it to the userid of the Question model.

Please note am not showing the userid on my form i.e. in the Question model i have declared the userid as follows;

class Question(models.Model): ... userid=models.ForeignKey(User, editable=false) ...

How do i assign logged-in user ID to the Question model userid?

+5  A: 

Your code may look like this:

from django.contrib.auth.decorators import login_required

class QuestionForm(forms.ModelForm):
    class Meta:
         model = Question

@login_required
def ask(request):
    form = QuestionForm(request.POST)

    if form.is_valid():
        question = form.save(False)
        question.userid = request.user
        question.save()

    #...
Alex Koshelev
Thank you! Was about to post a similar question, but this solved it
f4nt
A: 

One thing to keep in mind is the fact, that you can't access the request object (and therefore the current user) from you models without hacking around django's design constrains.

Therefore neat tricks like automatically populating fields like created_by and updated_by don't work from Django. You have to set such fields manually in your views as illustrated by @Daevaorn.

mdorseif
A: 

This blog entry (by James Bennett) might prove useful for you as well...it lays out a way to do almost exactly what you require.

bkev