Django-用户、用户配置文件和管理员

2024-04-26 22:06:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让Django管理界面显示关于我的个人资料的信息。它显示我的所有用户,但没有配置文件信息。我不太确定如何使它发挥作用。

我在谷歌上快速搜索后发现了这段代码:

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

admin.site.unregister(User)

class UserProfileInline(admin.StackedInline):
    model = UserProfile

class UserProfileAdmin(UserAdmin):
    inlines = [UserProfileInline]

admin.site.register(User, UserProfileAdmin)

然而,我认为它不起作用。当我登录到管理页面时,我会看到用户、组和站点。我点击用户,我看到我所有用户的列表,但没有任何个人资料的迹象。点击一个用户会显示该用户的信息,但仍然没有配置文件信息。

如果有帮助,这里是我的模型声明:

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

class UserProfile(models.Model):
    company = models.CharField(max_length=30)
    user = models.ForeignKey(User, unique=True)

我的注册码是:

def register(request):
    if request.method == 'POST':
        uf = UserForm(request.POST)
        upf = UserProfileForm(request.POST)
        if uf.is_valid() and upf.is_valid():
            user = uf.save()
            userprofile = upf.save(commit=False)#need to get the user profile object first
            userprofile.user = user #then set the user to user
            userprofile.save() #then save to the database
            return HttpResponseRedirect('/auth/login/')
    else:
        uf = UserForm()
        upf = UserProfileForm()
    return render_to_response('register.html', dict(userform=uf,userprofileform=upf),context_instance=RequestContext(request))

Tags: django用户fromimportauth信息adminmodels
3条回答

丢失的逗号不重要。我怀疑问题是您添加了一个新的admin.py,但是开发服务器没有识别它。如果重新启动开发服务器,它将看到新文件。

我看不出到底是什么问题,但这里有一个稍微简单的例子,我知道是有效的。这是任何一个正在工作的管理员。尝试在内联中添加一个尾随逗号——有些东西没有它就中断了。

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)

这并不完全是对您的问题的回答,但是,根据Django Admin documentation,您可以在用户“表”中显示来自UserProfile的信息。你可以让它搜索。

这看起来像这样(修改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',)

如果您的profile类不再被称为UserProfile,那么您在搜索时可能会遇到问题。

相关问题 更多 >