我想知道如何以color
(多對多字段)的形式填充來自CheckboxSelectMultiple
小部件的值。如何使用Django表單中的多個複選框保存多對多字段
#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.
複選框正在顯示,我得到的視圖中選定的值,但我不能保存它們。刪除commit = False後,我得到這個錯誤:插入或更新表「cars_car_color」違反外鍵約束 – howtodothis 2012-07-25 04:18:48
好吧,更新可能的解決方案。 – Raekkeri 2012-07-25 04:39:10