Overwrite 'Personal info' field in the admin/Users? - python

During my first Django app i've managed to hit this 'road-block' where i'm trying to extend User model from my .forms file where forms.py looks like this:
#forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
phone = forms.CharField(max_length=50, required=False)
class Meta:
model = User
fields = ['username', 'email', 'phone', 'password1', 'password2']
class UserLoginForm(AuthenticationForm):
class Meta:
model = User
fields = ['username', 'password']
In my .models file i'm only having a 'Profile' model which is being registered within admin.py:
#admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import *
from .forms import UserRegisterForm
admin.site.unregister(User)
class CustomUserAdmin(UserAdmin, UserRegisterForm):
fieldsets = UserAdmin.fieldsets + (
(('Personal info'), {'fields': ('phone',)}),
)
admin.site.register(User, CustomUserAdmin)
admin.site.register(Profile)
...and i'm getting this back(bare in mind i've tried also passing just my form class which resulted in allot more errors):
#error
FieldError at /admin/auth/user/1/change/
Unknown field(s) (phone) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/auth/user/1/change/
Django Version: 3.0.4
So the end goal would be to have another field available in my Users/'Personal info'(that's been extended within forms.py) and also would be nice to get that field when creating a new user from within the admin page. Any help/idea would be greatly appreciated, thanks.

Related

Import-export module works not with User model for me in Django

I am trying to import new users to original User model form the Django admin site. I used to add the users one-by-one manually to the model but now I need to import lots of users and I need a solution to bulk import. I tried the code below, but I have an error:
django.contrib.admin.sites.NotRegistered: The model User is not registered
Please help me to solve this.
admin.py
from django.contrib import admin
from django.contrib.auth.models import User
from import_export.admin import ImportExportModelAdmin
from import_export import resources
class UserResource(resources.ModelResource):
class Meta:
model = User
fields = ('id','username','first_name', 'last_name', 'email' 'password1', 'password2')
class UserAdmin(ImportExportModelAdmin):
list_display = ('id','username','first_name', 'last_name', 'email')
resource_class = UserResource
pass
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

No user link in auth section of Django admin

I am trying to implement a custom user model, but under the auth url localhost:8000/admin/auth/ of the Django admin website my model is not showing up.
I found an answer at the link below to the overall problem, but when trying to implement it myself I still do not see the users in the auth section of the Django admin.
No “Users” link in “Auth” section of Django admin site
what am I doing wrong here ?
models.py
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
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
CustomUser = get_user_model()
class CustomUserAdmin(UserAdmin):
form = CustomUserChangeForm
add_form = CustomUserCreationForm
model = CustomUser
list_display = (
"email",
"username",
)
fieldsets = (
(None, {"fields": ("email", "password")}),
("Permissions", {"fields": ("is_admin", "groups", "user_permissions")}),
)
admin.site.register(CustomUser, CustomUserAdmin)
forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ("email", "username")
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ("email", "username")
I faced the same problem:
created my own user model
in admin, groups and my user model are not listed in same (auth) section
My solution was basically to put django groups into my app to have it displayed in the same section, because django creates admin sections for each app.
create your own group model as proxy object in your models.py
from django.contrib.auth.models import Group as DjangoGroup
...
class Group(DjangoGroup):
class Meta:
proxy = True
verbose_name = _('group')
verbose_name_plural = _('groups')
(un)register your models in admin.py
from django.contrib.auth.admin import GroupAdmin as DjangoGroupAdmin
from django.contrib.auth.models import Group as DjangoGroup
from .models import CustomUser, Group
...
admin.site.register(CustomUser, CustomUserAdmin)
admin.site.unregister(DjangoGroup)
admin.site.register(Group, DjangoGroupAdmin)

How do I add an extra field in Django Admin?

I'm just starting out with Django and I've just revamped my project so that instead of using the base user, I use an AbstractUser model, as defined in my models.py folder
#accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
# add additional fields in here
favourite_colour = models.CharField("Favourite Colour", max_length=100)
def __str__(self):
return self.email
I've also created the creation forms that work well with my signup system
#accounts/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import User
from django import forms
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = ('username', 'email', 'favourite_colour')
help_texts = {
'username': 'Make something unique',
'email': None,
}
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email', 'favourite_colour')
And now I am trying to edit the admin page so that I can change a users favourite_colour attribute. So far I have this in my admin.py file
#accounts/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 = ['username', 'email', 'favourite_colour']
admin.site.register(CustomUser, CustomUserAdmin)
Which shows me the favourite_colour of each user
My question is, how do I make a field to edit this CustomUser attribute once you've clicked on a user?, for example like this I'd welcome any help at all as I'm not too good at reading the docs. Please ask if you need more code adding to the question, I've never asked a Django question before
After some more looking I found a fieldsets option (link1, link2, link3) that can be used inside of my CustomUserAdmin code. In my CustomUserAdmin class I now have:
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['username', 'email', 'favourite_colour']
fieldsets = UserAdmin.fieldsets + (
('Extra Fields', {'fields': ('favourite_colour',)}),
)

Django choosen user permission is not showing in admin page

I tried to extend default Django user in my project by using AbstractUser. In Django admin i couldn't see choosen user permissions.
Here is my work
from django.db import models
from django.contrib.auth.models import AbstractUser
class ExtendedUser(AbstractUser):
bio = models.TextField(max_length=500, blank=True)
birth_date = models.DateField(null=True, blank=True)
After that i add my extended user in admin.py
class ExtendedUserAdmin(admin.ModelAdmin):
pass
admin.site.register(ExtendedUser, ExtendedUserAdmin)
Also add AUTH_USER_MODEL in settings.py
AUTH_USER_MODEL = '_aaron_user.ExtendedUser'
I solved this problem by importing UserAdmin and register my ExtendedUser with this model in my admin.py file.
from.models import ExtendedUser
from django.contrib.auth.admin import UserAdmin
admin.site.register(ExtendedUser, UserAdmin)
The result is choosen groups and choosen user permissions are now available.
For those who use custom User model you need to add next code in admin.py:
filter_horizontal = ('groups', 'user_permissions',)
For example:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
search_fields = ('email',)
list_display = ('email', 'is_staff', 'is_active',)
list_filter = ('email', 'is_staff', 'is_active',)
filter_horizontal = ('groups', 'user_permissions',)
class Meta:
model = CustomUser
admin.site.register(CustomUser, CustomUserAdmin)
The line filter_horizontal is taken from original django.contrib.auth.admin class UserAdmin
After that 'Choosen groups' and 'Choosen user permissions' are available.
In my case it was missing bootstrap files from static/admin|css|js

Adding phonenumber field to signup form Django

When I enter the details in this form and press the submit button , I don't see the values of phoneno and otp getting saved in the database .The fields phone number and otp are not shown at all .
SEE image only username is saved and the otp and phone number fields are not displayed nor saved
This is my signup/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# Create your models here.
class allusers1(UserCreationForm):
phoneno1=forms.CharField(label = "phonewa",max_length=10)
otp1=forms.IntegerField(label="OTPP",required=False)
class Meta:
model=User
fields=(
'username',
'password',
'phoneno1',
'otp1',
)
def save(self,commit=True):
user=super(allusers1,self).save(commit=False)
user.username1=self.cleaned_data['username']
user.password1=self.cleaned_data['password']
user.phoneno1=self.cleaned_data['phoneno1']
user.otp1=self.cleaned_data['otp1']
if commit:
user.save()
return user
This is mysignup/forms.py
from django.shortcuts import render
from .forms import allusers1
def signup(request):
form1=allusers1(request.POST or None)
if form1.is_valid():
form1.save()
context = {
"form1": form1,
}
return render(request, "signup.html",context)
Your User model is the default django.contrib.auth.models.User that you import in the second line. This model has predefined fields. otp1and phoneno1 are not amongst them as you can see from the docs. So when you save a Userinstance, these attributes are simply ignored.
So you have to extend the User model like described in the docs (Django 2.0).
# models.py
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
otp1 = models.IntegerField(null=True)
phoneno1 = models.CharField(max_length=10)
# settings.py
settings.AUTH_USER_MODEL = 'myapp.User'
# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)
You won't need a special form then for the Django admin. Your own model will inherit everything Django's User model brings with it, plus your own fields / methods.

Categories