我想在 Django 用户配置文件编辑页面中显示一个模型字段,即 module_name 只读。模型 Category 与 Profile 模型具有 manytomany 关系。
类别
id category_name module_name
1 A X
2 B Y
profile_category
id profile_id category_id
1 2 1
例如。当我在管理页面上编辑 2 的用户 ID 时,如果类别 ID 1 是,我想显示模块名称 X分配给用户 id 2
模型.py
class Category(models.Model):
category_name = models.CharField(max_length=150, blank=False, null=True, default="", unique=True)
module_name = models.TextField(blank=False, null=True)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name ='profile')
phone_number = PhoneNumberField( blank=True, null=True)
organisation = models.CharField(max_length=30, blank=True)
category = models.ManyToManyField(Category)
admin.py
class ProfileInline(admin.StackedInline):
model = Profile
filter_horizontal = ('category',)
class CustomUserAdmin(UserAdmin):
inlines = (ProfileInline, )
list_select_related = ( 'profile', )
请建议这是否可能。
非常感谢任何帮助/建议。提前致谢。
请您参考如下方法:
方法一
使用readonly_fields它继承自 admin.BaseModelAdmin。
class ProfileInline(admin.StackedInline):
model = Profile
readonly_fields = ('module_names',)
def module_names(self, instance):
# Write a get-method for a list of module names in the class Profile
# return HTML string which will be display in the form
return format_html_join(
mark_safe('<br/>'),
'{}',
((line,) for line in instance.get_module_names()),
) or mark_safe("<span>The user belongs to no category</span>")
# short_description functions like a model field's verbose_name
module_names.short_description = "Module names"
方法二
对于旧版本的 admin 站点,您可以 Hook admin.StackedInline 的 get_fieldsets 方法。此方法已发布 here有一个很好的例子。
