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

Note that you should pass request.POST as a keyword argument, since your constructor expects 'user' as the first positional argument.

Doing it this way, you need to pass user as a keyword argument. You can either pass request.POST as a positional argument, or a keyword argument (via data=request.POST).

Answer from elo80ka on Stack Overflow
Top answer
1 of 6
80

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

Note that you should pass request.POST as a keyword argument, since your constructor expects 'user' as the first positional argument.

Doing it this way, you need to pass user as a keyword argument. You can either pass request.POST as a positional argument, or a keyword argument (via data=request.POST).

2 of 6
45

Here's the way to get the user in your form when using generic views:

In the view, pass the request.user to the form using get_form_kwargs:

class SampleView(View):
    def get_form_kwargs(self):
        kwargs = super(SampleView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

In the form you will receive the user with the __init__ function:

class SampleForm(Form):
    def __init__(self, user, *args, **kwargs):
        super(SampleForm, self).__init__(*args, **kwargs)
        self.user = user
Top answer
1 of 8
29

I have some sample code from a recent project of mine that I believe may help you. In this example, super users can edit every field, while everyone else has the "description" field excluded.

Note that I think it's expected that you return a Form class from get_form, which could be why yours was not working quite right.

Here's the example:

class EventForm(forms.ModelForm):
    class Meta:
        model = models.Event
        exclude = ['description',]

class EventAdminForm(forms.ModelForm):
    class Meta:
        model = models.Event

class EventAdmin(admin.ModelAdmin):

    def get_form(self, request, obj=None, **kwargs):
        if request.user.is_superuser:
            return EventAdminForm
        else:
            return EventForm 

admin.site.register(models.Event, EventAdmin)
2 of 8
15

I have no idea why printing the property doesn't give you want you just assigned (I guess may be that depends on where you print, exactly), but try overriding get_fieldsets instead. The base implementation looks like this:

def get_fieldsets(self, request, obj=None):
    if self.declared_fieldsets:
        return self.declared_fieldsets
    form = self.get_formset(request).form
    return [(None, {'fields': form.base_fields.keys()})]

I.e. you should be able to just return your tuples.

EDIT by andybak. 4 years on and I found my own question again when trying to do something similar on another project. This time I went with this approach although modified slightly to avoid having to repeat fieldsets definition:

def get_fieldsets(self, request, obj=None):
    # Add 'item_type' on add forms and remove it on changeforms.
    fieldsets = super(ItemAdmin, self).get_fieldsets(request, obj)
    if not obj: # this is an add form
        if 'item_type' not in fieldsets[0][1]['fields']:
            fieldsets[0][1]['fields'] += ('item_type',)
    else: # this is a change form
        fieldsets[0][1]['fields'] = tuple(x for x in fieldsets[0][1]['fields'] if x!='item_type')
    return fieldsets
Discussions

python - Creating forms with method="get" in django - Stack Overflow
I have a form containing two text input types. The value from both the forms are passed onto the view myfunc which then passes it on to another template.the url of the form results should be /app/1/ More on stackoverflow.com
🌐 stackoverflow.com
August 9, 2016
python - How to get value from form field in django framework? - Stack Overflow
How do I get values from form fields in the django framework? I want to do this in views, not in templates... More on stackoverflow.com
🌐 stackoverflow.com
Django form as GET - Stack Overflow
I want to have my site having form validation and xml generation by using GET. There will be no form rendering as HTML to fill, simply request will be a GET that parameters are generated automatica... More on stackoverflow.com
🌐 stackoverflow.com
November 11, 2011
get_form() not working on a Dynamic Form
You should use either formsets or use a custom field that allows multiple values. The former is probably the easiest More on reddit.com
🌐 r/django
2
1
August 3, 2024
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn › Server-side › Django › Forms
Django Tutorial Part 9: Working with forms - Learn web development | MDN
November 24, 2024 - Django's form handling uses all of the same techniques that we learned about in previous tutorials (for displaying information about our models): the view gets a request, performs any actions required including reading data from the models, then generates and returns an HTML page (from a template, into which we pass a context containing the data to be displayed).
🌐
Django
docs.djangoproject.com › en › 6.0 › topics › forms
Working with forms | Django documentation | Django
Django’s login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET, by contrast, bundles the submitted data into a string, and uses this to compose a URL.
🌐
GeeksforGeeks
geeksforgeeks.org › render-html-forms-get-post-in-django
Render HTML Forms (GET & POST) in Django - GeeksforGeeks
One of the essential components in web development is handling HTML forms, a way for users to send data to the server for processing ... A widget is Django’s representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget.
Published   May 17, 2025
🌐
GeeksforGeeks
geeksforgeeks.org › python › render-html-forms-get-post-in-django
Handling HTML Forms in Django: GET and POST Methods - GeeksforGeeks
Requires CSRF protection in Django using {% csrf_token %}. Consider a project named 'geeksforgeeks' having an app named 'geeks'. ... <form action="" method="GET"> <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name"> <input type="submit" value="OK"> </form>
Published   January 16, 2026
Find elsewhere
🌐
Django Documentation
docs.djangoproject.com › en › 5.1 › ref › class-based-views › mixins-editing
Editing mixins | Django documentation | Django
Renders a response, providing the invalid form as context. ... Calls get_form() and adds the result to the context data with the name ‘form’.
🌐
Matthew Downey
matthewdowney.github.io › django-modify-admin-form-from-request.html
Modify a form in the Django admin panel based on the request | Matthew Downey
November 2, 2017 - @admin.register(Something) class SomethingAdmin(admin.ModelAdmin): form = SomethingForm fields = ('ownery', 'name') def get_form(self, request, obj=None, **kwargs): form = super(SomethingAdmin, self).get_form(request, obj=obj, **kwargs) # Do something here ...
🌐
DjangoGirls
tutorial.djangogirls.org › en › django_forms
Django Forms · HonKit
This is exactly what we want to do: we will create a form for our Post model. Like every important part of Django, forms have their own file: forms.py.
🌐
TutorialsPoint
tutorialspoint.com › home › django › django form processing
Django - Form Processing
February 13, 2026 - #-*- coding: utf-8 -*- from django import forms class LoginForm(forms.Form): user = forms.CharField(max_length = 100) password = forms.CharField(widget = forms.PasswordInput()) As seen above, the field type can take "widget" argument for html rendering; in our case, we want the password to be hidden, not displayed. Many others widget are present in Django: DateInput for dates, CheckboxInput for checkboxes, etc. There are two kinds of HTTP requests, GET and POST.
🌐
Learning About Electronics
learningaboutelectronics.com › Articles › How-to-retrieve-data-from-a-Django-form-Python.php
Python- How to Retrieve Data from a Django Form
We create the variable, emailvalue, and set it equal to form.cleaned_data.get('email'). This retrieves the data that the user entered into the email form field. These are all of our variables. We then pass them into the template file through the context dictionary. This is how we are then able to render out the results in the template file. And this is how we can retrieve data from a Django form.
🌐
GeeksforGeeks
geeksforgeeks.org › django-forms
Django Forms - GeeksforGeeks
Django is a fully fleshed framework which can help you create web applications of any form. This article discusses how to get parameters passed by URLs in django views in order to handle the function for the same.
Published   May 27, 2025
🌐
Django
docs.djangoproject.com › en › 3.2 › ref › forms › api
The Forms API | Django documentation | Django
October 22, 2021 - When the Form is valid, cleaned_data will include a key and value for all its fields, even if the data didn’t include a value for some optional fields. In this example, the data dictionary doesn’t include a value for the nick_name field, but cleaned_data includes it, with an empty value: >>> from django import forms >>> class OptionalPersonForm(forms.Form): ...
🌐
Reddit
reddit.com › r/django › get_form() not working on a dynamic form
r/django on Reddit: get_form() not working on a Dynamic Form
August 3, 2024 -

I have a form with a single CharField: pages = forms.CharField()

I'm then rendering that form on the frontend but using JavaScript to duplicate the field so a user can clone that field x amount of times on the frontend. When the user submits it I'm only able to get the last field using the below:

def post(self, request):
 form = self.get_form()
     print(form)

I think the issue is caused because form setup in Django only has a single field but when it's been submitted then there are more than 1 so self.get_form() is only getting the last field?

When I print(request.__dict__) I can see that all fields are being posted

 '_post': <QueryDict: {'pages': ['a', 'b', 'c']}>

I'm not sure how to go about solving this issue. I could just extract the submission from the above QueryDict but then I won't be able to do: if form.is_valid()

Any advice on how I should tackle this issue? Should I just get it from the _post since it's just a CharField()? I'm still learning so I'd rather implement a proper solution than a hacky one.

🌐
GitHub
github.com › django › django › blob › main › django › views › generic › edit.py
django/django/views/generic/edit.py at main · django/django
from django.views.generic.detail import ( BaseDetailView, SingleObjectMixin, SingleObjectTemplateResponseMixin, ) · · class FormMixin(ContextMixin): """Provide a way to show and handle a form in a request.""" · initial = {} form_class = None · success_url = None · prefix = None · · def get_initial(self): """Return the initial data to use for forms on this view.""" return self.initial.copy() ·
Author   django
🌐
Django Forum
forum.djangoproject.com › using django
How to read non-Django HTML form data? - Using Django - Django Forum
July 19, 2021 - In the past I’ve used an idiom like this to retrieve Django Form data: if request . method == 'POST': form = MyForm ( request . POST ) if form . is_valid (): user_name = form . cleaned_data [ "user_name" ] user_email = form . cleaned_data [ "user_email" ] # etc.
🌐
Real Python
realpython.com › django-social-forms-4
Build and Submit HTML Forms With Django – Part 4 – Real Python
September 19, 2022 - If the view function was called due to an HTTP GET request, you’ll jump right over this whole code block into line 10 and render the page with an empty form in line 11. Line 5: You fill DweetForm with the data that came in through the POST request. Based on your setup in forms.py, Django will pass the data to body.