gpt4 book ai didi

python - 如何在 Django 管理中预填充 UserProfile 字段?

转载 作者:行者123 更新时间:2023-12-01 06:12:31 24 4
gpt4 key购买 nike

如果您使用以下命令,则在管理中预填充大多数模型字段(对于生成 slugs 很有用)似乎很简单:

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

但是当我使用下面的代码尝试预填充 UserProfile 字段时,它会给出此错误消息,即使我在 UserProfile 模型中显然有一个 slug。 (只是查找了错误的模型,我不知道如何解决这个问题......)

错误:

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

在settings.py中:

AUTH_PROFILE_MODULE = 'myapp.UserProfile'

在 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)

有人能找出这里错误的原因吗?

最佳答案

slugUserProfile 中的一个字段,但 prepopulated_fields = {"slug": ("name",)} 是一个属性UserProfileAdmin 的,应用于 User

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

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

关于python - 如何在 Django 管理中预填充 UserProfile 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5014044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com