Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save Many To Many field with Multiple Checkboxes in Django Form

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.
like image 738
howtodothis Avatar asked Jul 25 '12 04:07

howtodothis


1 Answers

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).

like image 109
Rohan Avatar answered Nov 05 '22 03:11

Rohan