I have this in my models.py:
class UserManager(BaseUserManager):
def create_user(self, name, password=None):
"""
Creates and saves a User with the given name and password.
"""
if not name:
raise ValueError('A user must have a name.')
user = self.model()
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, name, password):
"""
Creates and saves a staff user with the given name and password.
"""
user = self.create_user(
name,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, name, password, id):
"""
Creates and saves a superuser with the given name and password.
"""
user = self.create_user(
name,
id,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
The reason I added the field id in my create_superuser -method is that it is a required field in my model and I thought I need to include it also when running python manage.py createsuperuser. My problem is that I don't know how to customize the super user creation. With this I always get the error TypeError: create_superuser() missing 1 required positional argument: 'id'. I also tried to remove the id from the function. The process goes through without errors then, but I can't log in to the admin site, it says the username or password are not correct.
I have this in my admin.py:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .forms import UserAdminCreationForm, UserAdminChangeForm
User = get_user_model()
# Remove Group Model from admin. We're not using it.
admin.site.unregister(Group)
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserAdminChangeForm
add_form = UserAdminCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ['name', 'admin']
list_filter = ['admin']
fieldsets = (
(None, {'fields': ('name', 'password')}),
('Personal info', {'fields': ()}),
('Permissions', {'fields': ('admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('name', 'password1', 'password2')}
),
)
search_fields = ['name']
ordering = ['name']
filter_horizontal = ()
admin.site.register(User, UserAdmin)
Do I need to modify the admin.py -file to make this work or is there some other obvious reason why it doesn't work?
In any case, it is really bad practice to give id value manually. the id should be auto-generated. But if you really want to get id as a function parameter, then you need to override the Django command to create a superuser.
You can read the details for the custom Django admin command here.
https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/
Related
I am creating a custom user registration form and I keep getting this error. How do I correct this.
> ProgrammingError at /Identity/register/ (1146, "Table 'nest.auth_user'
> doesn't exist")
I adjusted the authentication system to use email instead of username and I switched from SQlite to Mysql.
# Create models for Identities app.
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
from django.contrib.auth.models import User
# Create your models here.
class UserManager(BaseUserManager):
# Create a model manager for User model with no user name field
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
# Create and save a User with the given email and password
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
# Create and save a regular User with the given email and password.
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
# Create and save a SuperUser with the given email and password.
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class User(AbstractUser):
# User Model
username = None
email = models.EmailField(_('email add '), unique = True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
I registered the User Model:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.utils.translation import ugettext_lazy as _
from .models import User
# Add User profile from models document
from Identities.models import UserProfile
# Register your models here.
#admin.register(User)
class UserAdmin(DjangoUserAdmin):
# Create administration model for custom User model
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
list_display = ('email', 'first_name', 'last_name', 'is_staff')
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email',)
I also created a custom user model and registered the model
class UserProfile(models.Model):
user = models.OneToOneField(User)
contact = models.IntegerField(default=0)
admin.site.register(UserProfile)
I created the register view :
from django.shortcuts import render
from Identities.forms import CreateAccountForm
def register(request):
if request.method == 'POST':
form = CreateAccountForm(request.POST)
if form.is_valid():
form.save()
else:
return redirect(reverse('Identities:logout'))
else:
form = CreateAccountForm()
var = {'form' : form}
return render(request, 'Identities/create_account.html', var)
Then I created the class model in forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CreateAccountForm(UserCreationForm):
email = forms.EmailField(required = True)
class Meta:
model = User
fields = (
'first_name',
'last_name',
'email',
'password1',
'password2'
)
def save(self, commit = True):
user = super(CreateAccountForm, self).save(commit = False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
You need to migrate first
python3 manage.py makemigrations
python3 manage.py migrate
Need to migrate your model files to database...
python manage.py makemigrations
python manage.py migrate
This happened to me when switching from sqlite to mysql. I guess I'd made auth_user on sqlite and it didn't exist on mysql.
A few things seemed to really help me out.
Restarting Apache: sudo systemctl restart apache2
Making a new super user: python3 manage.py createsuperuser.
I got this error: Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
So then I did python3 manage.py makemigrations and python3 manage.py migrate for admin, auth, contenttypes, sessions.
Then again: python3 manage.py createsuperuser.
It fixed it for me.
I also had that error when I referenced my custom User-class in a separate Model via a ForeignKey for example. I set AUTH_USER_MODEL in my settings.py like this:
AUTH_USER_MODEL = "users.User"
I fixed it by using that reference from settings.AUTH_USER_MODEL instead. For this, you need to import it first:
# Replace this
# from users.models import MyUser
# With this
from django.conf import settings
and replace your custom User-model with the one from the settings:
# Replace this
# owner = models.ForeignKey(MyUser, related_name="budgets", on_delete=models.PROTECT)
# With this
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="budgets", on_delete=models.PROTECT)
The custom authentication I wrote follows the instructions from the docs. I am able to register, login, and logout the user, no problem there. Then, when I create a superuser python manage.py createsuperuser, it creates a user in the database, but it does not let me login when I go to the admin page and try to login saying
Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive.
Here is my code:
models.py:
from __future__ import unicode_literals
from django.db import models
from django.db import models
from django.contrib.auth.models import AbstractUser, AbstractBaseUser, Group, Permission
from django.contrib.auth.models import BaseUserManager
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist, MultipleObjectsReturned
from datetime import datetime
from django.contrib.auth.models import PermissionsMixin
import re
class CustomUserManager(BaseUserManager):
def create_user(self, email, password = None):
'''Creates and saves a user with the given email and password '''
if not email:
raise ValueError('Email address is requied.')
user = self.model(email = self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
''' Creates and saves a superuser with the given email and password '''
user = self.create_user(email, password = password)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""
Custom user class
"""
email = models.EmailField(verbose_name = 'email address',unique = True, db_index = True)
# email is the unique field that can be used for identification purposes
first_name = models.CharField(max_length = 20)
last_name = models.CharField(max_length = 30)
joined = models.DateTimeField(auto_now_add = True)
is_active = models.BooleanField(default = True)
is_admin = models.BooleanField(default = False)
is_superuser = models.BooleanField(default = False)
group = models.ManyToManyField(Group, related_name = 'users')
permission = models.ManyToManyField(Permission, related_name = 'users')
objects = CustomUserManager()
USERNAME_FIELD = 'email' # the unique identifier (mandatory) The filed must have unique=True set in its definition (see above)
def get_full_name(self):
return self.email
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
''' Does the user have a specific permission'''
return True # This may need to be changed depending on the object we want to find permission for
def has_module_perms(self, app_label):
''' Does the user have permission to view the app 'app_label'? The default answer is yes.
This may be modified later on. '''
return True
#property
def is_staff(self):
''' IS the user a member of staff? '''
return self.is_admin
def __unicode__(self):
return '{user_email}, {user_title} joined on {joined_date}'.format(user_email = self.email,
user_title = self.user_type,
joined_date = self.joined)
In backends.py:
from django.conf import settings
from django.contrib.auth.hashers import check_password
from accounts.models import User
class EmailAuthBackend(object):
''' Custom authentication backend. Allows users to login using their email address '''
def authenticate(self, email=None, password = None):
''' the main method of the backend '''
try:
user = User.objects.get(email = email)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk = user_id) # Note that you MUST use pk = user_id in getting the user. Otherwise, it will fail and even though the user is authenticated, the user will not be logged in
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
in admin.py:
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from accounts.models import User as CustomUser
class UserCreationForm(forms.ModelForm):
''' A Form for creating new users. Includes all the required field, plus a repeated password.'''
password1 = forms.CharField(label = 'Password', widget = forms.PasswordInput)
password2 = forms.CharField(label = 'Password Confirmation', widget = forms.PasswordInput)
class Meta:
model = CustomUser
fields = ('email',)
def clean_password2(self):
''' Checks that the two password entries match '''
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('Passwords do NOT match!')
return password2
def save(self, commit = True):
''' Save the provided password in hashed format '''
user = super(UserCreationForm, self).save(commit = False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
''' A form for updating users. Includes all the field on the user, but replaces the password field with admin's password hash display field '''
password = ReadOnlyPasswordHashField()
class Meta:
model = CustomUser
fields = ('email', 'password', 'first_name', 'last_name', 'is_active', 'is_admin')
def clean_password(self):
''' Regardless of what the user provides, return the initial value. This is done here rather than on the field because the field
does not have access to the initial value'''
return self.initial['password']
class UserAdmin(BaseUserAdmin):
''' The form to add and change user instances '''
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the user model.
# These override the defintions on the base UserAdmin
# that reference specific fields on auth.User
list_display = ('email', 'first_name', 'last_name', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal Info',{'fields': ('first_name', 'last_name',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user
add_fieldsets = (
(None, {'classes': ('wide',),
'fields': ('email', 'first_name', 'last_name', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Now, register the new UserAdmin...
admin.site.register(CustomUser, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
And, finally, in settings.py:
AUTHENTICATION_BACKENDS = ['accounts.backends.EmailAuthBackend',]
So what's missing?
I think the problem is in your EmailAuthBackend. If you add some printing/logging to the backend, you'll find that the login form calls the authenticate method with username and password. This means that email is None, and therefore the user = User.objects.get(email = email) lookup fails.
In your case, the regular ModelBackend will work fine for you, because you have USERNAME_FIELD = 'email'. If you remove AUTHENTICATION_BACKENDS from your settings then the login should work. You can then remove your EmailAuthBackend.
If you wanted to log in users with their cell number and password (and cell_number was not the USERNAME_FIELD, then you would need a custom authentication backend. You would also need a custom authentication form that called authenticate(cell_number=cell_number, password=password). Another example of a custom authentication backed is RemoteUserBackend, which logs in the user based on an environment variable set by the server.
Had the same issue. Instead of password=None, I changed it to password only. And passed 'password=password' , together with 'username=username' as you can see below:
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password):
if not email:
raise ValueError('Please add an email address')
if not username:
raise ValueError('Please add an username')
user = self.model(email=self.normalize_email(
email), username=username, password=password)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(email=self.normalize_email(
email), username=username, password=password)
And as Denis has already said above, make sure to add AUTH_USER_MODEL = 'accounts.User' to settings.py
I am trying to Custom authentication login with a legacy database. So far I still do not know how to do it. However, when I copy this example code, and try to write some sample code it can work. However, my legacy database is md5 encryption. I now am trying to change my sample code to md5 encryption.
I just
import hashlib
and #out
ReadOnlyPasswordHashField
and in
class UserChangeForm:
change the code
password = hashlib.md5()
admin.py
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
#from django.contrib.auth.forms import ReadOnlyPasswordHashField
import hashlib
from .models import MyUser
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = MyUser
fields = ('email', 'date_of_birth')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
#password = ReadOnlyPasswordHashField()
password = hashlib.md5()
class Meta:
model = MyUser
fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'date_of_birth', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('date_of_birth',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'date_of_birth', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(MyUser, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
however,,when I recreate a user and check my db it is still shows pbkdf2 ??,,
Can any one tell me how to change to md5? Thank you very much!
It doesn't matter what you do in your view. The password will still be hashed according to the settings in PASSWORD_HASHERS. I'm not understanding at all why you need to downgrade to MD5...But if you really need to, you can change this setting in settings.py:
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher',
'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
]
Can I use same authentication system as provided by Django User models for models subclassing Abstract Base User models and, if not, then what else can we do? Also, how to configure ModelAdmin for providing admin access to these models?
The fact that you prefer using Django's built-in authentication system as is, is probably an indicator that substituting a custom User class based on the Abstract Base User model is unnecessary. You might want to consider extending the User class with a one-to-one relationship (how-to from the docs). This will allow you to keep all of Django's default behaviour, as well as add any additional fields, methods, etc. that you would want a User to have. We've found this to be adequate for most of our cases, and far less hassle than creating an entirely new Use class.
Anyways, that being said, you can create a custom authentication by inheriting from BaseUserManager and creating a new manager, then assigning your custom User's objects field to this new manager. Alternatively, you could assign your custom User's objects field to Django's manager. You should only create your own manager if you need some sort of custom authentication (for example, logging in with an email instead of with a username). Here is a link to the docs on how to do that.
To register the custom User model with Django's admin, you'll need to do a few things in your specific app's admin.py file. First, create custom forms for creating and editing Users, then subclass UserAdmin in your custom User Admin class, and reference the forms you previously created. Finally, register the new User Admin using admin.site.register(). Here's a full example of the admin.py file:
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from customauth.models import MyUser
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = MyUser
fields = ('email', 'date_of_birth')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""
A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = MyUser
fields = ['email', 'password', 'date_of_birth', 'is_active', 'is_admin']
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class MyUserAdmin(UserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'date_of_birth', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('date_of_birth',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'date_of_birth', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Now register the new UserAdmin...
admin.site.register(MyUser, MyUserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
Once done with the admin.py file, specify the custom model as your default user model using the AUTH_USER_MODEL variable in your settings.py file.
AUTH_USER_MODEL = 'customauth.MyUser'
I want Django to send an email to user email-address with Login details once admin adds a new user to admin site.So I tried using Django signals for that but just becoz django user registration is a two step process signals get notified in first step only and called email function without email address(which comes in second step).
My signal code:
def email_new_user(sender, **kwargs):
if kwargs["created"]: # only for new users
new_user = kwargs["instance"]
send_mail('Subject here', 'Here is the message.', 'from#example.com',['to#example.com'], fail_silently=False)
post_save.connect(email_new_user, sender=User)
So what i tried to overcome this problem.I use this code in admin.py
class UserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'first_name', 'last_name', 'date_joined', 'last_login')
search_fields = ['username', 'email']
filter_horizontal = ('user_permissions',)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
This makes all registration process a single step process and my signals start working and sending mail to user_id on new user addition.But the problem came after this were:
1. User password is not converted into hash and is visible while entering into form,that makes user not able to login into admin site.
2.Email field in form is not compulsory which I want to be compulsory.
Please help me :(
[EDIT]
I tried your code But I m still at same place where i was before posting this question.
the code i used in my admin.py is:
from django.contrib import admin
from mysite.naturefarms.models import *
from django.contrib.auth.models import User,Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from django.contrib.admin.views.main import *
class MyUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email',)
class UserAdmin(admin.ModelAdmin):
add_form = MyUserCreationForm
admin.site.unregister(User)
class MyUserAdmin(UserAdmin):
add_form = MyUserCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
admin.site.register(User, MyUserAdmin)
If you look in django.contrib.auth admin.py, you'll see that the UserAdmin class specifies the add_form as UserCreationForm.
UserCreationForm only includes the 'username' field from the User model.
Since you're providing your own UserAdmin, you can just override the add_form to a custom UserCreationForm that includes the fields you need to make your signal work properly.
Hope that helps you out.
[Edit]
Here's the UserCreationForm from contrib.auth forms.py:
class UserCreationForm(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."))
class Meta:
model = User
fields = ("username",)
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(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
Notice the fields = ("username",) tuple which excludes all other fields on the User model. You need something like:
class MyUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email',)
then you can use that as the add_form in your custom UserAdmin:
class UserAdmin(admin.ModelAdmin):
add_form = MyUserCreationForm
It's pretty late in my part of the world, but I'll see if I can get a working sample for you tomorrow.
[Edit]
Ok, here's the necessary changes you'll need to make to make this work. I've tested it using Django 1.3:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django import forms
admin.site.unregister(User)
class MyUserAdmin(UserAdmin):
add_form = MyUserCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
admin.site.register(User, MyUserAdmin)
I didn't see that the UserAdmin had an add_fieldset property initially. That's why the email field wasn't displaying in the add form.
From this example try defining email in your custom UserCreationForm as required=True:
class MyUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email',)