Django custom user creation not showing custom fields in admin site - python

I'm trying to create a cutom user in my Django with custom fields required like first_name, last_name, date_of_birth, gender, email, etc. So for this I overrided AbstractBaseUser for my custom user, UserCreationForm for creating new user and UserChangeForm changing user's field values.
Models.py
class AppUserManager(BaseUserManager):
"""
Manager for class AppUser
"""
def _create_user(self, username, password, first_name, last_name,
date_of_birth, email, gender, is_staff, is_superuser,
**extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
email = self.normalize_email(email)
user = self.model(username=username,
first_name=first_name, last_name=last_name,
date_of_birth=date_of_birth, email=email, gender=gender,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, password, first_name, last_name, date_of_birth, email, gender, **extra_fields):
return self._create_user(username, password, first_name, last_name,
date_of_birth, email, gender, False, False,
**extra_fields)
def create_superuser(self, username, password, first_name, last_name, date_of_birth, email, gender, **extra_fields):
return self._create_user(username, password, first_name, last_name,
date_of_birth, email, gender, True, True,
**extra_fields)
class AppUser(AbstractBaseUser, PermissionsMixin):
"""
User for Application
"""
username = models.CharField(verbose_name='username', max_length=30, unique=True,
help_text='Required. 30 characters or fewer. Letters, digits and '
'#/./+/-/_ only.',
validators=[
validators.RegexValidator(r'^[\w.#+-]+$', 'Enter a valid username.', 'invalid')
])
first_name = models.CharField(verbose_name='first name', max_length=30)
last_name = models.CharField(verbose_name='last name', max_length=30)
date_of_birth = models.DateField(verbose_name='birth date')
email = models.EmailField(verbose_name='email address', unique=True)
GENDER_CHOICES = (
('m', 'Male'),
('f', 'Female'),
)
gender = models.CharField(verbose_name='gender', max_length=1, choices=GENDER_CHOICES)
is_staff = models.BooleanField(verbose_name='staff status', default=False,
help_text='Designates whether the user can log into this admin '
'site.')
is_active = models.BooleanField(verbose_name='active status', default=True,
help_text='Designates whether this user should be treated as '
'active. Un select this instead of deleting accounts.')
date_joined = models.DateTimeField(verbose_name='date joined', default=timezone.now)
objects = AppUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['first_name', 'last_name', 'date_of_birth', 'email', 'gender']
class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'
db_table = 'app_users'
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"""Returns the short name for the user."""
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email], **kwargs)
admin.py
class CustomUserCreationForm(UserCreationForm):
"""
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)
first_name = forms.CharField(label='First Name') # Custom Required Field. and other fields should go same way
class Meta(UserCreationForm.Meta):
model = AppUser
fields = ('username', 'first_name', 'last_name', 'date_of_birth', 'email', 'gender')
def clean_username(self):
username = self.cleaned_data["username"]
try:
AppUser.objects.get(username=username)
except AppUser.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
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 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 CustomUserChangeForm(UserChangeForm):
password = ReadOnlyPasswordHashField(label="password",
help_text="""Raw passwords are not stored, so there is no way to see this
user's password, but you can change the password using <a href=\"password/\">
this form</a>.""")
class Meta(UserChangeForm.Meta):
model = AppUser
fields = (
'username', 'first_name', 'last_name', 'date_of_birth', 'email', 'gender',
'password', 'is_active', 'is_staff', 'is_superuser', 'user_permissions'
)
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 AppUserAdmin(UserAdmin):
"""
"""
form = CustomUserChangeForm
add_form = CustomUserCreationForm
list_display = ('username', 'first_name', 'last_name', 'email',)
list_filter = ('is_superuser',)
fieldsets = (
(None, {'fields': (
'username', 'first_name', 'last_name', 'date_of_birth', 'email', 'gender',
)}),
('Permissions', {'fields': (
'is_active', 'is_superuser', 'is_staff',
)}),
)
search_fields = ('username', 'email', 'first_name', 'last_name',)
ordering = ('username', 'email',)
admin.site.register(AppUser, AppUserAdmin)
I created a superuser from command line. But User add form only shows: Username, Password and Password Confirmation fields.
So how can I get fields in create user form having required fields displayed?
After submitting this gives me error:
Exception Type: IntegrityError at /admin/users/appuser/add/
Exception Value: Column 'date_of_birth' cannot be null

That's the correct form for adding a user. As the help text on top of the form states, the username and password are set first, then you will see the rest of the fields. If you edit an existing user you will also see everything.

in your AppUserAdmin add
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'first_name', 'last_name', 'gender', .........
'password1', 'password2')}
),
)
Of course add all of your required fields in the dots place. add_fieldsets is responsible for visible fields on django admin user creation site

Related

Django: How to create superuser with custom fields?

I have a custom User model in my models.py and custom UserManager as well. My custom User model has username field with changed name to login and same is updated in UserManager as well. Everything goes fine, but when I try to create superuser using command python manage.py createsuperuser, it asks for login but it does not ask for email which at the end gives me this error:
TypeError: UserManager.create_superuser() missing 1 required positional argument: 'email'
My custom User model is:
class User(AbstractBaseUser, PermissionsMixin):
login = models.CharField(max_length=254, unique=True)
email = models.EmailField(max_length=254, unique=True)
first_name = models.CharField(max_length=254, null=True, blank=True)
last_name = models.CharField(max_length=254, null=True, blank=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'login'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.pk)
My custom UserManager is:
class UserManager(BaseUserManager):
def _create_user(self, login, email, password, is_staff, is_admin, **extra_fields):
if not email:
raise ValueError('Users must have an email address')
now = timezone.now()
email = self.normalize_email(email)
user = self.model(
login=login,
email=email,
is_staff=is_staff,
is_active=True,
is_admin=is_admin,
last_login=now,
date_joined=now,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, login, email, password, **extra_fields):
user = self._create_user(login, email, password, False, False, **extra_fields)
user.save(using=self._db)
return user
def create_superuser(self, login, email, password, **extra_fields):
user=self._create_user(login, email, password, True, True, **extra_fields)
return user
and in admin.py I have:
class UserAdmin(BaseUserAdmin):
fieldsets = (
(None, {'fields': ('login', 'email', 'password', 'first_name', 'last_name', 'last_login')}),
('Permissions', {'fields': (
'is_active',
'is_staff',
'is_admin',
'groups',
'user_permissions',
)}),
)
add_fieldsets = (
(
None,
{
'classes': ('wide',),
'fields': ('login', 'email', 'password1', 'password2')
}
),
)
list_display = ('login', 'email', 'first_name', 'last_name', 'is_admin', 'last_login')
list_filter = ('is_staff', 'is_admin', 'is_active', 'groups')
search_fields = ('email', 'login',)
ordering = ('email', 'login',)
filter_horizontal = ('groups', 'user_permissions',)
I just had to add 'email' in the REQUIRED_FIELDS variable in my User model definition. i.e.
I had to change following line:
REQUIRED_FIELDS = []
to
REQUIRED_FIELDS = ['email']

Matching Query Error while trying to make Case Insensitive Usernames in Django

I'm trying to Override the user model to make usernames case insensitive and allow semicolons. I haven't added the code for semicolons yet. I am getting a matching query error while trying to create a superuser.
When I run python manage.py createsuperuser I get a matching query error
Here is my code
models.py
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager
)
class UserManager(BaseUserManager):
def get_by_natural_key(self, username):
return self.get(**{self.model.USERNAME_FIELD + '__iexact': username})
def create_user(self, username, password=None, is_active=True, is_staff=False, is_admin=False):
if not username:
raise ValueError("Users must have an username address")
if not password:
raise ValueError("Users must have a password")
user_obj = self.model(
username = self.get_by_natural_key(username)
)
user_obj.set_password(password) # change user password
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.active = is_active
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self, username, password=None):
user = self.create_user(
username,
password=password,
is_staff=True
)
return user
def create_superuser(self, username, password=None):
user = self.create_user(
username,
password=password,
is_staff=True,
is_admin=True
)
return user
class User(AbstractBaseUser):
username = models.CharField(max_length=255, unique=True)
#full_name = models.CharField(max_length=255, blank=True, null=True)
active = models.BooleanField(default=True) # can login
staff = models.BooleanField(default=False) # staff user non superuser
admin = models.BooleanField(default=False) # superuser
timestamp = models.DateTimeField(auto_now_add=True)
# confirm = models.BooleanField(default=False)
# confirmed_date = models.DateTimeField(default=False)
USERNAME_FIELD = 'username' #username
# USERNAME_FIELD and password are required by default
REQUIRED_FIELDS = [] #['full_name'] #python manage.py createsuperuser
objects = UserManager()
def __str__(self):
return self.username
def get_full_name(self):
return self.username
def get_short_name(self):
return self.username
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
def is_staff(self):
return self.staff
def is_admin(self):
return self.admin
def is_active(self):
return self.active
admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
User = get_user_model()
class UserAdmin(BaseUserAdmin):
list_display = ('username', 'admin')
list_filter = ('admin', 'staff', 'active')
fieldsets = (
(None, {'fields': ('username', 'password')}),
('Personal info', {'fields': ()}),
('Permissions', {'fields': ('admin', 'staff', 'active',)}),
)
# 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': ('username', 'password1', 'password2')}
),
)
search_fields = ('username',)
ordering = ('username',)
filter_horizontal = ()
admin.site.register(User, UserAdmin)
Here is the error that I'm getting
account.models.DoesNotExist: User matching query does not exist.

django custom user model user creation issue: permissions not working

I'm making a custom user model in django, but somehow any new users created through the creation form is missing their assigned permissions (is_active, is_staff, is_admin), preventing them from logging in at all.
Can anyone show me where did I go wrong? Any suggestion is greatly appreciated!
Code snippets:
models.py
class MyUserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, ID, name, email, privilege, password=None):
if not ID:
raise ValueError('Users must have a ID number')
user = self.model(
ID=ID,
name=name,
email=self.normalize_email(email),
privilege=privilege,
)
if self.privilege == 'Admin':
self.is_superuser = True
else:
user.is_active = True
user.is_staff = False
user.is_admin = False
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, NIP, name, email, privilege, password):
new_user = self.create_user(
ID,
name,
email,
privilege,
password=password,
)
new_user.is_superuser = True
new_user.save(using=self._db)
return new_user
class employee(AbstractBaseUser, PermissionsMixin):
ID = models.IntegerField(verbose_name="ID", unique=True)
name = models.CharField(verbose_name="Name", max_length=50, blank=True, unique=True)
email = models.EmailField(verbose_name="email", max_length=225, default='this#mail.com')
Department = models.CharField(max_length=50, choices=DEP_CHOICES, default='')
Role = models.CharField(max_length=50, choices=ROLE_CHOICES, default='')
privilege = models.CharField(max_length=10, default='User')
is_admin = models.BooleanField()
is_staff = models.BooleanField()
is_active = models.BooleanField()
forms.py
class CustomUserCreationForm(UserCreationForm):
ID = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput)
class Meta(UserCreationForm):
model = employee
fields = "__all__"
class CustomUserChangeForm(UserChangeForm):
ID = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = employee
fields = "__all__"
admin.py
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
add_form = CustomUserChangeForm
form = CustomUserChangeForm
model = employee
list_display = ('ID', 'name', 'email', 'privilege')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('ID', 'password')}),
('Personal info', {'fields': ('name', 'email', 'privilege')}),
('Permissions', {'fields': ('is_admin', 'is_staff', 'is_active')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('ID', 'name', 'email')}
),
)
search_fields = ('name',)
ordering = ('ID',)
filter_horizontal = ()
views.py
def employee_list(request):
data_list = Employee.objects.order_by('NIP')
registered = False
if request.method == "POST":
if 'add_user' in request.POST:
user_form = CustomUserCreationForm(request.POST, prefix='add')
if user_form.is_valid():
new_user = user_form.save()
new_user.set_password(user.password)
new_user.save()
registered = True
return HttpResponseRedirect(reverse('employee'))
else:
user_form = CustomUserCreationForm(prefix='add')
return render(request, 'employee_list.html',
{'SignUpForm': user_form,
'registered': registered,
'Emp_list':data_list})
Instead of using 'priviledge' as a character field in the Employee model, which is very prone to error in user input, use a choice field instead.
class MyUserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, name, email, privilege='member', is_admin=False, is_staff=False, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
name=name,
email=self.normalize_email(email),
privilege=privilege,
)
user.set_password(password)
user.is_active = True
user.is_staff = is_staff
user.is_admin = is_admin
user.save(using=self._db)
return user
def create_superuser(self, name, email, password):
new_user = self.create_user(
name,
email,
privilege='admin',
password=password,
is_staff=True,
is_admin=True
)
return new_user
class Employee(AbstractBaseUser):
PRIVILEGE_LEVEL = (
('Administrator', 'admin'),
('Staff', 'staff'),
('Member', 'member'),
)
# ID = models.IntegerField(verbose_name="ID", unique=True)
id = models.AutoField(primary_key=True)
name = models.CharField(verbose_name="Name", max_length=50, blank=True, unique=True)
email = models.EmailField(verbose_name="email", max_length=225, default='this#mail.com')
Department = models.CharField(max_length=50, choices=DEP_CHOICES, default='')
Role = models.CharField(max_length=50, choices=ROLE_CHOICES, default='')
# privilege = models.CharField(max_length=10, default='User')
privilege = models.CharField(max_length=120, choices=PRIVILEGE_LEVEL, default='member')
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
Also, 'id' is auto generated by django as the primary key field, so it doesnt have to be in the frontend form.
By default the django model form calls MyUserManager.create_user.
and based on the modifications i made above, it defaults to creating a user
without permissions. Unless is_admin and is_staff are implicitly set to True
To create a superuser from your current form, you can update MyUserManager.create_user like so,
def create_user(self, name, email, privilege='member', is_admin=False, is_staff=False, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
name=name,
email=self.normalize_email(email),
privilege=privilege,
)
user.set_password(password)
user.is_active = True
user.is_staff = is_staff
user.is_admin = is_admin
if privilege == 'admin':
user.is_superuser = True
user.save(using=self._db)
return user
But i would advise you update your CustomUserCreationForm instead as such,
class CustomUserCreationForm(UserCreationForm):
# ID = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput)
class Meta(UserCreationForm):
model = Employee
fields = "__all__"
# ADD THIS
def clean(self, value):
print(self.data)
print(self.errors)
cleaned_data = self.cleaned_data
print(cleaned_data)
return cleaned_data
# ADD THIS
def save(self, *args, **kwargs):
data = self.cleaned_data
# email, password1 = v['email'], v['password1']
employee = None
if data['privilege'] == 'admin':
employee = Employee.objects.create_superuser(
name=data['name'],
email=data['email'],
password=data['password'],
)
else:
employee = Employee.objects.create_user(
name=data['name'],
email=data['email'],
password=data['password'],
)
# User is already saved after calling BaseUserManager function.
return employee
MyUserManager.create_superuser calls the MyUserManager.create_user and updates it based on parameter passed to it.
Let me know if you need further clarifications. Cheers.

django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'username'")

I have the following custom user model implementation in my Django application :
users/models.py
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email: str,
password: str, is_staff: bool,
is_superuser: bool, **extra_fields):
"""Creates and saves a User with the given email and password.
"""
email = self.normalize_email(email)
user = self.model(email=email, is_staff=is_staff, is_active=True,
is_superuser=is_superuser, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email: str, password=None, **extra_fields):
return self._create_user(email, password, False, False, **extra_fields)
def create_superuser(self, email: str, password: str, **extra_fields):
return self._create_user(email, password, True, True, **extra_fields)
class User(AbstractUser, UUIDModel):
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
email = models.EmailField(unique=True, db_index=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email'
objects = UserManager()
class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'
ordering = ('-date_joined', )
def get_full_name(self):
return "{} {}".format(self.first_name, self.last_name)
def get_short_name(self):
return self.first_name
def get_email(self):
return self.email
def __str__(self):
return "{}".format(self.email)
And my change form in admin.py looks like this :
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.auth.forms import UserChangeForm as DjangoUserChangeForm
from django.contrib.auth.forms import UserCreationForm as DjangoUserCreationForm
from .models import User
# Forms
# ----------------------------------------------------------------------------
class MyUserCreationForm(DjangoUserCreationForm):
class Meta:
model = User
fields = ("email",)
class MyUserChangeForm(DjangoUserChangeForm):
class Meta:
model = User
fields = '__all__'
# ModelAdmins
# ----------------------------------------------------------------------------
#admin.register(User)
class UserAdmin(AuthUserAdmin):
add_form_template = 'admin/auth/user/add_form.html'
model = User
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'),
}),
)
readonly_fields = ('date_joined', 'last_login')
form = MyUserChangeForm
add_form = MyUserCreationForm
list_display = ('email', 'first_name', 'last_name', 'is_active')
list_filter = ('is_superuser', 'is_active')
search_fields = ('first_name', 'last_name', 'email')
ordering = ('email',)
I have added these two lines in my settings.py files.
AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",)
I have extended this model to a custom profile model. But when I try to create another user I get the following error django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'username'") . Can anybody help me with this?
I am using Django : Django==2.2 with MySql.
Set
USERNAME_FIELD = 'username'
and test your code.
If everything works then change it.
Add username field in your custom user modal
Because error clearly says duplicate entry for key username which means, you have overrides the default user authentication by email id, so every time you create a user blank username tries to be created. Still, Django won't allow it's default implementation to be unique=True, so you have to override the username attribute also.
class User(AbstractUser):
email = models.EmailField(max_length=100, unique=True)
# add the below one line code
username = models.CharField(max_length=100, unique=False, null=True, default=None)
is_deleted = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']

Django custom user model : User creation issue

I am have created a custom user model to replace username with email. But when I am trying to add user from Django Admin I get error:
Please correct the errors below.
There is no other information with that error message.
The code for custom user:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name="email_address",
max_length=255,
unique=True,
)
name = models.CharField(max_length=255)
is_staff = models.BooleanField(
default=False,
)
is_active = models.BooleanField(
default=True,
)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def get_full_name(self):
return self.name
def __str__(self):
return self.email
Custom User Manager Code:
class UserManager(BaseUserManager):
def _create_user(self, email, password, **kwargs):
if not email:
raise ValueError("Email is required")
email = self.normalize_email(email)
user = self.model(email=email, **kwargs)
user.set_password(password)
user.save()
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, **kwargs):
kwargs.setdefault('is_staff', True)
kwargs.setdefault('is_superuser', True)
kwargs.setdefault('is_active', True)
if kwargs.get('is_staff') is not True:
raise ValueError("Superuser must have is_staff True")
if kwargs.get('is_superuser') is not True:
raise ValueError("Superuser must have is_superuser True")
return self._create_user(email, password, **kwargs)
and the admin code for same:
class CustomUserAdmin(BaseUserAdmin):
add_form = CustomUserCreationForm
form = CustomUserCreationForm
list_display = ('id', 'email', 'is_superuser')
list_filter = ('is_superuser',)
fieldsets = (
(None, {'fields': ('name', 'email', 'password')}),
('Permissions', {'fields': ('is_superuser', 'is_staff')}),
)
add_fieldsets = fieldsets
search_fields = ('name', 'email')
ordering = ('name', 'email')
filter_horizontal = ()
Custom User Form:
# users/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import User
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('name', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = User
fields = ('name', 'email')
I have tried many changes but couldn't figure out the issue. I would appreciate any help on this.
Change:
class Meta:
model = User
fields = ('name', 'email')
To:
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields + ('name', 'email')

Categories