Unknown field(s) (model) specified for User - python

I am build project ,when i run python manage.py makemigrations
i got this error
File "/mnt/c/Users/ZAKARIA/Desktop/project/Accounts/admin.py", line 45, in <module>
class UpdateUserForm(forms.ModelForm):
File "/mnt/c/Users/ZAKARIA/Desktop/project/env/lib/python3.8/site-packages/django/forms/models.py", line 327, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (is_staff) specified for User
** Here is my code for models.py**
import datetime
from django.core.mail import send_mail
from distutils.command.upload import upload
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils import timezone
from phonenumber_field.modelfields import PhoneNumberField
from .managers import UserManger
GENDER_MALE = "m"
GENDER_FEMALE = "f"
OTHER = "o"
GENDER_CHOICES = (
(GENDER_MALE, "Male"),
(GENDER_FEMALE, "Female"),
(OTHER, "Other"),
)
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True)
picture = models.ImageField(
upload_to='images/users', null=True, verbose_name="")
is_active = models.BooleanField(default=True)
#is_staff = models.BooleanField(default=False)
phone = PhoneNumberField()
is_admin = models.BooleanField(default=False)
#credits =models.PositiveIntegerField(default=100)
linkedin_token = models.TextField(blank=True, default='')
expiry_date = models.DateTimeField(null=True, blank=True)
objects = UserManger()
USERNAME_FIELD = 'email'
REQURTED_FIELDS = []
def get_full_name(self):
full_name = '%S %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def __str__(self):
return self.email
def has_perm(self, prem, obj=None):
"Does the user have a specific permission?"
return True
def has_module_perm(self, app_label):
"Does the user have permissions to view the app `app_label`?"
return True
#property
def is_staff(self):
"Is the user a member of staff"
return self.is_admin
"""#property
def is_out_of_credits(self):
"Is the user out of credits"
return self.credits > 0
#property
def has_sufficient_credits(self,cost):
return self.credits - cost >= 0
"""
#property
def linkedin_signed_in(self):
return bool(self.linkedin_token) and self.expiry_date > timezone.now()
** Here is my code for manangers.py **
from django.contrib.auth.base_user import BaseUserManager
class UserManger(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, phone, password, **extra_fields):
if not email:
raise ValueError('Users must hava an email address')
user = self.model(
email.self.normalize_email(email),
phone=phone,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, phone, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, phone, password, **extra_fields)
def create_superuser(self, email, phone, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must hava is_superuser=True.')
return self._create_user(email, phone, password, **extra_fields)
** Here is my code for admin.py**
from pyexpat import model
import django
from django.contrib import admin
from django import forms
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User
class AddUserForm(forms.ModelForm):
"""
new User Form . Requires password confirmation.
"""
password1 = forms.CharField(
label='Password', widget=forms.PasswordInput
)
password2 = forms.CharField(
label='Confirm password', widget=forms.PasswordInput
)
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'gender')
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().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UpdateUserForm(forms.ModelForm):
"""
Update User Form ,Doesn't allow changing password in the Admin
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = (
'email', 'password', 'first_name', 'gender', 'last_name', 'is_active',
'is_staff'
)
def clean_password(self):
return self.initial["password"]
class UserAdmin(BaseUserAdmin):
form = UpdateUserForm
add_form = AddUserForm
list_display = ('email', 'first_name', 'last_name',
'gender', 'is_staff')
list_filter = ('is_staff',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {
'fields': ('first_name', 'last_name', 'gender')}),
('Permissions', {'fields': ('is_active', 'is_staff')}),
)
add_fieldsets=(
(
None,
{
'classes':('wide',),
'fields':(
'email','first_name', 'last_name', 'gender','password1','password2'
)
}
),
)
search_fields=('email','first_name','last_name')
ordering =('email','first_name','last_name')
filter_horizontal = ()
admin.site.register(User, UserAdmin)
** Here is my code for forms.py**
from django.contrib.auth import authenticate
from django.contrib.auth.forms import UserCreationForm
from Accounts.models import User
class UserRegistrationForm(UserCreationForm):
def __init__(self, *args, **kwargs):
UserCreationForm.__init__(self, *args, *kwargs)
self.fields['gender'].required = True
self.fields['first_name'].label = "First Name :"
self.fields['last_name'].label = "Last Name :"
self.fields['email'].label = "Email :"
self.fields['password1'].label = "Password"
self.fields['password2'].label = " Confirm Password"
self.fields['gender'].label = "Gender"
self.fields['phone'].label = "Phone"
self.fields['date_of_birth'].label = "Date Of Birth"
self.fields['first_name'].widget.attrs.update(
{
'placeholder': 'Enter First Name',
}
)
self.fields['last_name'].widget.attrs.update(
{
'placeholder': 'Enter Last Name',
}
)
self.fields['email'].widget.attrs.update(
{
'placeholder': 'Enter Email',
}
)
self.fields['password1'].widget.attrs.update(
{
'placeholder': 'Enter Password',
}
)
self.fields['password2'].widget.attrs.update(
{
'placeholder': 'Confirm Password',
}
)
self.fields['phone'].widget.attrs.update(
{
'placeholder': 'Enter Phone',
}
)
self.fields['date_of_birth'].widget.attrs.update(
{
'placeholder': 'Enter Date Of Birth',
}
)
class Meta:
model = User
fields = ['first_name', 'last_name', 'email', 'phone',
'password1', 'password2', 'gender', 'date_of_birth']
def clean_gender(self):
gender = self.cleaned_data.get('gender')
if not gender:
raise forms.ValidationError("Gender is required")
return gender
def save(self, commit=True):
user = UserCreationForm.save(self, commit=False)
user.role = "user"
if commit:
user.save()
return user
class UserLoginForm(forms.Form):
email = forms.EmailField(
widget=forms.EmailInput(attrs={'placeholder': 'Email', })
)
password = forms.CharField(
strip=False, widget=forms.PasswordInput(attrs={'placeholder': 'Password', }))
def clean(self, *args, **kwargs):
email = self.cleaned_data.get("email")
password = self.cleaned_data.get('password')
if email and password:
self.user = authenticate(email=email, password=password)
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
raise forms.ValidationError("User Does not exist")
if not user.check_password(password):
raise forms.ValidationError("Password is not Match")
if not user.is_active:
raise forms.ValidationError("User is not Active")
return super(UserLoginForm, self).clean(**args, **kwargs)
def get_user(self):
return self.user
** Here is my code for views.py**
from django.shortcuts import render
from django.contrib import messages, auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect, get_list_or_404
from django.urls import reverse, reverse_lazye
from matplotlib.style import context
from Accounts.forms import *
def get_success_urls(request):
"""
Handle Success Url After Login
"""
if 'next' in request.GET and request.GET['next'] != '':
return request.GET['netx']
else:
return reverse('jobs:home')
def user_registration(request):
"""
Handle user registration
"""
form = UserRegistrationForm(request.POST or None)
if form.is_valid():
form = form.save()
return redirect('Accounts:login')
context = {
'form': form
}
return render(request, 'accounts/user-registeration.html', context)
def user_logIn(request):
"""
Provides users to logIn
"""
form = UserLoginForm(request.POST or None)
if request.user.is_authenticated:
return redirect('/')
else:
if request.method == 'POST':
if form.is_valid():
auth.login(request, form.get_user())
return HttpResponseRedirect(get_success_urls(request))
context = {
'form': form,
}
def user_logOut(request):
"""
Provide the ability to logout
"""
auth.logout(request)
messages.success(request, 'You are Successfully logged out')
return redirect('Accounts:login')
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.
can any one help me to solve this problem

Double check this is correct:
fields = (
'email', 'password', 'first_name', 'gender', 'last_name', 'is_active',
'is_staff'
the is_staff field, is that an actual field of your user model ?

Related

error: UNIQUE constraint failed: accounts_user.username

I need to register a new user so wheen I seed data I get this error
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.username
model.py:
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from phonenumber_field.modelfields import PhoneNumberField
# custom manager
class UserManager(BaseUserManager):
"""Define a model manager for User model with no username 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)
GENDER_CHOICES = (
('M', "Male"),
('F', "Female"),
('O', "Other"),
)
class User(AbstractUser):
#username = None
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True
)
date_of_birth = models.DateField(default='1990-01-01')
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True)
picture = models.ImageField(
upload_to='img/users', null=True, verbose_name=""
)
phone = PhoneNumberField()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = UserManager()
def save(self, **kwargs):
if not (self.is_staff or self.is_superuser):
password = self.password
if password is not None:
self.set_password(password)
super(User, self).save(**kwargs)
name = f"{self.first_name} {self.last_name}"
Profile.objects.create(
name=name, dob=self.date_of_birth, user=self)
return self
else:
return super(User, self).save(**kwargs)
def __str__(self):
return self.email
view.py
from django.shortcuts import render,redirect
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.conf import settings
from django.urls import reverse_lazy,reverse
from django.views.generic import CreateView
from .forms import UserRegistrationForm,UserLoginForm
User = settings.AUTH_USER_MODEL
def get_success_urls(request):
"""
Handle Success Url After Login
"""
if 'next' in request.GET and request.GET['next'] != '':
return request.GET['netx']
else:
return reverse('candidates:home')
def login(request):
form = UserLoginForm(request.POST or None)
if request.user.is_authenticated:
return redirect('/')
else:
if request.method == 'POST':
if form.is_valid():
auth.login(request, form.get_user())
return HttpResponseRedirect(get_success_urls(request))
context = {
'form': form,
}
return render(request, 'accounts/login.html',context)
def user_registration(request):
"""
Handle user registration
"""
form = UserRegistrationForm(request.POST or None)
if form.is_valid():
form = form.save()
return redirect('accounts:login.html')
context = {
'form': form,
}
return render(request, 'accounts/user-registration.html', context)
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import authenticate
from .models import User
class UserRegistrationForm(UserCreationForm):
def __init__(self, *args, **kwargs):
UserCreationForm.__init__(self, *args, **kwargs)
self.fields['gender'].required = True
self.fields['first_name'].label = "First Name :"
self.fields['last_name'].label = "Last Name :"
self.fields['email'].label = "Email :"
self.fields['password1'].label = "Password"
self.fields['password2'].label = " Confirm Password"
self.fields['gender'].label = "Gender"
self.fields['phone'].label = "Phone"
self.fields['date_of_birth'].label = "Date Of Birth"
self.fields['first_name'].widget.attrs.update(
{
'placeholder': 'Enter First Name',
}
)
self.fields['last_name'].widget.attrs.update(
{
'placeholder': 'Enter Last Name',
}
)
self.fields['email'].widget.attrs.update(
{
'placeholder': 'Enter Email',
}
)
self.fields['password1'].widget.attrs.update(
{
'placeholder': 'Enter Password',
}
)
self.fields['password2'].widget.attrs.update(
{
'placeholder': 'Confirm Password',
}
)
self.fields['phone'].widget.attrs.update(
{
'placeholder': 'Enter Phone',
}
)
self.fields['date_of_birth'].widget.attrs.update(
{
'placeholder': 'Enter Date Of Birth',
}
)
class Meta:
model = User
fields = ['first_name', 'last_name', 'email', 'phone',
'password1', 'password2', 'gender', 'date_of_birth']
error_messages = {
"first_name": {"required": "First name is required", "max_length": "Name is too long"},
"last_name": {"required": "Last name is required", "max_length": "Last Name is too long"},
"gender": {"required": "Gender is required"},
}
def clean_gender(self):
gender = self.cleaned_data.get('gender')
if not gender:
raise forms.ValidationError("Gender is required")
return gender
def save(self, commit=True):
user = UserCreationForm.save(self, commit=False)
user.role = "user"
if commit:
user.save()
return user
class UserLoginForm(forms.Form):
email = forms.EmailField(
widget=forms.EmailInput(attrs={'placeholder': 'Email', })
)
password = forms.CharField(
strip=False, widget=forms.PasswordInput(attrs={'placeholder': 'Password', }))
def clean(self, *args, **kwargs):
email = self.cleaned_data.get("email")
password = self.cleaned_data.get('password')
if email and password:
self.user = authenticate(email=email, password=password)
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
raise forms.ValidationError("User Does not exist")
if not user.check_password(password):
raise forms.ValidationError("Password is not Match")
if not user.is_active:
raise forms.ValidationError("User is not Active")
return super(UserLoginForm, self).clean(*args, **kwargs)
def get_user(self):
return self.user
What is causing such an error? I researched similar posts on this platform but each case is unique.
can any one help me?
It's what the error says. You have set up using email addresses as the username and unique = True. So you can't have 2 users with the same email address. Try using a different email address. Does the superuser use the same email as the user your are trying to sign up?

