回到顶部

Contents

How to access the HttpRequest object in Django forms( Django view 给 forms 传递数据)

Example 1:

PASSING THE REQUEST OBJECT TO THE FORM

In your view, when you create a form instance, pass the request object as a parameter. Here I used a parameter named request.

form = MyForm(request.POST, request.FILES, request=request)

ACCESSING THE REQUEST OBJECT IN THE FORM

In your form, use the __init__ method to assign the request object to a variable. Here I used self.request.

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(MyForm, self).__init__(*args, **kwargs)

FORM VALIDATION

Now we can use the self.request variable to access the request object inside of our form methods.

In the following example, I used the self.request variable to check if the name of the currently logged user is different from the value of the ‘name’ field.

class MyForm(forms.ModelForm):
    # Use self.request in your field validation
    def clean_name(self):
        if self.cleaned_data['name'] != self.request.user.name:
            raise forms.ValidationError("The name is not the same.")
        return self.cleaned_data['name']

Example 2:

As ars and Diarmuid have pointed out, you can pass request.user into your form, and use it in validating the email. Diarmuid's code, however, is wrong. The code should actually read:

from django import forms

class UserForm(forms.Form):
    email_address = forms.EmailField(widget = forms.TextInput(attrs = {'class':'required'}))

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

    def clean_email_address(self):
        email = self.cleaned_data.get('email_address')
        if self.user and self.user.email == email:
            return email
        if UserProfile.objects.filter(email=email).count():
            raise forms.ValidationError(u'That email address already exists.')
        return email

Then, in your view, you can use it like so:

def someview(request):
    if request.method == 'POST':
        form = UserForm(request.POST, user=request.user)
        if form.is_valid():
            # Do something with the data
            pass
    else:
        form = UserForm(user=request.user)
    # Rest of your view follows

From:

 

^_^
请喝咖啡 ×

文章部分资料可能来源于网络,如有侵权请告知删除。谢谢!
前一篇: drf 启动报错:AssertionError: `coreapi` must be installed for schema support.
下一篇: django.template.exceptions.TemplateDoesNotExist: django_filters/rest_framework/crispy_form.html
captcha