Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: name 'request' is not defined, in Django forms

How do I get the current logged in user in forms.py? I am trying to pre-populate the email field of the current user.

class ContactMe(forms.Form):
    name                 = forms.CharField(label = "Name")
    email_address        = forms.CharField(label = "Email Address", intital = request.user.email)
    subject              = forms.CharField(label = "Subject")
    message              = forms.CharField(label = "Message", widget=forms.Textarea(attrs={'cols': 10, 'rows': 3}))
    additional_comments  = forms.CharField(required = False)
    class Meta:
        model = Contact_me

I tried passing request from views.py as :

contact_form = ContactMe(request.POST or None, request)

and then receiving the request inside of class ContactMe as :

class ContactMe(forms.Form, request):
    name                 = forms.CharField(label = "Name")
    email_address        = forms.CharField(label = "Email Address", intital = **request.user.email**)
    subject              = forms.CharField(label = "Subject")
    message              = forms.CharField(label = "Message", widget=forms.Textarea(attrs={'cols': 10, 'rows': 3}))
    additional_comments  = forms.CharField(required = False)
    class Meta:
        model = Contact_me

It throws the error NameError: name 'request' is not defined. I know request is accessible in html, models.py, views.py. How to get it in forms.py?

The views.py :

def list_posts(request):
    request.session.set_expiry(request.session.get_expiry_age())        # Renew session expire time
    instance_list = Post.objects.all()
    register_form = UserRegisterForm(data=request.POST or None)
    if register_form.is_valid():
        personal.views.register_form_validation(request, register_form)

    login_form = UserLoginForm(request.POST or None)
    if login_form.is_valid() :
        personal.views.login_form_validation(request, login_form)

    feedback_form = FeedbackForm(request.POST or None)
    if feedback_form.is_valid() :
        personal.views.feedback_form_validation(request, feedback_form)

    contact_form = ContactMe(request.POST or None, request)
    if contact_form.is_valid() :
    personal.views.contact_form_validation(request, login_form)

    if request.POST and not(register_form.is_valid() or login_form.is_valid()):
        if request.POST.get("login"):
            return accounts.views.login_view(request)
        else:
            return accounts.views.register_view(request)

    template = 'blog/archives.html'
    dictionary = {

        "object_list"   : content,
        "register_form" : register_form,
        "login_form"    : login_form,
        "feedback_form" : feedback_form,
        "contact_form"  : contact_form,
    }
    return render(request,template,dictionary)
like image 928
sagar_jeevan Avatar asked Mar 20 '17 12:03

sagar_jeevan


Video Answer


2 Answers

You are trying to pass the request when constructing the form class. At this point there is no request. The request only exists inside your view function. You should, therefore, pass the request in your view function when constructing the form instance. To prepopulate the form, you can use the initial keyword of the form constructor. It takes a dictionary of field names and values as input.

Example:

#views.py
from django.shortcuts import render
from django import forms

class TestForm(forms.Form):
    foo = forms.CharField()

def test_form(request):
    form = TestForm(initial=dict(foo=request.<some_property>))
    context = dict(form=form)
    template_name = 'testapp/test.html'
    return render(request, template_name, context)
like image 123
Martin Bierbaum Avatar answered Oct 26 '22 15:10

Martin Bierbaum


This line is wrong class ContactMe(forms.Form, request).

(Hint: request isn't a base class for your form)

The correct way is to access the user in the __init__ method of the form:

class ContactMe(forms.ModelForm):

    class Meta:
         model = Contact_me
         fields = '__all__'

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(ContactMe, self).__init__(*args, **kwargs)

The corresponding line in the views.py:

contact_form = ContactMe(request.POST, user=request.user)
like image 23
arie Avatar answered Oct 26 '22 13:10

arie