No username attribute of model error, even already have objects = UserManager()? - python

Here is my model in the user app
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserTable(AbstractBaseUser, PermissionsMixin):
USERNAME_FIELD='email'
objects = UserManager()
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
phone = models.CharField(max_length=255, default=None)
is_active = models.BooleanField(default=False)
Here is my admin.py inside the user app.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import UserTable
admin.site.register(UserTable, UserAdmin)
I also included in my settings.py
INSTALLED_APPS = [
....
'user.apps.UserConfig',
....
]
This is the error when I run python manage.py migrate
(admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'user.UserTable'.
The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'user.UserTable'.
I dont know why, I thought when I set objects = UserManager() fields like username, first_name, last_name is setted up. I also user USERNAME_FIELD to set email replacing the username primary key.

You are supposed to write ur own UserManager
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('User must have an email address')
user = self.model(
email=self.normalize_email(email),
**extra_fields
)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
user = self.create_user(
email,
password,
**extra_fields
)
return user
Just a small comment in UserTable model, make
is_active = models.BooleanField(default=True) To be able to login
And in settings.py file add
AUTH_USER_MODEL = 'user.UserTable'
Edit
I noticed that you are calling AbstractBaseUser, BaseUserManager in a wrong way
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
Try it out and told me if there is any problem!

The problem is because you are inheriting from AbstractBaseUser (which does not come with a username field):
class AbstractBaseUser(models.Model):
password = models.CharField(_('password'), max_length=128)
last_login = models.DateTimeField(_('last login'), blank=True, null=True)
... # No definition for usename in this class
and then using UserAdmin (which requires username as field) as your admin:
#admin.register(User)
class UserAdmin(admin.ModelAdmin):
...
# The admin needs the username field as described by ordering
# But your custom user model doesn't have it
ordering = ('username',)
There are a number of ways to fix this, but one way is to define your own model admin for your custom user:
from django.contrib import admin
class MyAdmin(admin.ModelAdmin):
pass
admin.site.register(UserTable, MyAdmin)

Related

'AdminSiteTests' object has no attribute 'user' Django unit tests

I can't seem to figure out why my unit test is failing for the following
Traceback (most recent call last):
File "/app/core/tests/test_admin.py", line 26, in test_users_listed
self.assertContains(res, self.user.name)
AttributeError: 'AdminSiteTests' object has no attribute 'user'
test_admin.py
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setup(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='admin#test.com',
password='test123'
)
self.client.force_login(self.admin_user)
self.user = get_user_model().objects.create_user(
email='test#test.com',
password='test123',
name='test name'
)
def test_users_listed(self):
"""Test that users are listed on user page"""
url = reverse('admin:core_user_changelist')
res = self.client.get(url)
self.assertContains(res, self.user.name)
self.assertContains(res, self.user.email)
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from core import models
class UserAdmin(BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'name']
admin.site.register(models.User, UserAdmin)
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a new user"""
if not email:
raise ValueError('Users must have a email address')
user = self.model(email=self.normalize_email(email), **extra_fields)
# Must encrypt password using set_password() that comes with BaseUserManager
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""Creates and saves new superuser"""
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""Custom user model that supports using email instead of username"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
I am creating the user in the setup function for the rest of my tests but I'm thinking maybe the setup function isn't getting called to create the user?
All other tests are passing. Including a test that checks whether a user has been created. Any help would be apperciated

How to implement Django SSO with custom user model and object permission (EX/django-guardian) in multiple projects

I tried to search and study some information on the google, but I couldn't find the good solution.
I have several Django projects and want to create "Member" project store user information which implement Single-Sign-On(SSO) feature (ex/"django-simple-sso"). Then I need to classify user permission, I study the package "django-guardian" which maybe can help me do object permission.
I do below things to create custom model in "Member" project. Then I just post the code that I add/change.
# setting.py of "Member" project
INSTALLED_APPS = [
'users',
'guardian'
]
AUTHENTICATION_BACKENDS = (
'guardian.backends.ObjectPermissionBackend',
)
I add an app which called users in the project named "Member".
# admin.py in the users app of Member project.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ('email', 'is_staff', 'is_active', 'employee_account', 'location', 'chinese_name', 'english_name', 'extension', 'last_login', 'date_joined')
list_filter = ('email', 'is_staff', 'is_active', 'employee_account', 'location', 'chinese_name', 'english_name', 'extension', 'last_login', 'date_joined')
fieldsets = (
(None, {'fields': ('employee_account', 'password')}),
('Permissions', {'fields': ('is_staff', 'is_active')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('employee_account', 'password1', 'password2', 'is_staff', 'is_active')}
),
)
search_fields = ('employee_account',)
ordering = ('employee_account',)
admin.site.register(CustomUser, CustomUserAdmin)
# apps.py in the users app of Member project.
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
# forms.py in the users app of Member project.
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('employee_account',)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('employee_account',)
# manager.py in the users app of Member project.
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
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 Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
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)
extra_fields.setdefault('is_active', 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)
# models.py in the users app of Member project
from django.db import models
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from .managers import CustomUserManager
class CustomUser(AbstractBaseUser, PermissionsMixin):
employee_account = models.CharField(max_length=100, unique=True)
location = models.CharField(max_length=50)
chinese_name = models.CharField(max_length=30)
english_name = models.CharField(max_length=30)
extension = models.CharField(max_length=30)
email = models.EmailField(max_length=125)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'employee_account'
REQUIRED_FIELDS = ['location','chinese_name','english_name','extension', 'email']
objects = CustomUserManager()
def __str__(self):
return self.employee_account
Then I use django shell to add user and assign permission.
>>> from django.contrib.auth.models import Group
>>> from users.models import CustomUser
>>> jack = CustomUser.objects.create_user('123456789#gamil.com', '123456789')
>>> admins = Group.objects.create(name='admins')
>>> jack.has_perm('change_group', admins)
False
>>> from guardian.models import UserObjectPermission
>>> UserObjectPermission.objects.assign_perm('change_group', jack, obj=admins)
<UserObjectPermission: admins | | change_group>
>>> jack.has_perm('change_group', admins)
True
>>> jack.has_perm('change_group')
False
After that I create an book app in another project named book_web.
# model.py in the book app of book_web project
from django.db import models
class Book(models.Model):
sn = models.CharField(max_length=200)
book = models.CharField(max_length=100)
author = models.CharField(max_length=100)
price = models.PositiveIntegerField(null=True, blank=True)
number = models.PositiveIntegerField(null=True, blank=True)
1. It seems work abnormally when key this command UserObjectPermission.objects.assign_perm('change_group', jack, obj=admins). I found that response doesn't show the user name which is different with django-guardian example code.
2. I don't know how to assign Book object permission in Member project such as django-guardian example code. Because there is not same model as Book model in the Member project.
Does anyone have similar experience about this?
If you have another recommendation package to implement the feature, welcome to share your experience. Thanks for your response.

