How to set emailfield to required when extending AbstractUser?
I was wondering how to override the AbstractUser's emailfield model to set it as required. Currently my form list the email field but does not set as required. By default shouldn't all models be required?
From the documentation it shows an example of how to set a field to required when creating a super user but I am not sure how to complete the task from the AbstractUser model without using AbstractBaseUser.
model.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
display_name = models.CharField(max_length=50, unique=True)
bio = models.CharField(max_length=500, blank=True, null=True)
authorization_code = models.CharField(max_length=20)
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta (UserCreationForm):
model = CustomUser
fields = ('username', 'email', 'display_name', 'authorization_code')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email', 'bio')
admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
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', 'username', 'display_name', 'bio']
list_display_links = ('username', 'display_name')
fieldsets = (
(None, {'fields': ('username', 'display_name', 'email', 'bio', 'password')}),
('Permissions', {'fields': ('is_staff', 'is_active')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'display_name', 'email', 'bio', 'password1', 'password2', 'is_staff', 'is_active')}
),
)
admin.site.register(CustomUser, CustomUserAdmin)
Solution:
# It was as simple as updating my CustomUser model as shown:
class CustomUser(AbstractUser):
display_name = models.CharField(max_length=50, unique=True)
bio = models.CharField(max_length=500, blank=True, null=True)
authorization_code = models.CharField(max_length=20)
email = models.EmailField(max_length=50, unique=True)
You can do it by overriding email in AbstractBaseUser.
from django.contrib.auth.models import AbstractBaseUser, UserManager
class User(AbstractBaseUser):
email = models.EmailField(_('email address'), blank=False)
objects = UserManager()
Related
My Django project is based on built-in User model.
For some extra attributes, I have defined another model:
models.py:
class Status(models.Model):
email = models.ForeignKey(User, on_delete=models.CASCADE)
is_verified = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
def __str__(self):
return self.email
And here's the custom ModelAdmin:
admin.py:
class CustomUserAdmin(UserAdmin):
model = User
list_display = ['email']
search_fields = ['email']
I want list_display to show me is_verified and is_active fields from Status model but I'm lost.
I've looked into some similar questions on SO like Display field from another model in django admin or Add field from another model Django but none of the solutions are applicable because one of my models is Django's built-in.
Try this.
models.py
class Status(models.Model):
# email = models.ForeignKey(User, on_delete=models.CASCADE)
email = models.OneToOneField(
User,
on_delete=models.CASCADE,
related_name='status'
)
is_verified = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
def __str__(self):
return self.email
admin.py
class CustomUserAdmin(UserAdmin):
model = User
list_display = ['email', 'is_verified', 'is_active']
search_fields = ['email']
def is_verified(self, obj):
return obj.status.is_verified
def is_active(self, obj):
return obj.status.is_active
If you want to apply the displayed name or ordering, please refer to the following
source
I saw your comments and tried running the code myself. There were some problems, so I modified admin.py as follows.
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
admin.site.unregister(User)
#admin.register(User)
class CustomUserAdmin(UserAdmin):
list_display = ['email', 'status_is_verified', 'status_is_active']
list_filter = ['status__is_verified', 'status__is_active']
search_fields = ['email']
#admin.display(ordering='status__is_verified')
def status_is_verified(self, obj):
return obj.status.is_verified
#admin.display(ordering='status__is_active')
def status_is_active(self, obj):
return obj.status.is_active
I am begginer in django. I would like to add some posts and comments but I am getting an Integrity error.
Without comments model it was working before but it doesn´t work together. I already delete my database and makemigrations and migrate again.
post models
from django.db import models
from django.conf import settings
# from django.contrib.auth import get_user_model
# User = get_user_model()
# Create your models here.
class Post(models.Model):
user = models.ForeignKey(
#to=User,
to=settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='posts',
null=True
)
content = models.CharField(
max_length=150,
blank=False
)
created = models.DateTimeField(
auto_now=True
)
liked_by = models.ManyToManyField(
#to=User,
to=settings.AUTH_USER_MODEL,
related_name='liked_posts',
blank=True
)
post serializer
from rest_framework import serializers
from .models import Post
from ..comment.serializers import CommentSerializer
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
comments = CommentSerializer(source='comments.content')
fields = [
'id',
'user',
'content',
'comments',
'created',
'liked_by',
]
comment.models
from django.db import models
from django.conf import settings
from apps.post.models import Post
# Create your models here.
class Comment(models.Model):
user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comment', null=True)
post = models.ForeignKey(to=Post, on_delete=models.SET_NULL, related_name='comment', null=True)
content = models.CharField(max_length=150)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'Comment by: {self.user}'
comment serializer
from rest_framework import serializers
from .models import Comment
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ['id', 'user', 'post', 'content', 'created']
you need to pass the CommentSerializer field in PostSerializer Meta class properly.
from rest_framework import serializers
from .models import Post
from .comment.serializers import CommentSerializer
class PostSerializer(serializers.ModelSerializer):
comments = CommentSerializer(many=True)
class Meta:
model = Post
fields = [
'id',
'user',
'content',
'comments',
'created',
'liked_by',
'comments',
]
i would like to add data to table which having a foreignkey relatonship with user model through django rest api.
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
# username = None
email = models.EmailField(verbose_name='email',max_length=50,unique=True)
phone = models.CharField(max_length=17,blank=True)
REQUIRED_FIELDS = [
'first_name',
'last_name',
'phone',
'username',
]
USERNAME_FIELD = 'email'
def get_username(self):
return self.email
class UserInfo(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
address = models.CharField(max_length=50)
zipcode = models.CharField(max_length=20)
medication = models.CharField(max_length=25)
def __str__(self):
return str(self.user)
serializers.py
from djoser.serializers import UserCreateSerializer
class UserCreateSerializerCustom(UserCreateSerializer):
class Meta(UserCreateSerializer.Meta,):
model = User
fields = (
'id',
'email',
'username',
'password',
'first_name',
'last_name',
'phone',
)
## User Additional Info Serializers
class UserAdditionalSerializers(serializers.ModelSerializer):
user = UserCreateSerializerCustom()
class Meta:
model = UserInfo
fields = (
'user',
'address',
'zipcode',
'medication',
)
views.py
class UserAdditionalView(generics.ListCreateAPIView):
queryset = UserInfo.objects.all()
serializer_class = UserAdditionalSerializers
how will i send user instance with the data....??
i'm using token authentication for the api. Which is the best way to achieve this..??
I am trying to override change model form for adming page but don't know why it doesn't work.
Can smb help me please?
My forms.py:
from django import forms
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.models import User
class CustomUserChangeForm(UserChangeForm):
email = forms.EmailField(required=True, label="Email")
phone = forms.CharField(label="Phone number")
class Meta:
model = User
fields = ("username", "email", "phone", )
My admin.py:
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', 'username', 'phone', ]
admin.site.register(CustomUser, CustomUserAdmin)
My models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(_('username'), max_length=30,
unique=True)
first_name = models.CharField(_('first name'), max_length=30,
blank=True)
last_name = models.CharField(_('last name'), max_length=30,
blank=True)
email = models.EmailField(_('email address'), unique=True,
blank=True, null=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the
format: '+999999999'. Up to 15 digits allowed.")
phone = models.CharField(_('phone number'), validators=[phone_regex],
max_length=17,
unique=True, blank=True, null=True)
I am trying to override change model form but don't know why it doesn't work.
Can smb help me please?
At first sight you used the wrong model in your form: it should be:
from myapp.models import CustomUser
from django.contrib.auth.forms import UserChangeForm
class CustomUserChangeForm(UserChangeForm):
email = forms.EmailField(required=True, label='Email')
phone = forms.CharField(label='Phone number')
class Meta:
model = CustomUser
fields = ('username', 'email', 'phone', )
That being said, since your CustomerUserChangeForm does not have any fields to change passwords or permissions, you can use a simple ModelForm [Django-doc]:
from django.forms import ModelForm
from myapp.models import CustomUser
class CustomUserChangeForm(ModelForm):
email = forms.EmailField(required=True, label='Email')
phone = forms.CharField(label='Phone number')
class Meta:
model = CustomUser
fields = ('username', 'email', 'phone', )
I created a custom user model extending AbstractBaseUser class. code is below.
class UserModel(AbstractBaseUser):
sys_id = models.AutoField(primary_key=True, blank=True)
name = models.CharField(max_length=127, null=False, blank=False)
email = models.EmailField(max_length=127, unique=True, null=False, blank=False)
mobile = models.CharField(max_length=10, unique=True, null=False, blank=False)
user_type = models.PositiveSmallIntegerField(choices=user_type_choices, null=False, blank=True, help_text="Admin(1)/Institute(2)/Student(3)")
access_valid_start = models.DateTimeField(null=True, blank=True)
access_valid_end = models.DateTimeField(null=True, blank=True)
created_when = models.DateTimeField(null=True, blank=True )
created_by = models.BigIntegerField(null=True, blank=True)
last_updated_when = models.DateTimeField(null=True, blank=True)
last_updated_by = models.BigIntegerField(null=True, blank=True)
notes = models.CharField(max_length=2048, null=True, blank=True)
is_active = models.BooleanField(default=True)
# this field is required to login super user from admin panel
is_staff = models.BooleanField(default=True)
# this field is required to login super user from admin panel
is_superuser = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = "email"
# REQUIRED_FIELDS must contain all required fields on your User model,
# but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.
REQUIRED_FIELDS = ['name', 'mobile', 'user_type']
class Meta:
app_label = "accounts"
db_table = "users"
def __str__(self):
return self.email
def get_full_name(self):
return self.name
def get_short_name(self):
return self.name
# this methods are require to login super user from admin panel
def has_perm(self, perm, obj=None):
return self.is_superuser
# this methods are require to login super user from admin panel
def has_module_perms(self, app_label):
return self.is_superuser
Now in my admin panel only 'groups' is available. I want my custom user mode i.e. UserModel to appear in admin panel so that I can add, edit and delete user from admin user interface.
I tried multiple codes from SO, simplest of them is below
from django.contrib.auth.admin import UserAdmin
from accounts.models import UserModel
from django.contrib import admin
class MyUserAdmin(UserAdmin):
model = UserModel
fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('mobile',)}),
)
admin.site.register(UserModel, MyUserAdmin)
now I am getting this errors ..
ERRORS:
<class 'accounts.admin.MyUserAdmin'>: (admin.E019) The value of 'filter_horizontal[0]' refers to 'groups', which is not an attribute of 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E019) The value of 'filter_horizontal[1]' refers to 'user_permissions', which is not an attribute of 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'MyUserAdmin', or an attribute or method on 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'first_name', which is not a callable, an attribute of 'MyUserAdmin', or an attribute or method on 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'last_name', which is not a callable, an attribute of 'MyUserAdmin', or an attribute or method on 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E116) The value of 'list_filter[3]' refers to 'groups', which does not refer to a Field.
Please let me know how can I add custom user model successfully to admin UI?
From the Django Documentation
If your custom user model extends django.contrib.auth.models.AbstractUser, you can use Django’s existing django.contrib.auth.admin.UserAdmin class. However, if your user model extends AbstractBaseUser, you’ll need to define a custom ModelAdmin class. It may be possible to subclass the default django.contrib.auth.admin.UserAdmin; however, you’ll need to override any of the definitions that refer to fields on django.contrib.auth.models.AbstractUser that aren’t on your custom user class.
So basically, if you create a new user model from the AbstractBaseUser instead of AbstractUser you need to create your own custom ModelAdmin class, alternatively if you inherit from UserAdmin (which is what you're currently doing) you need to override and handle any differences.
#Anurag Rana your custom UserAdminclass should look like this
from django.contrib.auth.admin import UserAdmin
from accounts.models import UserModel
from django.contrib import admin
class MyUserAdmin(UserAdmin):
model = UserModel
list_display = () # Contain only fields in your `custom-user-model`
list_filter = () # Contain only fields in your `custom-user-model` intended for filtering. Do not include `groups`since you do not have it
search_fields = () # Contain only fields in your `custom-user-model` intended for searching
ordering = () # Contain only fields in your `custom-user-model` intended to ordering
filter_horizontal = () # Leave it empty. You have neither `groups` or `user_permissions`
fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('mobile',)}),
)
admin.site.register(UserModel, MyUserAdmin)
You are trying to use UserAdmin but you don't have fields which it refers to
groups
permissions
first name
last name
username
You should probably need to check UserAdmin class in depth and see what variables you should override
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2'),
}),
)
form = UserChangeForm
add_form = UserCreationForm
change_password_form = AdminPasswordChangeForm
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
search_fields = ('username', 'first_name', 'last_name', 'email')
ordering = ('username',)
filter_horizontal = ('groups', 'user_permissions',)
Also errors can give you a hint of where something went wrong