Note: The code below was written for an earlier version of Django (prior to Custom Custom Models ). It contains race status and should only be used with the isolation level of a SERIALIZABLE transaction and a transaction with queries.
Your code will not work because the attributes of the field instances are read-only. I'm afraid this might be a little more complicated than you think.
If you only create user instances with the form, you can define a custom ModelForm that will apply this behavior:
from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model = User def clean_email(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude(username=username).exists(): raise forms.ValidationError(u'Email addresses must be unique.') return email
Then simply use this form wherever you need to create a new user.
By the way, you can use Model._meta.get_field('field_name') to get fields by name, not by position. For example:
UPDATE
Django's documentation recommends using the clean method for all validations, which spans several form fields, because it called after all the <FIELD>.clean and <FIELD>_clean . This means that you can (mostly) rely on the field value present in cleaned_data inside clean .
Since the form fields are checked in the order in which they are declared, I think it is sometimes advisable to place a multi-field check in the <FIELD>_clean , if the field in question appears after all other fields depend on, I I do this, so any validation errors are related to the field itself, and not to the form.
elo80ka Jul 22 '09 at 11:17 2009-07-22 11:17
source share