Note that there are some explanatory texts on larger screens.

plurals
  1. POkeeping User.email unique from Django Admin
    text
    copied!<p>I am using Django 1.3/Python 2.7.</p> <p>My application is using django.contrib.auth for User management. For the main user registration I have a form which checks if the 'email' has already been registered. So it makes sure all email fields are unique.</p> <p>But it happens that some admins use the django admin interface to add users, and end up adding duplicate accounts with the same email.</p> <p>For this purpose I have created a NewUserCreationForm, where I've duplicated the django.contrib.auth.UserCreationForm and added an 'email' field to it.</p> <pre><code>class NewUserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$', help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."), error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")}) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, help_text = _("Enter the same password as above, for verification.")) email = forms.EmailField(label=_("Email"), max_length=75) class Meta: model = User fields = ("username", "email") def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(_("A user with that username already exists.")) def clean_password2(self): password1 = self.cleaned_data.get("password1", "") password2 = self.cleaned_data["password2"] if password1 != password2: raise forms.ValidationError(_("The two password fields didn't match.")) return password2 def save(self, commit=True): user = super(NewUserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.email = self.email if commit: user.save() return user class CustomUserAdmin(UserAdmin): add_form = NewUserCreationForm admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) </code></pre> <p>But this code isn't working. I can see the form rendering, but with no email field, just the Username, password1 and password2 fields.</p> <p>what is it that I am missing here?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload