Categories
Python Answers

How to get request data in a Python Django form?

Spread the love

Sometimes, we want to get request data in a Python Django form.

In this article, we’ll look at how to get request data in a Python Django form.

How to get request data in a Python Django form?

To get request data in a Python Django form, we can pass the request object into the form.

For instance, we write

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

to create the UserForm form class.

Then in our view, we write

def someview(request):
    if request.method == 'POST':
        form = UserForm(request.POST, user=request.user)
        if form.is_valid():
            # ...
            pass
    else:
        form = UserForm(user=request.user)

to create the UserForm instance with the user argument set to request.user to populate the form with user data.

And we pass in request.POST to populate the form with POST data.

Conclusion

To get request data in a Python Django form, we can pass the request object into the form.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *