Django user model in submodel - python

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.

Related

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

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)

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.

"Table 'nest.auth_user' doesn't exist"

I am creating a custom user registration form and I keep getting this error. How do I correct this.
> ProgrammingError at /Identity/register/ (1146, "Table 'nest.auth_user'
> doesn't exist")
I adjusted the authentication system to use email instead of username and I switched from SQlite to Mysql.
# Create models for Identities app.
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
from django.contrib.auth.models import User
# Create your models here.
class UserManager(BaseUserManager):
# Create a model manager for User model with no user name field
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
# Create and save a User with the given email and password
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
# Create and save a regular User with the given email and password.
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
# Create and save a SuperUser with the given email and password.
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class User(AbstractUser):
# User Model
username = None
email = models.EmailField(_('email add '), unique = True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
I registered the User Model:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.utils.translation import ugettext_lazy as _
from .models import User
# Add User profile from models document
from Identities.models import UserProfile
# Register your models here.
#admin.register(User)
class UserAdmin(DjangoUserAdmin):
# Create administration model for custom User model
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
list_display = ('email', 'first_name', 'last_name', 'is_staff')
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email',)
I also created a custom user model and registered the model
class UserProfile(models.Model):
user = models.OneToOneField(User)
contact = models.IntegerField(default=0)
admin.site.register(UserProfile)
I created the register view :
from django.shortcuts import render
from Identities.forms import CreateAccountForm
def register(request):
if request.method == 'POST':
form = CreateAccountForm(request.POST)
if form.is_valid():
form.save()
else:
return redirect(reverse('Identities:logout'))
else:
form = CreateAccountForm()
var = {'form' : form}
return render(request, 'Identities/create_account.html', var)
Then I created the class model in forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CreateAccountForm(UserCreationForm):
email = forms.EmailField(required = True)
class Meta:
model = User
fields = (
'first_name',
'last_name',
'email',
'password1',
'password2'
)
def save(self, commit = True):
user = super(CreateAccountForm, self).save(commit = False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
You need to migrate first
python3 manage.py makemigrations
python3 manage.py migrate
Need to migrate your model files to database...
python manage.py makemigrations
python manage.py migrate
This happened to me when switching from sqlite to mysql. I guess I'd made auth_user on sqlite and it didn't exist on mysql.
A few things seemed to really help me out.
Restarting Apache: sudo systemctl restart apache2
Making a new super user: python3 manage.py createsuperuser.
I got this error: Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
So then I did python3 manage.py makemigrations and python3 manage.py migrate for admin, auth, contenttypes, sessions.
Then again: python3 manage.py createsuperuser.
It fixed it for me.
I also had that error when I referenced my custom User-class in a separate Model via a ForeignKey for example. I set AUTH_USER_MODEL in my settings.py like this:
AUTH_USER_MODEL = "users.User"
I fixed it by using that reference from settings.AUTH_USER_MODEL instead. For this, you need to import it first:
# Replace this
# from users.models import MyUser
# With this
from django.conf import settings
and replace your custom User-model with the one from the settings:
# Replace this
# owner = models.ForeignKey(MyUser, related_name="budgets", on_delete=models.PROTECT)
# With this
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="budgets", on_delete=models.PROTECT)

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

Categories

Resources