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

2023-02-18 14:48:22 浏览数 (1)

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.

代码语言:javascript复制
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.

代码语言:javascript复制
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.

代码语言:javascript复制
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:

代码语言:javascript复制
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:

代码语言:javascript复制
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:

  • https://brunobastos.net/how-to-access-the-httprequest-object-in-django-forms/
  • https://stackoverflow.com/questions/1202839/get-request-data-in-django-form

0 人点赞