Search code examples
djangoformsintegration-testing

How do i auto-populate fields in django?


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?


Solution

  • 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()
    
        #...