I would like to know how in the following form color
(many-to-many field) can be populated by values from CheckboxSelectMultiple
widget.
#models.py
class Color(models.Model):
RED = 1
BLACK = 2
COLOR_CHOICES = (
(RED, _('Red')),
(BLACK, _('Black')),
)
name = models.CharField(_('Color'), max_length=512,
choices=COLOR_CHOICES, blank=True)
class Car(models.Model):
color = models.ManyToManyField(Color, blank=True, null=True)
def save(self):
self.slug = slugify(self.name)
super(Car, self).save()
#forms.py
class AddCar(forms.ModelForm):
color = forms.MultipleChoiceField(
choices=Color.COLOR_CHOICES,
widget=forms.CheckboxSelectMultiple(),
required=False
)
#view.py
def add(request):
if request.method == 'POST':
form = AddCar(request.POST)
...
if form.is_valid():
car = form.save(commit=False)
for c in request.POST.getlist('color'):
car.color.add(c)
car.save()
form.save_m2m()
return redirect('/')
#error
'Car' instance needs to have a primary key value before a many-to-many relationship can be used.
You are doing form.save(commit=False)
in which does not actually creates record in DB and due to which it cannot store M2M fields. Do form.save_m2m()
after you save form.
Or from your code, you can move car.color.add()
after you have saved the car
. And also you don't need to have form.save(commit=False)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With