Django. How to add an extra field in User model and have it displayed in the admin interface

I'm learning Django and need some help.
I need to include an extra boolean field in my User Model (auth_user table in the db I believe) and have it be displayed in the admin interface when managing users, like the staff status field in this image...
127:0.0.1:8000/admin/user :
and...
127.0.0.1:8000/admin/auth/user/2/change/ :
I'm unsure on how to approach this. I understand I'll have to extend the AbstractUser model and then perhaps manually add the field into the db, but then how do I update the new field for the view, form and templates for the admin interface? Will I have to rewrite the django admin source code for all of these or is there an simpler way?
This is how I did it:
Note: This should be done when you are creating a new project.
Adding field(s) to User model :-
models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
gender = models.BooleanField(default=True) # True for male and False for female
# you can add more fields here.
Overriding the default User model :-
settings.py:
# the example_app is an app in which models.py is defined
AUTH_USER_MODEL = 'example_app.User'
Displaying the model on admin page :-
admin.py:
from django.contrib import admin
from .models import User
admin.site.register(User)
The best way is to create new Model with User OneToOneField. e.g
class UserProfile(models.Model):
user = models.OneToOneField(User)
phone = models.CharField(max_length=256, blank=True, null=True)
gender = models.CharField(
max_length=1, choices=(('m', _('Male')), ('f', _('Female'))),
blank=True, null=True)
You can play with django admin either in User Model or UserProfile Model and can display the fields in Admin accordingly
You have two options, they are:
Extend the existing User model by adding another model and linking it to the User model using one-to-one relation. See here.
Write your own user model and use it, which would be difficult for a newbie. See here.
#managers.py Create new file.
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', 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)
#models.py Create your models here.
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import gettext_lazy as _
from .managers import CustomUserManager
class User(AbstractBaseUser,PermissionsMixin):
first_name =models.CharField(max_length=250)
email = models.EmailField(_('email address'), unique=True)
mobile =models.CharField(max_length=10)
status = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
object =CustomUserManager()
# add more your fields
#admin.py
from django.contrib import admin
from .models import User
#admin.register(User)
class UserAdmin(admin.ModelAdmin):
list_display = ('email','mobile','password')
#setting.py
AUTH_USER_MODEL = 'users.User'
# run command
python manage.py makemigrations
python manage.py migrate

Django Custom User did not log in

