I want to edit the User Model in admin.py but I am not able to figure out how can I do this?
Here is the Image of Admin Panel of User Model
Can someone please help me? I want to add some customized fields in the User model.
You can do that by extending AbstractUser from django.
# models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _
class User(AbstractUser):
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
email = models.EmailField(
_('email address'),
unique=True,
blank=True
)
cellphone = models.CharField(
_('cell phone'),
max_length=20,
null=True, blank=True
)
Then you also need to specify this Custom user model in your settings. Specify path to the user model you've just created. <app_name>.<ModelClassName>
# settings.py
AUTH_USER_MODEL = 'users.User'
Lastly, your admin must also inherit from Django default UserAdmin, if you want to save your time from all the hassle of creating some methods they have already created. Now you can edit user admin the way you want by also getting advantage of all the
existing admin features.
# admin.py
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as OrigUserAdmin
User = get_user_model()
#admin.register(User)
class UserAdmin(OrigUserAdmin):
list_display = (
'id', 'first_name', 'last_name', 'username', 'email', 'is_active'
)
use 'AbstractUser' model to Extend pre define user model in Django.
then we cam easily add some field or add more information in usermodel.
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
Then we have to update our settings.py defining the AUTH_USER_MODEL property.
AUTH_USER_MODEL = 'core.User'
follow this link for more information:-https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html
Related
So I was trying to add an imagefield in my model using the UserModel, so I made this models
from django.contrib.auth.models import User
from django.db import models
class ProfileImage(models.Model):
user = models.OneToOneField(User,
on_delete=models.CASCADE,
editable=False)
avatar = models.ImageField()
def user_avatar(self):
return self.profileimage.avatar
User.add_to_class('user_avatar', user_avatar)
And I made an admin to see the imagefield in the users,
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
# Register your models here.
UserAdmin.fieldsets += ('Custom fields set', {'fields': ('user_avatar',)}),
I dont kno what is wrong with my code, when I open a user to see the image field and , does anyone know what is the problem?
In admin fields and fieldsets expects you to list actual columns in the database. user_avatar is a function you've written so you can't list it as a field on the User model because it doesn't exist in that table.
Make a more generic model for all types of user information, not just an image, like this;
class Profile(models.Model):
"""
Profile model
"""
user = models.OneToOneField(
verbose_name=_('User'),
to=settings.AUTH_USER_MODEL,
related_name='profile',
on_delete=models.CASCADE
)
avatar = models.ImageField()
Then you can access the avatar with request.user.profile.avatar or in your admin register your Profile model as an inline to the User;
from django.contrib import admin
from django.contrib.auth import get_user_model
from myapp.accounts.models import Profile
User = get_user_model()
class ProfileInline(admin.StackedInline):
model = Profile
max_num = 1
can_delete = False
class MyUserAdmin(admin.UserAdmin):
inlines = [ProfileInline]
# unregister old user admin
admin.site.unregister(User)
# register new user admin that includes a UserProfile
admin.site.register(User, MyUserAdmin)
I am making an app that wants the default user model to be extended. I want to customize some of the fields, like adding some restrictions to the username. For example, the username must be between 4 to 16 characters and may contain lowercase alphabets, dashes and dots only.
My question is that how to update these fields in django? What is the best practice to do it. My model is below.
from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUserManager(UserManager):
pass
class CustomUser(AbstractUser):
objects = CustomUserManager()
followers = models.ManyToManyField("self", related_name="following", symmetrical=False)
First need to add file forms.py to your project. Then import User model to your forms.py and models.py
from django.contrib.auth.models import User
How to extend defaul user model you can see here.
For max and min symbols check use Forms.py, for example:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
username = forms.CharField(max_length=16, min_length=4, required=True, error_messages= {"username_exists": "Username already exists."})
first_name = forms.CharField(max_length=30, required=False)
last_name = forms.CharField(max_length=30, required=False)
email = forms.EmailField(max_length=100, required=True, error_messages= {"invalid": "Please, enter correct E-mail"})
password1 = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)
widgets = {
'password': forms.PasswordInput(),
}
You can raise any error messages in your forms, look link higher.
How can i make a custom search function in django admin. I want to search all fields of the database tables and to find and retrieve the matches.
Is it possible?
Lets take an example of custom User models with below fields,
app_name/models.py
from django.contrib.auth.models import AbstractBaseUser
class User(AbstractBaseUser):
first_name = models.CharField(max_length=50)
middle_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
username = models.CharField(max_length=100)
Now the admin for this models would be,
app_name/admin.py
from django.contrib import admin
from app_name.models import User
class UserAdmin(admin.ModelAdmin):
search_fields = User._meta.get_all_field_names()
admin.site.register(User, UserAdmin)
User._meta.get_all_field_names() will return you a list of all the fields of User model.
I use django-primate. I override standard user class with 3 new fields:
from primate.models import UserBase, UserMeta
from django.db import models
class CustomUser(UserBase):
__metaclass__ = UserMeta
name = models.CharField(max_length=500, default='Jon Deg')
jabber_id = models.CharField(max_length=150, default='jabber#jabber.org')
title = models.CharField(max_length=20, blank=True)
And, of course, add admin.py:
from primate.admin import UserAdminBase
from django.contrib import admin
from django.contrib.auth.models import User
class UserAdmin(UserAdminBase):
pass
admin.site.register(User, UserAdmin)
Now in django-admin I can manage only 'name' and some other standard auth fields. How can I add, for example, jabber_id to django-admin?
My purpose is to see at the admin site only user name, email and phone number.
I've create UserProfile by extending User model:
model.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
name = models.CharField(max_length=50, null=True,blank=True)
address = models.CharField(max_length=50, null=True,blank=True)
phone = models.CharField(max_length=20, null=True,blank=True)
country = models.CharField(max_length=20, null=True,blank=True)
state = models.CharField(max_length=20, null=True,blank=True)
zip = models.CharField(max_length=10, null=True,blank=True)
code = models.CharField(max_length=40, null=True)
def user_email(self):
return self.user.email
admin.py
from myApp.models import UserProfile
from django.contrib import admin
class UserProfileAdmin(admin.ModelAdmin):
fields = ('name','phone',)
list_display = ('name','user_email',)
admin.site.register(UserProfile, UserProfileAdmin)
so on the list_display it works, I can see only the columns I've chosen, but when I add 'user_email' ( fields = ('name','user_email', 'phone',) )to fields I get when I try to go to admin site:
'UserProfileAdmin.fields' refers to field 'user_email' that is missing from the form.
Fields on a related model use two underscores. Dunno if it'll work in the admin though.
list_display = ('name','user__email',)
Just because I recently used it and you maybe want this, too: If you wan't to add an inline admin to the "User" admin page in Django you can do this (at least in Django 1.3) by doing:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from models import UserProfile
class UserProfileInlineAdmin(admin.StackedInline):
model = UserProfile
class MyUserAdmin(UserAdmin):
inlines = [ UserProfileInlineAdmin ]
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
You can't put editable fields from a related model into an admin form, without using inlines. You can show the field as a readonly value: just add it to readonly_fields.