Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

338
Views
How can you use a request.user in model form in django?

I want to be able to use the request.user in the model form init. Here is my view:

def create(request, pk):    
    if request.method == 'POST':
        form = CreateForm(request.POST)
        if form.is_valid():
            object = form.save()
            object.save()
            return render(request, 'going_create.html', {'object':object})
    else:
        form = CreateForm()
    return render(request, 'being_create.html', {'form':form})

Basically, I need request.user to prefill a django form field. Here is my form:

class CreateForm(forms.ModelForm):
    
    def __init__(self, *args, **kwargs):

        self.request = kwargs.pop('request')
        super(CreateForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].initial = self.request.user.first_name

    class Meta:
        model = creater
        fields = (
            'first_name',
        )

Also, there are form = CreateForm(request.POST) if request.method == 'POST', and form = CreateForm() when else. So, as I am not familiar with using a function view, I hope you could tell me where I need to add the code so that I could use request.user to prefill a django field. Thank you, and please leave any questions you have.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You pass it though a parameter:

class CreateForm(forms.ModelForm):
    
    def __init__(self, *args, user=None, **kwargs):
        super(CreateForm, self).__init__(*args, **kwargs)
        if user is not None:
            self.fields['first_name'].initial = user.first_name

    class Meta:
        model = creater
        fields = (
            'first_name',
        )

In the view you then construct the form with:

from django.contrib.auth.decorators import login_required

@login_required
def create(request, pk):    
    if request.method == 'POST':
        form = CreateForm(request.POST, user=request.user)
        if form.is_valid():
            object = form.save()
            return render(request, 'going_create.html', {'object':object})
    else:
        form = CreateForm(user=request.user)
    return render(request, 'being_create.html', {'form':form})

Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!