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)
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)
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']
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