NameError:name' request'在Django表单中没有定义

时间:2017-03-20 12:48:42

标签: python django django-forms django-views

如何在forms.py中获取当前登录用户?我正在尝试预先填充当前用户的电子邮件字段。

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

我尝试将views.py的请求传递为:

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

然后在类ContactMe内接收请求:

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

它会抛出错误NameError: name 'request' is not defined。我知道请求可以在htmlmodels.pyviews.py中访问。如何在forms.py中获取它?

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)

3 个答案:

答案 0 :(得分:3)

此行错误class ContactMe(forms.Form, request)

(提示:request不是您表单的基类)

正确的方法是访问表单user方法中的__init__

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)

views.py中的相应行:

contact_form = ContactMe(request.POST, user=request.user)

答案 1 :(得分:3)

您正在尝试在构造表单类时传递request。此时没有请求。请求仅存在于您的视图函数中。因此,在构造表单实例时,您应该在视图函数中传递请求。要预填充表单,可以使用表单构造函数的initial关键字。它需要字段名称和值的字典作为输入。

示例:

#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)

答案 2 :(得分:0)

如果您编写 requests 而不是 request

,也会出现此错误

示例

在 views.py

def all_products(requests):
    products = Product.objects.all()
    return render(request, 'store/home.html', {'products': products})

应该是:

def all_products(request):
    products = Product.objects.all()
    return render(request, 'store/home.html', {'products': products})

这是我的问题,这就是我提出来的原因。