My site makes use of Django's User Authentication User model and a custom UserProfile model to store some additional data (birthday, etc.). Is there a way to create a view in Django admin that weaves together fields from both the User and UserProfile models?
I suspect that this code snippet is not even close, but maybe it will help illustrate what I'm trying to do:
from django.contrib import admin from django.contrib.auth.models import User from userprofile.models import UserProfile class UserProfileAdmin(admin.ModelAdmin): list_display = ('name', 'gender', 'User.email') #user.email creates the error - tried some variations here, but no luck. admin.site.register(UserProfile, UserProfileAdmin)
Error message:
ImproperlyConfigured: UserProfileAdmin.list_display[2], 'User.email' is not a callable or an attribute of 'UserProfileAdmin' or found in the model 'UserProfile'.
Ultimately, I'm trying to create an admin view that has first & last name from UserProfile and email from User.
To be able to edit multiple objects from one Django admin, you need to use inlines. You can see the form to add and edit Villain inside the Category admin. If the Inline model has alot of fields, use StackedInline else use TabularInline .
The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.
get_absolute_url allows to keep your object DRY. To have a url which defines that object instance. In most case a detail page for that object.
for displaying user email you need to have a method on UserProfile
or UserProfileAdmin
that returns the email
on UserProfile
def user_email(self): return self.user.email
or on UserProfileAdmin
def user_email(self, instance): return instance.user.email
then change your list_display
to
list_display = ('name', 'gender', 'user_email')
Related docs: ModelAdmin.list_display
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With