how to modify choices on admin pages - django

后端 未结 4 785
猫巷女王i
猫巷女王i 2020-12-15 11:27

I have a model that has a field named \"state\":

class Foo(models.Model):
    ...
    state = models.IntegerField(choices = STATES)
    ...

4条回答
  •  一个人的身影
    2020-12-15 12:08

    When you create a new admin interface for a model (e.g. MyModelAdmin) there are specific methods for override the default choices of a field. For a generic choice field:

    class MyModelAdmin(admin.ModelAdmin):
        def formfield_for_choice_field(self, db_field, request, **kwargs):
            if db_field.name == "status":
                kwargs['choices'] = (
                    ('accepted', 'Accepted'),
                    ('denied', 'Denied'),
                )
                if request.user.is_superuser:
                    kwargs['choices'] += (('ready', 'Ready for deployment'),)
            return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)
    

    But you can also override choices for ForeignKey and Many to Many relationships.

提交回复
热议问题