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 that share this CharField but they each have different choices.

class MyModel(MyBaseModel):
    stuff = models.CharField('Stuff', max_length=255, default=None)

    class Meta:
        proxy = True

class MyModelAdmin(admin.ModelAdmin):
    fields = ('stuff',)
    list_display = ('stuff',)
admin.site.register(MyModel, MyModelAdmin)

For this model I want to use MY_CHOICES in MyModelAdmin.

Do I override a widget? Do I need to override the whole form?

up vote 16 down vote accepted
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

  • 1
    Thanks a lot, I was digging through the docs and missed this :S there's no way to avoid creating a ModelForm is there? – Rudolf Olah Sep 27 '12 at 16:56
  • I don't think there is. Why? – demux Sep 27 '12 at 21:15
  • 1
    just checking, I thought there might be an option to just pass it to the charfield or as a meta option or something else. – Rudolf Olah Sep 27 '12 at 21:47

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

You need to think of how you are going to store the data at a database level. I suggest doing this:

  1. Run this pip command: pip install django-multiselectfield
  2. In your models.py file:

    from multiselectfield import MultiSelectField
    
    MY_CHOICES = (('item_key1', 'Item title 1.1'),
              ('item_key2', 'Item title 1.2'),
              ('item_key3', 'Item title 1.3'),
              ('item_key4', 'Item title 1.4'),
              ('item_key5', 'Item title 1.5'))
    
    class MyModel(models.Model):
          my_field = MultiSelectField(choices=MY_CHOICES)
    
  3. In your settings.py:

     INSTALLED_APPS = (
          'django.contrib.auth',
          'django.contrib.contenttypes',
          'django.contrib.sessions',
          'django.contrib.sites',
          'django.contrib.admin',
    
          #.....................#
    
          'multiselectfield',
    )
    
  4. Watch the MAGIC happen!

Source:

in Gerard's answer, if you keep :

def __init__(self, stuff_choices=(), *args, **kwargs):

then when you will try to add new model from admin, you will always get 'This field is required.' for all required fields.

you should remove stuff_choices=() from initialization:

def __init__(self,*args, **kwargs):

You need to override the form the ModelAdmin is going to use:

class MyForm(forms.ModelForm):
    stuff = forms.CharField('Stuff', max_length=255, choices=MY_CHOICES, default=None)

    class Meta:
        model = MyModel
        fields = ('stuff', 'other_field', 'another_field')


class MyModelAdmin(admin.ModelAdmin):
    fields = ('stuff',)
    list_display = ('stuff',)
    form = MyForm()

If you need your choices to be dynamic, maybe you could do something similar to:

class MyForm(forms.ModelForm):
    stuff = forms.CharField('Stuff', max_length=255, choices=MY_CHOICES, default=None)

    def __init__(self, stuff_choices=(), *args, **kwargs):
        # receive a tupple/list for custom choices
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['stuff'].choices = stuff_choices

and in your ModelAdmin's __init__ define what MY_CHOICES is going to be and assign the form instance there instead:

Good luck! :)

  • I thought the forms.CharField was like models.CharField and had the choices option. But I decided to double check and found out that forms has ChoiceField (see my answer). – demux Sep 27 '12 at 17:00
  • I need to say: Million thanks! Couldn't find anywhere the solution for generating choices dependent on the model instance of the form. And here, in a ModelForm constructor, the instance is available. – ceruleus May 9 at 6:59

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.