Django: Unknown field(s) (avatar) specified for User - django

So I have this models
from django.db import models
from django.conf import settings
# Create your models here.
class ProfileImage(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
editable=False
)
avatar = models.ImageField()
def user_avatar(self):
return self.profileimage.avatar
And my admin.py
from django.contrib import admin
# Register your models here.
from django.contrib.auth.admin import UserAdmin
UserAdmin.fieldsets += ('Custom fields set', {'fields': ('avatar',)}),
I am using the User model, and I add to it a imagefield, but I want to see the image field in the admin page so a did that in admin.py but when I enter to the users admin this error appear:
Unknown field(s) (avatar) specified for User. Check fields/fieldsets/exclude attributes of class UserAdmin.

Well, what you should try to do is change your admin code and your models a little bit. Try this:
models.py
class Profile(models.Model):
user = models.OneToOneField(
verbose_name=_('User'),
to=settings.AUTH_USER_MODEL,
related_name='profile',
on_delete=models.CASCADE
)
avatar = models.ImageField()
and admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from accounts.models import ProfileImage
User = get_user_model()
class ProfileInline(admin.StackedInline):
model = ProfileImage
max_num = 1
can_delete = False
class MyUserAdmin(UserAdmin):
inlines = [ProfileInline]
# unregister old user admin
admin.site.unregister(User)
admin.site.unregister(Group)
# register new user admin that includes a UserProfile
admin.site.register(User, MyUserAdmin)

Your code should look like this
updated
Models.py
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)
admin.py
UserAdmin.fieldsets += ('Custom fields set', {'fields': ('user_avatar',)}),

Related

How to add a date and time column in my Django default user page in admin

I am using the Django default user model and in my admin, I can see 5 columns which are username, email address, first name, last name, and staff status. I need to add another column here that displays the date joined. Can anyone help here? thanks in advance
User / admin.py
from django.contrib import admin
from .models import Profile
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
class UserAdmin(AuthUserAdmin):
list_display = ('username', 'date_joined', 'email')
admin.site.register(Profile)
Profile Model:
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default = 'default.jpg', upload_to = 'profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self):
super().save()
Please refer to the documentation on this.
In your case you will want to alter your admin class to look something like:
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
#admin.register(User)
class UserAdmin(AuthUserAdmin):
...
list_display = (..., 'date_joined', ...)
...

Add the related objects of User and display them in User model in django admin

I am having two models projects and User in projects the User is related like shown below
models.py:
class project(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
room = models.ForeignKey(room,on_delete=models.CASCADE)
goal = models.ManyToManyField(goal)
design = models.ManyToManyField(design)
furniture = models.ForeignKey(furniture,on_delete=models.CASCADE)
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
Now here I want to display the extra column as projects in user page in django admin for every user when I click on that it should take to particular project detail page of that user
Screenshots:
This is the user list page
This is the project list page
This is the project detail page
admin.py:
from django.contrib import admin
from .models import project
class ProjectAdmin(admin.ModelAdmin):
readonly_fields = ('user','room','goal','design','furniture','created_at','updated_at')
admin.site.register(project,ProjectAdmin)
Please help me out Thanks in advance
You would need to write a custom admin for your User:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.safestring import mark_safe
UserModel = get_user_model()
admin.site.unregister(UserModel)
#admin.register(UserModel)
class CustomUserAdmin(UserAdmin):
list_display = (
'username', 'email', 'first_name', 'last_name', 'user_project'
)
def user_project(self, obj):
url = '/admin/modsy/project/{}/change/'.format(obj.project.pk)
return mark_safe('view project'.format(url))

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.

Customizing the user model: how to show related info in the admin

Django 1.10.2
Studying customization of the User model.
Trying to follow the documentaion https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model
I wish to store that department and show it in the admin.
The problem is that department doesn't appear.
I played with fieldsets and list_display, but failed.
Could you help me understand how to show the department in the admin?
admin.py
from django.contrib.auth.models import User
from django.db import models
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)
# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class EmployeeInline(admin.StackedInline):
model = Employee
can_delete = False
verbose_name_plural = 'employee'
# Define a new User admin
class UserAdmin(BaseUserAdmin):
inlines = (EmployeeInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

Django admin inline UserProfile field

Every user has (should have) a UserProfile object, and every UserProfile can have Locations against it (foreign key in Location). I want to show these Locations (and allow editing/adding/deleting them) in the User view in the admin site. Nested inlines aren't possible, so I'd like to add a LocationInline to the User page, which I'm unsure how to do.
models.py
from django.db import models
from registration.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
# ...
class Location(models.Model):
owner = models.ForeignKey(UserProfile)
# Address and stuff
admin.py
from django.contrib import admin
from django.contrib.auth.models import User
from main.models import UserProfile, Location
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
class UserProfileInline(admin.StackedInline):
model = UserProfile
max_num = 1
can_delete = False
class LocationInline(admin.TabularInline):
model = Location
extra = 1
class UserAdmin(AuthUserAdmin):
inlines = [UserProfileInline, LocationInline]
# Obviously doesn't work, because Location is from UserProfile, not User
# How can I make it use user.profile instead?
admin.site.unregister(User)
admin.site.register(User, UserAdmin)