I've created a CustomUser from AbstractUser in Django 1.9. Add on admin.sites.register when I was create superuser, django have created successful but when I was log in on system the user didn't exists.
Follow the code:
On customuser/models.py:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class CustomUserManager(BaseUserManager):
def create_user(self, username, email, first_name, last_name, cpf, password=None):
user = self.model(
username=username,
email=email,
first_name=first_name,
last_name=last_name,
cpf=cpf
)
return user
def create_superuser(self, username, email, first_name, last_name, cpf, password):
user = self.create_user(username, email, first_name, last_name, cpf,
password=password)
user.is_super_user = True
user.save()
return user
class CustomUser(AbstractUser):
SEXO_CHOICES = (
(u'Masculino', u'Masculino'),
(u'Feminino', u'Feminino'),
)
cpf = models.BigIntegerField(unique=True)
phone = models.CharField(max_length=15, blank=True)
is_super_user = models.BooleanField(default=False)
data_de_nascimento = models.DateField(null=True)
sexo = models.CharField(max_length=9, null=True, choices=SEXO_CHOICES)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'cpf']
objects = CustomUserManager()
On settins.py, I add the line:
INSTALLED_APPS = [
...
'customuser',
]
...
AUTH_USER_MODEL = 'customuser.CustomUser'
And my customuser/admin.py:
from django.contrib import admin
from models import CustomUser, CustomUserManager
admin.site.register(CustomUser)
Thanks a lot for your help.
See these docs on making custom user work with admin site.
UPDATE:
Sorry, previously I thought, you were inheriting your model from AbstractBaseUser, therefore that answer was giving you error.
Since, you're inheriting from AbstractUser, your subclass will automatically get is_staff field. So, you'll just need to set is_staff to True in create_superuser method.
class CustomUserManager(...):
# ...
def create_superuser(...):
# ...
user.is_staff = True
user.save()
return user

Django user model in submodel

In my current project I'm replacing the default django user model. As the number of models started growing I decided to split the implementation into several folders, but now django can't find my user model.
I had this, which works:
djutils
models.py
UserManager
User
I changed to this and it doesn't work anymore
djutils
models
__init__.py
from djutils.models.user import UserManager, User
user.py
UserManager
User
Shouldn't it still import the models? I get:
CommandError: One or more models did not validate:
auth.user: Model has been swapped out for 'djutils.User' which has not been installed or is abstract.
I have this in my settings.py
AUTH_USER_MODEL = 'djutils.User'
(Notice the first case works)
Please advise!
Regards
Edit
djutils
models
__init__.py
from __future__ import absolute_import
from djutils.models.base import Manager, PrivateModel, Model
from djutils.models.user import UserManager, User
from djutils.models.passwordrecovery import PasswordRecoveryManager, PasswordRecovery
user.py
from djutils.models.base import Manager, Model
from djutils import mail
from djutils import settings
from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from djutils import fields
class UserManager(Manager, BaseUserManager):
def create_user_instance(self, email, password, first_name, last_name, **extra_fields):
return user
def create_user(self, email, password, first_name, last_name, **extra_fields):
return user
def create_superuser(self, email, password, first_name, last_name, **extra_fields):
return user
class User(Model(20), AbstractBaseUser, PermissionsMixin):
# Basico info
first_name = fields.NameField(max_length=20, help_text=_('First name'))
last_name = fields.NameField(max_length=20, help_text=_('Last name'))
email = fields.EmailField(max_length=255, unique=True, help_text=_('Email'))
url = fields.URLField(help_text=_('Personal homepage'))
bio = fields.TextField(help_text=_('Biographic details'))
#picture = fields.ImageField(help_text=_('Profile picture'))
# Permissions
is_active = fields.BooleanField(default=False, help_text=_('Active user'))
is_staff = fields.BooleanField(default=False, help_text=_('Staff member'))
# Logging
date_joined = fields.DateTimeField(default=timezone.now)
# A string describing the name of the field on the User model that is used as the unique identifier
USERNAME_FIELD = 'email'
# A list of the field names that must be provided when creating a user via the createsuperuser management command
REQUIRED_FIELDS = ['first_name', 'last_name', 'password']
# Fields that are not returned by get_public
PRIVATE = ['is_active', 'is_superuser', 'is_staff', 'last_login', 'groups', 'user_permissions', 'password', 'id']
# Model manager
objects = UserManager()
class Meta:
swappable = 'AUTH_USER_MODEL'
permissions = ()
def send_mail(self, request, subject, body, context={}):
mail.send_mail(request, subject, body, [self.email], context)
def send_confirmation_email(self, request, context={}):
self.send_mail(request, settings.CONFIRMATION_SUBJECT, settings.CONFIRMATION_TEMPLATE, dict(context, **{
'redirect': request.build_absolute_uri(settings.CONFIRMATION_REDIRECT_URL)
}))
Set app_label = 'djutils' in your User model's Meta class.
See the app_label docs for more info.

Categories

Resources