如何预先填写Django管理员中的UserProfile字段? [英] How to prepopulate UserProfile fields in the Django admin?

查看:229
本文介绍了如何预先填写Django管理员中的UserProfile字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用以下方式,预先管理管理员中的大多数模型字段(对于生成小数块有用)似乎很简单:

Prepopulating most model fields in the admin (useful for generating slugs) seems to be straightforward if you use:

prepopulated_fields = {"slug": ("name",)}  

但是当我使用下面的代码尝试要预填充UserProfile字段,它会给出此错误消息,即使我明确地在UserProfile模型中有一个小插件。 (只是看错了模型,我不知道如何解决这个问题...)

But when I use the code below to try to prepopulate a UserProfile field, it gives this error message, even though I clearly have a slug in the UserProfile model. (It's just looking in the wrong model and I don't know how to fix this...)

错误:


在/ admin / 不正确地配置

'UserProfileAdmin.prepopulated_fields'是指从模型User中缺少的字段'slug'。

ImproperlyConfigured at /admin/
'UserProfileAdmin.prepopulated_fields' refers to field 'slug' that is missing from model 'User'.

在settings.py:

In settings.py:

AUTH_PROFILE_MODULE = 'myapp.UserProfile'

在models.py:

In models.py:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    slug = models.SlugField(max_length=50)

在admin.py:

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    max_num = 1
    can_delete = False

class UserProfileAdmin(admin.ModelAdmin):
    inlines = [UserProfileInline]
    prepopulated_fields = {"slug": ("name",)}

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

这个错误的原因在这里?

Can anyone spot reason for the error here?

推荐答案

slug code> UserProfile ,但 prepopulated_fields = {slug:(name,)} 是<$ c的属性$ c> UserProfileAdmin ,它应用于用户

slug is a field in UserProfile, but the prepopulated_fields = {"slug": ("name",)} is an attribute of UserProfileAdmin, which is applied to User.

prepopulated_fields 触发一些JavaScript,它会自动生成同一模型的某些其他字段的值的SlugField的值。您正在尝试的是预先填写不同模型的字段 UserProfileAdmin 应用于用户 prepopulated_fields 指的是 slug ,这是模型用户未知的字段。它在 UserProfile 中定义。

prepopulated_fields triggers some javascript that autogenerates the value of a SlugField out of the values of some other fields of the same model. What you are trying is to prepopulate a field of a different model. The UserProfileAdmin is applied to User, the prepopulated_fields refers to the field slug which is unknown to the model User. It is defined in UserProfile.

这就是为什么我认为这里最大的问题是名字 UserProfileAdmin 应该是 UserAdmin 。不要混淆应用了内联的 prepopulated_fields 的模型。即使有一个OneToOne关系,它仍然是一个不同的模型。

That's why I think that the biggest problem here is the name UserProfileAdmin which should rather be UserAdmin. Don't confuse the model to which the prepopulated_fields is applied with the one that is inlined. Even when there is a OneToOne relation, it still is a different model.

这篇关于如何预先填写Django管理员中的UserProfile字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