简体   繁体   中英

Django ModelForm CheckBox Widget

I'm currently have an issue, and likely overlooking something very trivial. I have a field in my model that should allow for multiple choices via a checkbox form (it doesn't have to be a checkbox in the admin screen, just in the form area that the end-user will see). Currently I have the field setup like so:

# Type of Media
MEDIA_CHOICES = (
    ('1', 'Magazine'),
    ('2', 'Radio Station'),
    ('3', 'Journal'),
    ('4', 'TV Station'),
    ('5', 'Newspaper'),
    ('6', 'Website'),
)
media_choice = models.CharField(max_length=25,
    choices=MEDIA_CHOICES)

I need to take that and make a checkbox selectable field in a form out of it though. When I create a ModelForm, it wants to do a drop down box. So I naturally overrode that field, and I get my checkbox that I want. However, when the form's submitted, it would appear that nothing useful is saved when I look at the admin screen. The database does however show that I have a number of things selected, which is a positive sign. However, how can I get that to reflect in the admin screen properly?

Edit: FWIW I'll gladly accept documentation links as answers, because it would seem I'm just glossing over something obvious.

In such a case, the easiest way is to put the choices into a separate model and then use a ManyToMany relationship. After that, you simply override the ModelForm's widget for that field to use forms.CheckboxSelectMultiple and Django will automatically do the right thing. If you insist to use a CharField, you'll probably have to do something like this snippet .

@ 2. comment: how are you overriding the widget? This is how I do it and it works flawlessly:

class SomeModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SomeModelForm, self).__init__(*args, **kwargs)
        self.fields['some_field'].widget = forms.CheckboxSelectMultiple()

I've just started to look into widgets assignment with ModelForms. In a lot of examples I've seen, piquadrat's included, the Form's __ init __ method is overridden.

I find this a little confusing, and just overriding the desired field is more natural for me:

class SomeModelForm(forms.ModelForm):
    some_field = forms.CharField(choices=MEDIA_CHOICES,
                                 widget=forms.CheckboxSelectMultiple)
    class Meta:
        model=SomeModel

Note: I'm using Django 1.1.

Using piquadrat's answer worked for me, but needed to add a line to define the queryset for the M2M. See this link .

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