how*_*his 5 django django-models django-forms django-views
我想知道如何以以下形式color(多对多字段)由CheckboxSelectMultiple小部件中的值填充。
#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()
Run Code Online (Sandbox Code Playgroud)
#forms.py
class AddCar(forms.ModelForm):
color = forms.MultipleChoiceField(
choices=Color.COLOR_CHOICES,
widget=forms.CheckboxSelectMultiple(),
required=False
)
Run Code Online (Sandbox Code Playgroud)
#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('/')
Run Code Online (Sandbox Code Playgroud)
#错误
'Car' instance needs to have a primary key value before a many-to-many relationship can be used.
Run Code Online (Sandbox Code Playgroud)
您是否没有显示复选框,或者这是您试图消除的错误?如果是后者,请尝试commit=False在保存表单时删除 。
更新:Color模型未指定任何字段。给它一个,例如color = IntegerField(choices=COLOR_CHOICES)。
在AddCar形式上,如果错误则给出choices=Color.COLOR_CHOICES- 您必须给它一个实际存在的对象元组(Color.COLOR_CHOICES 只是代码常量)。另外,您可能应该使用 ModelMultipleChoiceField,它带有一个queryset参数,例如:
colors = forms.ModelMultipleChoiceField(queryset=Color.objects, widget=forms.CheckboxSelectMultiple(), required=False)
https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelmultiplechoicefield
| 归档时间: |
|
| 查看次数: |
11440 次 |
| 最近记录: |