16👍
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()
1👍
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.
- [Django]-How to display multi-word app names properly (i.e. with spaces) in Django admin?
- [Django]-Is it possible to use context processors in Django without a request object?
- [Django]-How to query for distinct groups of entities which are joined via a self-referential many-to-many table?
- [Django]-Django send_mail results in Error 60, Operation Timed Out on Mac OSX
0👍
Using piquadrat’s answer worked for me, but needed to add a line to define the queryset for the M2M. See this link.
- [Django]-Easiest way to write a Python program with access to Django database functionality
- [Django]-Why isn't web2py more readily adopted?
- [Django]-Deploy Django\Tornado on Heroku
- [Django]-Pass data from one view to another django
- [Django]-Customize user's admin panel permission only to read(not delete,edit or add)