Django admin choice field

前端 未结 7 1680
日久生厌
日久生厌 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条回答
  •  被撕碎了的回忆
    2020-12-18 22:53

    from django.contrib import admin
    from django import forms
    
    class MyModel(MyBaseModel):
        stuff = models.CharField('Stuff', max_length=255, default=None)
    
        class Meta:
            proxy = True
    
    class MyModelForm(forms.ModelForm):
        MY_CHOICES = (
            ('A', 'Choice A'),
            ('B', 'Choice B'),
        )
    
        stuff = forms.ChoiceField(choices=MY_CHOICES)
    
    class MyModelAdmin(admin.ModelAdmin):
        fields = ('stuff',)
        list_display = ('stuff',)
        form = MyModelForm
    
    admin.site.register(MyModel, MyModelAdmin)
    

    See: https://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield

提交回复
热议问题