51đź‘Ť
âś…
class GameForm(forms.ModelForm):
name = forms.CharField(max_length=15, label='Name')
url = forms.URLField(label='URL', initial='http://')
cats = forms.ModelMultipleChoiceField(
queryset=Category.objects.all(),
widget=forms.CheckboxSelectMultiple,
required=True)
class Meta:
model = Game
fields = ('name','url','cats')
that should fix your view, but i’m not sure about the admin. still looking… will edit if i find anything.
👤Brandon Henry
46đź‘Ť
Here is how I solved it (Edit: and the admin thing)
Forms:
cats = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Category.objects.all())
(It was the queryset part I couldn’t find..)
View:
cats = form.cleaned_data['cats']
game.cats = cats
And that’s all the code needed to save the data.
Edit:
here is a solution for the admin
Models:
from django.contrib import admin
from django.forms import CheckboxSelectMultiple
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
Admin:
from gamesite.games.models import Game, MyModelAdmin
admin.site.register(Game, MyModelAdmin)
It’s kind of quirky in looks, but works!
If someone finds a way to make it more “clean” please post!
Cheers!
👤Grétar Jónsson
- [Django]-How can I detect Heroku's environment?
- [Django]-Retrieving list items from request.POST in django/python
- [Django]-How can I resolve 'django_content_type already exists'?
4đź‘Ť
Found this on from Chase Seibert, Engineering Manager of Dropbox
from django.db import models
from django.forms.models import ModelForm
from django.forms.widgets import CheckboxSelectMultiple
class Company(models.Model):
industries = models.ManyToManyField(Industry, blank=True, null=True)
class CompanyForm(ModelForm):
class Meta:
model = Company
fields = ("industries")
def __init__(self, *args, **kwargs):
super(CompanyForm, self).__init__(*args, **kwargs)
self.fields["industries"].widget = CheckboxSelectMultiple()
self.fields["industries"].queryset = Industry.objects.all()
- [Django]-Django set default form values
- [Django]-Saving ModelForm error(User_Message could not be created because the data didn't validate)
- [Django]-Which Model Field to use in Django to store longitude and latitude values?
Source:stackexchange.com