简体   繁体   中英

Multiselect form in Django Admin

I'm attempting to add a multi-select widget to my admin view that corresponds to a char-field.

models.py

class Campaign(models.Model):
    name = models.CharField(max_length=128)
    start_date = models.DateTimeField(default=timezone.now)
    end_date = models.DateTimeField(blank=True, null=True)
    budget = models.IntegerField()
    target = models.IntegerField()
    component_choices = models.CharField(max_length=128, null=True, blank=True)

admin.py

class CampaignAdmin(admin.ModelAdmin):
    fieldsets = (
        ('Main', {
            'fields': ('name', ('start_date', 'end_date',),),
        }),
        ('Budget', {
            'fields': ('budget', 'target',),
        }),
        ('Payment', {
            'fields': ('payment_terms', 'payment_initial', 'payment_per_mvm'),
        }),
    )

    form = ComponentChoicesForm

admin.site.register(Campaign, CampaignAdmin)

forms.py

class ComponentChoicesForm(ModelForm):

    component_type_choices = tuple(
        (x.id, str(x))
        for x in ComponentType.objects.all()
    )

    class Meta:
        model = ComponentType
        fields = '__all__'

    available_components = forms.MultipleChoiceField(
        choices=component_type_choices)

However the above code only displays the fieldsets and not the ComponentTypeChoices form at all. My intent is to have the user select from the choices i generate in forms.py in the admin.py in order to populate the Campaign.component_choices field.

You have created a form for a different model and used it in Campaign model admin. You should create a modelform for Campaign model rather than ComponentType .

Your forms and model admin should be like this,

forms.py

class CampaignForm(ModelForm):

    class Meta:
        model = Campaign
        fields = '__all__'

    OPTIONS = (('a', 'A'),('b', 'B'),('c', 'C'))

    available_components = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                     choices=OPTIONS) 

admin.py

class CampaignAdmin(admin.ModelAdmin):
    form = CampaignForm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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