I've successfully created my own extension for the User model based on this tutorial:
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#custom-users-and-permissions
I also need to add a ForeignKey to a Company model, so that each user is assigned to a company. But this isn't showing in the admin at all, neither in the initial admin view or the edit view.
I've added the ForeignKey reference in the MyUser class like so:
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
company = models.ForeignKey('Company', on_delete=models.CASCADE, default=1)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']
...
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 myapp.models import Company, Camera, 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', 'company')
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().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', 'company', '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', 'company', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('date_of_birth',)}),
('Company info', {'fields': ('company',)}),
('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)
admin.site.register(Company)
admin.site.register(Camera)
admin.site.unregister(Group)
If you add a foreign key to a custom user model, you need just to specify it on the fieldsets attribute.
For example with this custom user in models.py:
class CustomUser(AbstractUser):
company = models.ForeignKey('Company', on_delete=models.CASCADE)
You need this in the admin.py:
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from myapp.models import CustomUser
class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = CustomUser
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('company')}),
)
admin.site.register(CustomUser, MyUserAdmin)
Now you can select the user's company in the admin.
Related
I am new to django and totally confused so what should i do for these..
Note- list_display = ('email', 'first_name',) 'email', 'first_name' which defined in custom user model User
I am not getting errors but it not registering the Profile model
to admin why?
if i am adding phone from Profile model to list_display = ('email', 'first_name', 'phone') i m getting error (admin.E108) The value of 'list_display[2]' refers to 'phone', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'users.User'. How can i add phone in list_display?
I uses post_save_user_model_receiver() to auto create profile when
user is created is it best way to do it?
how can i add all Profile model fields for edit/update in users.admin (which is below).
profile model
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.auth import get_user_model # or from users.models import User
User = get_user_model()
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
photo = models.ImageField(null=True, blank=True)
date_of_birth = models.DateField(null=True, blank=True)
phone = models.IntegerField(null=True, blank=True)
country = models.CharField(max_length=150, null=True, blank=True)
city = models.CharField(max_length=150, null=True, blank=True)
bio = models.TextField(max_length=150, null=True, blank=True)
def __str__(self):
return str(self.user.email)
def post_save_user_model_receiver(sender, instance, created, *args, **kwargs ):
if created:
try:
Profile.objects.create(user=instance) # it create those user's profile
except:
pass
post_save.connect(post_save_user_model_receiver, sender=User)
Admin
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth import get_user_model
from .models import Profile
User = get_user_model()
# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
verbose_name_plural = 'profile'
# Define a new User admin
class UserAdmin(BaseUserAdmin):
inlines = (ProfileInline,)
list_display = ('email', 'first_name',)
list_filter = ('admin', 'staff', 'active')
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
users.admin file
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 import get_user_model # or from .models import User
from .forms import UserAdminCreationForm, UserAdminChangeForm
# Register your models here.
User = get_user_model() # or from .models import User
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 = ('email', 'first_name', 'get_phone', 'last_login', 'date_joined', 'is_admin')
list_filter = ('admin', 'staff', 'active')
list_select_related = ('profile',)
def get_phone(self, instance): # to show the Phone in list display from the Profile Model
return instance.profile.phone
get_phone.short_description = 'Phone'
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal Info', {'fields': ('first_name', 'last_name',)}),
('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': ('email', 'first_name', 'last_name', 'password1', 'password2', )
}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(User, UserAdmin)
# Remove Group Model from admin. We're not using it.
admin.site.unregister(Group)
I am trying to find out to restrict the group names for an admin user on Django. There are two groups in the system; "School One" and School "Two". The picture below shows the users belonging only to the "School Two" group (including me as John Doe).
For example, if I click the user "Josh Doe", I am directed to this page:
What I want is to display the groups that the current authenticated user (John Doe) belongs only. That way I can assign a group (or groups) to a particular user. So, here I want to see only "School Two" option as I (John Doe) belong only to that group (added by superuser).
How can I accomplish that?
Let me share my source codes with you:
admin.py file
from django.contrib import admin
from .models import User
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .forms import UserAdminCreationForm, UserAdminChangeForm
class MyUserAdmin(BaseUserAdmin):
form = UserAdminChangeForm
add_form = UserAdminCreationForm
list_display = ('email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_email_verified')
def get_list_filter(self, request):
if request.user.is_superuser:
return ['groups']
else:
return ['is_staff', 'is_active', 'is_email_verified']
readonly_fields = ('last_login', 'date_joined',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('first_name','last_name')}),
('Permissions', {'fields': ('is_active','is_staff', 'groups')}),
('Important dates', {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('first_name','last_name','email', 'password1', 'password2', 'groups')}
),
)
search_fields = ('first_name', 'last_name', 'email',)
ordering = ('email',)
filter_horizontal = ()
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
qs = qs.filter(groups__id__in=request.user.groups.all())
return qs
admin.site.register(User, MyUserAdmin)
In the forms.py file:
class UserAdminCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
User = get_user_model()
model = User
fields = ('email',)
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(UserAdminCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.is_staff = True
if commit:
user.save()
return user
class UserAdminChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
User = get_user_model()
model = User
fields = ('email', 'password', 'is_active','is_staff', 'groups')
def clean_password(self):
return self.initial["password"]
I would be glad if anybody could help with listing only the related group(s) as mentioned above.
It sounds like what you want is to make that field read-only for non-superuser staff. I think the easiest way to do that is to use the get_readonly_fields method on the ModelAdmin class to make this field read-only based on who is editing. Something like this:
class MyUserAdmin(BaseUserAdmin):
get_readonly_fields(self, request, obj=None):
fields = super().get_readonly_fields(request, obj)
if not request.user.is_superuser:
fields = fields + ('groups',)
return fields
I have a code to Extend User Model by Using a Custom Model Extending AbstractBaseUser. I got this error message
(ERRORS: : (admin.E108) The value of
'list_display[2]' refers to 'first_name', which is not a callable, an
attribute of 'UserAdmin', or an attribute or method on 'towns.MyUser'.
: (admin.E108) The value of
'list_display[3]' refers to 'last_name', which is not a callable, an
attribute of 'UserAdmin', or an attribute or method on 'towns.MyUser'.
The models file :
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class MyUserManager(BaseUserManager):
def create_user(self, username, email, password=None):
if not email:
raise ValueError('email address is required')
user = self.model(
username = username,
email = self.normalize_email(email)
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password=None):
user = self.create_user(
username, email, password=password
)
user.is_admin = True
user.is_staff = True
user.save(using=self._db)
return user
class MyUser (AbstractBaseUser):
username = models.CharField(
max_length=255,
unique=True
)
email = models.EmailField(
max_length=255,
unique=True,
verbose_name='email address'
)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
The form file:
from django.contrib.auth import get_user_model
from django.db.models import Q
User = get_user_model()
from django import forms
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='password', widget=forms.PasswordInput)
password2 = forms.CharField(label='password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email']
def clean_password(self):
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):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
class UserLoginForm(forms.Form):
query = forms.CharField(label='Username or Email')
password = forms.CharField(label='Password',widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
query = self.cleaned_data.get('query')
password = self.cleaned_data.get('password')
user_qs_final = User.objects.filter(
Q(username__iexact=query) |
Q(email__iexact=query).distinct()
)
if not user_qs_final.exists() and user_qs_final.count != 1:
raise forms.ValidationError('Invalid credentials = user does not exist')
user_obj = user_qs_final.first()
if not user.obj.check_password(password):
raise forms.ValidationError(' password is not correct')
self.cleaned_data["user_obj"] = user_obj
return super(UserLoginForm, self).clean(*args, **kwargs)
The admin file:
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .forms import UserCreationForm
from .models import MyUser
class UserAdmin(BaseUserAdmin):
add_form = UserCreationForm
List_display = ('username', 'email', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('username', 'email','password')}),
('Permissions', {'fields': ('is_admin',)}),
)
search_fields = ('username', 'email')
ordering = ('username','email')
filter_horizontal = ()
admin.site.register(MyUser,UserAdmin)
admin.site.unregister(Group)
also I have changed the AUTH_USER_MODEL in the settings file to be
AUTH_USER_MODEL = 'towns.MyUser'
any clue how get to resolve this error
Note : I do not really needs those fields (first_name), (last_name)
There is a typo in your admin class as you are not overriding the default list_display option which contains first_name. It should be list_display instead of List_display inside UserAdmin:
class UserAdmin(BaseUserAdmin):
add_form = UserCreationForm
list_display = ('username', 'email', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('username', 'email','password')}),
('Permissions', {'fields': ('is_admin',)}),
)
search_fields = ('username', 'email')
ordering = ('username','email')
filter_horizontal = ()
admin.site.register(MyUser,UserAdmin)
Using the documentation I am trying to create a custom authentication model in order to be able to use only Email and password to authenticate a user.
Despite I manage to do it, I am having trouble to edit the Admin panel and in particular the Edit form could you please help me to add the possible editable field.
my code is :
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 registration.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','is_active','is_hr','is_candidate','is_employee','company','first_name','last_name')
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().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', 'is_active', 'is_admin','is_hr','is_candidate','is_employee','company','first_name','last_name')
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', 'is_admin','is_active', 'is_admin','is_hr','is_candidate','is_employee','company','first_name','last_name')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('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', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Now register the new UserAdmin...
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)
model.py:
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class MyUserManager(BaseUserManager):
def create_Euser(self, email):
"""
Creates and saves a User with the given email,
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email)
)
user.save(using=self._db)
return user
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
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, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name= models.CharField(max_length=150, default='')
last_name= models.CharField(max_length=150, default='')
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_hr = models.BooleanField(default=False)
is_candidate = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
company = models.CharField(max_length=100, default='')
objects = MyUserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
def get_short_name(self):
# The user is identified by their email address
return self.email
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
You can add all you model fields.for that you should have to add field in fieldsets under UserAdmin.
change you fieldsets as below:
fieldsets = (
(None, {'fields': ('email', 'password','company','first_name','last_name')}),
('Permissions', {'fields': ('is_admin','is_active','is_hr','is_candidate','is_employee')}),
)
Above changes will add fields to django-admin.
I am building a custom user that uses an email as a username.
When I run the server to create a custom admin, I get this error
class 'user.admin.UserAdmin'>: (admin.E116) The value of
'list_filter[0]' refers to 'is_staff', which does not refer to a
Field.
Here is my code for the 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
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import BaseUser
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 = BaseUser
fields = ('email',)
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 != password2:
raise forms.ValidationError('Password do not 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
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 = BaseUser
fields = (
'email',
'password',
'user_first_name',
'user_last_name',
'user_mobile',
'is_a_student',
)
def clean_password(self):
return self.initial["password"]
class UserAdmin(UserAdmin):
#Forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
#The fields to be used in displaying User model.
#These overried the definitions on the base UserAdmin
#That reference specific fields on auth.User
list_display = (
'email',
)
list_filter = ('is_staff',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': (
'user_first_name',
'user_last_name',
'user_mobile',
)}),
('Permission', {'fields': (
'is_a_student',
)})
)
# 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',
'password1',
'password2',
'user_first_name',
'user_last_name',
'user_mobile',
'is_a_student',
)}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
#Register the new UserAdmin
admin.site.register(BaseUser, UserAdmin)
admin.site.unregister(Group)
Here is the models.py
from django.db import models
from django.core.validators import RegexValidator
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.core.mail import send_mail
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.core.files.storage import FileSystemStorage
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin
)
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email and password
"""
if not email:
raise ValueError('Users must have an email address')
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=email,
password=password,
)
user.is_superuser = user.is_staff = True
user.save(using=self._db)
return user
class BaseUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email',
max_length=255,
unique=True,
)
user_first_name = models.CharField(max_length=30)
user_last_name = models.CharField(max_length=50)
mobile_regex = RegexValidator(regex=r'^\+?1\d{9,15}$', message="Please enter a max of 10 digits :)")
user_mobile = models.CharField(validators=[mobile_regex], blank=True, max_length=10)
is_a_student = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(auto_now_add=True)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'User'
verbose_name_plural = 'Users'
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"""
Does the user have a specific permission?
"""
return True
def is_student(self):
return self.is_a_student
#property
def is_staff(self):
"""
Is the user a member of staff?
"""
return self.is_staff
def emai_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email])
Options done
- I already took out all of the is_staff attribute in admin.py and still got an error.
- Refactored it many times to check if the problem is in different areas of my code.
At this point I am stuck. Could someone please help debug this?
#list_filter = ('is_staff',)
list_filter = ('is_admin',)
You have to add this line which will filter your data in django-admin I had the same issue I resloved it by doing this in my admin.py file or for more brief information you can check out this wonderful tutorial:
Custom Django User Admin
`list_filter = ('admin', 'staff', or anything which you want to add in filter list)`
#property
def is_staff(self):
"""
Is the user a member of staff?
"""
return self.is_staff
The above code creates a recursive execution which caused the error.
#property
def is_admin(self):
"""
Is the user a member of staff?
"""
return self.is_staff
As Django "talks" about field i would check the model in a first review
i couldn't find any password or password1 nor password2 field in the model for example.