Django - User, UserProfile, and Admin

后端 未结 3 2024
执念已碎
执念已碎 2020-12-04 18:29

I\'m trying to get the Django Admin interface to display information about my profile. It displays all of my users but no profile information. I\'m not quite sure how to g

相关标签:
3条回答
  • 2020-12-04 19:01

    This is not exactly an answer to your question BUT, according to Django Admin documentation, you can display information from UserProfile in your User "table". And you can make it searchable.

    That would look something like this (modifying answer from C. Alan Zoppa):

    class UserProfileAdmin(UserAdmin):
        inlines = [ UserProfileInline, ]
        def company(self, obj):
            try:
                return obj.get_profile().company
            except UserProfile.DoesNotExist:
                return ''
        list_display = UserAdmin.list_display + ('company',)
        search_fields = UserAdmin.search_fields + ('userprofile__company',)
    

    You might have an issue though with search if your profile class is no longer called UserProfile.

    0 讨论(0)
  • 2020-12-04 19:13

    The missing comma shouldn't matter. I suspect the problem is that you added a new admin.py but the development server didn't recognize it. If you restart the development server, it'll see the new file.

    0 讨论(0)
  • 2020-12-04 19:24

    I can't see exactly what's wrong, but here's a slightly simpler example that I know works. Put this is any working admin.py. Try adding a trailing comma to your inline-- some things break without it.

    from django.contrib import admin
    from django.contrib.auth.models import User
    from django.contrib.auth.admin import UserAdmin
    from accounts.models import UserProfile
    
    admin.site.unregister(User)
    
    class UserProfileInline(admin.StackedInline):
        model = UserProfile
    
    class UserProfileAdmin(UserAdmin):
        inlines = [ UserProfileInline, ]
    
    admin.site.register(User, UserProfileAdmin)
    
    0 讨论(0)
提交回复
热议问题