Incorrect work redefined form in django admins - django

I've created custom model Profile and linked it to the User model which works fine. But, now I want to create custom UserCreateForm in Django admin. I redefined it and added necessary fields, but after that still shows, all fields from profile model, ex: phone, home_address. I need fields displayed as : 'first_name', 'last_name', 'username', 'password1', 'password2' in the UserCreateForm. What have I done wrong?
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class NewUserCreateForm(UserCreationForm):
class Meta:
fields = ('username', 'first_name', 'last_name',)
class ProfileInline(admin.TabularInline):
model = Profile
class UserAdmin(UserAdmin):
add_form = NewUserCreateForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('first_name', 'last_name', 'username','password1', 'password2', ),
}),
)
inlines = [ProfileInline]
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

Firstly your models.py file will be :
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user_id = models.OneToOneField(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=100)
address = models.CharField(max_length=256)
...
Then your admin.py file.
from.models import Profile
# Register your models here.
class ProfileAdmin(admin.ModelAdmin):
model = Profile
exclude = ['phone',] # Or whatever you don't want to display.
admin.site.register(Profile, ProfileAdmin)
For extended implementation please add or remove based on your needs.
Hope it helps.

Related

User password is not hashed when creating through Django admin panel

I have inherited the user class to make custom authentication. I do not get password hashing this way. It just stores as plain text in MySQL database. I have created staff through admin panel and unable to login as staff. Furthermore I have also created auth API endpoints using DRF and Djoser and am unable to login with the user profiles created through Django admin panel.
Here is my code.
models.py
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass
admin.py
from .models import User
class UserAdmin(admin.ModelAdmin):
pass
admin.site.register(User, UserAdmin)
I have seen old replies in Stack Overflow suggesting changing the parent class to django.contrib.auth.admin.UserAdmin . When I try this the add user template form only has 3 fields. Username, Password and Password Confirmation.
admin.py
from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin
from .models import User
class UserAdmin(DefaultUserAdmin):
pass
admin.site.register(User, UserAdmin)
How do I solve this problem.
I wrote a custom UserAdmin as well so i guess i can help you a little bit with that
try this one:
#admin.register(User)
class UserAdmin(UserAdmin):
"""Define admin model for custom User model with no email field."""
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
list_display = ('email', 'is_staff')
search_fields = ('email',)
ordering = ('email',)
And i also think that there`s problems in your models.py bcs you dont have userManager
UserManager uses when you`re creating user so i guess problem in that

Django 3: Setting user email to be unique, minimal viable solution

I'm writing a simple app, and I'm totally happy with Django User model, except that I want a user email to be unique and obligatory field.
I have developed a solution, but I'm wondering if I'm missing something.
a) If you think that something is missing in the solution below please let me know
b) If you think that you have a better solution please share
This is what I did
Created a custom user model
# customers/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
email = models.EmailField(verbose_name='Email', unique=True, blank=False, null=False)
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['email']
Added AUTH_USER_MODEL = 'customers.User' to settings.py
Changed a reference to User model:
User = get_user_model()
Modified admin.py in order to be able to add users using Django admin.
# customers/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model
User = get_user_model()
class CustomUserAdmin(UserAdmin):
list_display = ('username', 'email', 'is_staff')
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2'),
}),
)
admin.site.register(User, CustomUserAdmin)
I hope this one you are looking for
Use the below code snippets in any of your models.py
models.py
from django.contrib.auth.models import User
User._meta.get_field('email')._unique = True
django version : 3.0.2
Reference : Django auth.user with unique email
https://stackoverflow.com/a/64075027/6651010

Adding "group" field in Django User Admin

I am trying to add a "group" field to show group permissions on the user panel in Django 3.1.2. I tried combining this and this, but always end up in either The model User is already registered with 'auth.UserAdmin' or The model User is not registered (when trying to unregister first):
from django.contrib import admin
from django.contrib.auth.models import User
# fails in "model User not registered"
admin.site.unregister(User)
#fails in already registered with auth.UserAdmin
#admin.register(User)
class UserAdmin(admin.ModelAdmin):
def group(self, user):
return ' '.join([g.name for g in user.groups.all()])
list_display = ['username', 'email', 'first_name', 'last_name', 'is_active', group]
list_filter = ['groups', 'is_staff', 'is_superuser', 'is_active']
How would I correctly register my custom UserAdmin?
I don't remeber, where I saw answer on SO, but do like:
admin.site.unregister(User) before.
Than modificate admin.model, as you wish, and then, register again.
from django.contrib.auth.models import User, Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
admin.site.unregister(User)
class GroupInline(admin.StackedInline):
model = Group
#admin.register(User)
class UserAdmin(BaseUserAdmin):
inlines = (GroupInline,)
If you want to show the group a user belong to in the list display:
#admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
def group(self, user):
groups = []
for group in user.groups.all():
groups.append(group.name)
return ' '.join(groups)
group.short_description = 'Group'
and now in your list_display you can have it as this:
list_display = ['username', 'email', 'first_name', 'last_name', 'is_active', 'group']
I hope this works for you

How do I add or delete attributes on the 127.0.0.1:8000/admin/auth/user page?

How do I add or delete attributes on the 127.0.0.1:8000/admin/auth/user page?
I don't know how to add or remove properties from an existing page
class CustomAdmin(admin.ModelAdmin):
list_display = ['emp_no', 'first_name', 'last_name', 'gender', 'birth_date', 'hire_date']
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Nothing changes
try this code to changes the django admin auth user fields display
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
class CustomAdmin(UserAdmin):
list_display = ['emp_no', 'first_name', 'last_name', 'gender', 'birth_date', 'hire_date']
admin.site.register(User, CustomAdmin)
I advise you to change the admin page name (to be more specific) and unregister group if you don't need it (yet) :
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
admin.site.site_header = 'Your administration name'
class CustomAdmin(UserAdmin):
list_display = ['emp_no', 'first_name', 'last_name', 'gender', 'birth_date', 'hire_date']
admin.site.register(User, CustomAdmin)
admin.site.unregister(Group)

Adding extra field in admin for custom user in Django 1.11

I have a custom user model which is subclassed by AbstractUser with an added custom field.
# model.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
ADM = 'admin'
MEMBER = 'member'
ROLE_CH = ((ADM, 'Administrator'), (MEMBER, 'Member'))
role = models.CharField(max_length=20, choices=ROLE_CH, blank=True)
This model is also registered as the default auth model in settings.py
# settings.py
AUTH_USER_MODEL = "main.CustomUser"
Then in admin.py as per the documentation, I create a custom form which extends UserCreationForm and then register it to the custom user.
# admin.py
from django.contrib import admin
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = UserCreationForm.Meta.fields + ('role',)
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
admin.site.register(CustomUser, CustomUserAdmin)
However, it does not work as expected. The Add User form remains the default one i.e. only username, password and password confirmation fields are present. The role field does not appear.
Use form attribute instead of add_form:
class CustomUserAdmin(ModelAdmin):
form = CustomUserCreationForm
admin.site.register(CustomUser, CustomUserAdmin)
UPD
First answer is correct only for ModelAdmin base class, since it doesn't have add_form attribute.
For UserAdmin you should update add_fieldsets attribute:
class CustomUserAdmin(UserAdmin):
add_fieldsets = UserAdmin.add_fieldsets + (
(None, {
'fields': ('role',),
}),
)
admin.site.register(CustomUser, CustomUserAdmin)
In this case you dont even required add_form.