开发者

Django User model fields at AdminModel

开发者 https://www.devze.com 2023-03-09 11:06 出处:网络
My purpose is to see at the admin site only user name, email and phone number. I\'ve create UserProfile by extending User model:

My purpose is to see at the admin site only user name, email and phone number.

I've create UserProfile by extending User model:

model.py

from django.db import models
from django.contrib.auth.models import User


class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    name = models.CharField(max_length=50, null=True,blank=True)
    address = models.CharField(max_length=50, null=True,blank=True)
    phone = models.CharField(max_length=20, null=True,blank=True)
    country = models.CharField(max_length=20, null=True,blank=True)
    state = models.CharField(max_length=20, null=True,blank=True)
    zip = models.CharField(max_length=10, null=True,blank=True)
    code = models.CharField(max_length=40, null=True)


    def user_email(self):
        return self.user.email

admin.py

from myApp.models import UserProfile
from django.contrib import admin


class UserProfileAdmin(admin.ModelAdmin):



    fields = ('name','phone',)
    list_display   = ('name','user_email',)


 admin.site.register(UserProfile, UserProfileAdmin)

so on the list_display it works, I can see only the columns I've chosen, but when I add 'user_email' ( fields = ('name','user_email', 'phone',) )to fields I get when I try to go to admin site:

'UserProfileAdmin.fields' refers to field 'user_email' that开发者_StackOverflow is missing from the form.


Fields on a related model use two underscores. Dunno if it'll work in the admin though.

list_display   = ('name','user__email',)


Just because I recently used it and you maybe want this, too: If you wan't to add an inline admin to the "User" admin page in Django you can do this (at least in Django 1.3) by doing:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from models import UserProfile


class UserProfileInlineAdmin(admin.StackedInline):
    model = UserProfile

class MyUserAdmin(UserAdmin):
    inlines = [ UserProfileInlineAdmin ]

admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)


You can't put editable fields from a related model into an admin form, without using inlines. You can show the field as a readonly value: just add it to readonly_fields.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号