Django Login with Email or Phone Number

I have been trying to find a solution of a problem in Django for a very long time. The problem is I am trying to develop a login system than can use either email or phone number to authenticate user.
Well, that can be done using by creating a custom user model . I have tested this. It works.
First steps
The first thing you need to do is create a new Django project. Make sure you don't run migrations because there are still a few things we need to do before then.
After creating your new Django project, create a new app called accounts with the following command:
python manage.py startapp accounts
Creating the User Model
By default, the User model provided by Django has a username field, and an email field. However, we also need a phone number field. In order to add this field, we need to extend the Django user model. In the accounts app's models.py file, type in the following code:
models.py
phone_validator = RegexValidator(r"^(\+?\d{0,4})?\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{4}\)?)?$", "The phone number provided is invalid")
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=100, unique=True)
phone_number = models.CharField(max_length=16, validators=[phone_validator], unique=True)
full_name = models.CharField(max_length=30)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
# is_translator = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'phone_number'
REQUIRED_FIELDS = ['email', 'full_name']
def __str__(self):
return self.email
#staticmethod
def has_perm(perm, obj=None, **kwargs):
return True
#staticmethod
def has_module_perms(app_label, **kwargs):
return True
#property
def is_staff(self):
return self.is_admin
Register the model with the admin
admin.py
class UserAdmin(BaseUserAdmin):
form = UserChangeForm
add_form = UserCreationForm
list_display = ('email', 'phone_number', 'full_name', 'is_active', 'is_admin')
list_filter = ('is_active', 'is_admin')
fieldsets = (
(None, {'fields': ('full_name', 'email', 'phone_number', 'password')}),
('Permissions', {'fields': ('is_active', 'is_admin', 'is_superuser', 'last_login', 'groups', 'user_permissions')}),
)
add_fieldsets = (
(None, {'fields': ('full_name', 'phone_number', 'email', 'password1', 'password2')}),
)
search_fields = ('email', 'full_name')
ordering = ('email',)
filter_horizontal = ('groups', 'user_permissions')
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
is_superuser = request.user.is_superuser
if is_superuser:
form.base_fields['is_superuser'].disabled = True
return form
admin.site.register(User, UserAdmin)
forms.py
class UserLoginForm(forms.Form):
email = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
for login costumer in login.html
views.py
import random
from .backends import EmailPhoneUsernameAuthenticationBackend as EoP
class UserLoginView(View):
form_class = UserLoginForm
template_name = 'accounts/login.html'
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('core:home')
return super().dispatch(request, *args, **kwargs)
def get(self, request):
form = self.form_class
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = EoP.authenticate(request, username=cd['email'], password=cd['password'])
if user is not None:
login(request, user)
messages.success(request, 'You have successfully logged in!', 'success')
return redirect('core:home')
else:
messages.error(request, 'Your email or password is incorrect!', 'danger')
return render(request, self.template_name, {'form': form})
Writing a Custom Backend
backends.py
from django.contrib.auth.hashers import check_password
from django.contrib.auth import get_user_model
from django.db.models import Q
User = get_user_model()
class EmailPhoneUsernameAuthenticationBackend(object):
#staticmethod
def authenticate(request, username=None, password=None):
try:
user = User.objects.get(
Q(phone_number=username) | Q(email=username)
)
except User.DoesNotExist:
return None
if user and check_password(password, user.password):
return user
return None
#staticmethod
def get_user(user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Update the settings (3 Options)
settings.py
INSTALLED_APPS = [
...
# Third-party apps
'accounts.apps.AccountsConfig',
...
]
AUTH_USER_MODEL = 'accounts.User'
AUTHENTICATION_BACKENDS = [
'accounts.backends.EmailPhoneUsernameAuthenticationBackend'
]
I hope your problem will be solved and others will use it.
Well that can be done using by creating a custom user model . This is the only way known to me to achieve the result.
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have a username')
user = self.model(
email=self.normalize_email(email),
username=username,
)
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),
password=password,
username=username,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
def get_profile_image_filepath(self , filepath):
return 'profile_images/' + str(self.pk) + '/profile_image.png'
def get_default_profile_image():
return "dummy_image.png"
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
profile_image = models.ImageField(max_length=255,
upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image)
hide_email = models.BooleanField(default=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = MyAccountManager()
def __str__(self):
return self.username
def get_profile_image_filename(self):
return str(self.profile_image)[str(self.profile_image).index('profile_images/' + str(self.pk) + "/"):]
# For checking permissions. to keep it simple all admin have ALL permissons
def has_perm(self, perm, obj=None):
return self.is_admin
# Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY)
def has_module_perms(self, app_label):
return True
This is the custom user model and this will login via the email of the user .
You have to define in the settings.py for the user auth model .
In settings.py add this
AUTH_USER_MODEL = "user_app.Account"
replace the "user_app" with the app in whose models.py this model is stored .
And also you need to tell to the admin to do so .
go to admin.py of the app and add this .
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from account.models import Account
class AccountAdmin(UserAdmin) :
list_display = ("email" , "username" , "date_joined" , "last_login" , "is_admin" , "is_staff")
search_fields = ("email" , "username")
readonly_fields = ("id" , "date_joined" , "last_login")
filter_horizontal = ()
list_filter = ()
fieldsets = ()
admin.site.register(Account , AccountAdmin)
Another way of achieving the result is to take email or phone number credential and password from the user and then in the views find out the username and then log the user in..
Create a form and then create a save method to do this , or diectly do it in the views.
Like this :
def loginView(request) :
if request.POST :
email = request.POST.get("email")
password = request.POST.get("password")
user = User.objects.get(email = email)
if user.check_password(password) :
login(request, user)
return redirect("home")

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 Admin field_sets not showing in admin portal

I am creating a custom user class for my data base but I can't get my custom fields to show in the admin portal when adding a new user or changing an existing user. I have registered the app in my settings, migrated the data base, and set the AUTH_USER_MODEL in my settings.py. Thank you!
My admin portal looks like this:
And my files look like this:
models.py
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
import secrets
from api_keys.managers import *
class User(AbstractBaseUser, PermissionsMixin):
FULL = 4
MAJOR = 3
MINOR = 2
CONTROLLED = 1
access_groups = [(FULL, 4), (MAJOR, 3), (MINOR, 2), (CONTROLLED, 1)]
username = models.CharField(_('user name'), max_length=50, unique=True)
email = models.EmailField(_('email address'), unique=True)
first_name = models.CharField(_('first name'), max_length=50, blank=True)
last_name = models.CharField(_('last name'), max_length=50, blank=True)
account_name = models.TextField(_('account'), max_length=500, blank=True)
purpose = models.TextField(_('purpose'), max_length=5000, blank=True)
date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
is_active = models.BooleanField(_('active'), default=True)
is_staff = models.BooleanField(_('staff'), default=False)
access_group = models.IntegerField(_('permission group'), choices=access_groups, default=CONTROLLED)
api_key = models.CharField(_('api key'), max_length=100)
delete_on = models.DateField(_('deletion date'), blank=True, null=True)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'access_group']
def save(self, *args, **kwargs):
if not self.api_key:
self.api_key = secrets.token_urlsafe(16)
super(User, self).save(*args, **kwargs)
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def has_access(self, level):
return self.access_group >= level
def email_user(self, subject, message, from_email=None, **kwargs):
send_mail(subject, message, from_email, [self.email], **kwargs)
managers.py
from django.contrib.auth.base_user import BaseUserManager
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, username, email, password, **extra_fields):
if not username:
raise ValueError('The given user name must be set')
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(username=username, email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
extra_fields.setdefault('is_staff', False)
return self._create_user(username, email, password, **extra_fields)
def create_superuser(self, username, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_staff', True)
if not extra_fields.get('is_superuser'):
raise ValueError('Superuser must have is_superuser = True')
return self._create_user(username, email, password, **extra_fields)
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from api_keys.forms import UserChangeForm, UserCreationForm
from api_keys.models import User
# Register your models here.
class NewUserAdmin(UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
model = User
list_display = ('username', 'email', 'access_group', 'delete_on', 'api_key')
list_filter = ('username', 'email', 'access_group', 'is_superuser', 'delete_on')
readonly_fields = ['date_joined', 'api_key', 'last_login']
field_sets = (
('User', {'fields': ('username', 'email', 'password', 'access_group')}),
('Permissions', {'fields': (('is_staff', 'is_active'), 'access_group', 'delete_on')}),
)
add_field_sets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', ('password1', 'password2'))
}),
('Permissions', {'fields': (('is_staff', 'is_active'), 'access_group', 'delete_on')})
)
search_fields = ('username', 'email', 'first_name', 'last_name', 'account_name', 'access_group', 'delete_on')
ordering = ('username', 'email', 'first_name', 'last_name', 'access_group', 'account_name', 'delete_on')
admin.site.register(User, NewUserAdmin)
forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from api_keys.models import User
class UserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = User
fields = '__all__'
class UserChangeForm(UserChangeForm):
class Meta(UserChangeForm):
model = User
fields = '__all__'
The layout is controlled by ModelAdmin.fieldsets, not field_sets
class NewUserAdmin(UserAdmin):
...
fieldsets = (
('User', {'fields': ('username', 'email', 'password', 'access_group')}),
('Permissions', {'fields': (('is_staff', 'is_active'), 'access_group', 'delete_on')}),
)

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