Django admin choice field

前端 未结 7 1649
日久生厌
日久生厌 2020-12-18 22:48

I have a model that has a CharField and in the admin I want to add choices to the widget. The reason for this is I\'m using a proxy model and there are a bunch of models tha

7条回答
  •  萌比男神i
    2020-12-18 23:04

    You can override formfield_for_choice_field() that way you don't need to create a new form.

    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().formfield_for_choice_field(db_field, request, **kwargs)
    

    See formfield_for_choice_field

提交回复
热议问题