简体   繁体   English

如何将用户列表添加到Django管理面板

[英]How to add list of users to django admin panel

I have a model with start_date and end_date . 我有一个具有start_dateend_date的模型。 I would like to add a list of users at the bottom so that an admin can pick from a list of users that are associated with this model. 我想在底部添加一个用户列表,以便管理员可以从与此模型关联的用户列表中进行选择。

This is how the model looks in admin panel at the moment 这是该模型目前在管理面板中的外观

在此输入图像描述

My model looks like this in models.py 我的模型在models.py看起来像这样

class MyPeriod(ValidateOnSaveMixin, models.Model):
    start_date = models.DateField(unique=True)
    end_date = models.DateField()

In admin.py I tried adding filter_horizontal like this but it gave me errors admin.py我尝试像这样添加filter_horizontal但它给了我错误

class MyPeriodAdmin(admin.ModelAdmin):
    list_display = ('start_date', 'end_date',)
    filter_horizontal = ('user',)

The value of 'filter_horizontal[0]' refers to 'user', which is not an attribute of 'MyPeriod'. “ filter_horizo​​ntal [0]”的值表示“用户”,它不是“ MyPeriod”的属性。

Your current model does not contain an association between period and users. 您当前的模型不包含期间和用户之间的关联。 You have to specify a ForeignKey relation with the User model, such as: 您必须指定与User模型的ForeignKey关系,例如:

from django.conf import settings
...
class MyPeriod(ValidateOnSaveMixin, models.Model):
    start_date = models.DateField(unique=True)
    end_date = models.DateField()
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

After this addition (and applying migrations to reflect the changes to the actual database) you will be able to assign User s to your MyPeriod model. 添加之后(并应用迁移以反映对实际数据库的更改),您将能够将User分配给MyPeriod模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM