我在表单中使用 MultipleChoiceField 。我想将所有选定的值添加到数据库,但我使用的下一个代码只添加用户选择的最后一个值。我试着在我的视图中创建多个数字对象。我错在哪里?
models.py:
class Requirement(models.Model):
code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False)
symbol = models.CharField(_('Symbol'), max_length=250)
name = models.CharField(_('Name'), max_length=250)
forms.py:
class AddForm(forms.ModelForm):
symbol= forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=REQUIREMENTS_CHOICES,)
class Meta:
model = Requirement
fields = ('symbol',)
REQUIREMENTS_CHOICES = (
('A', 'Name A'),
('B', 'Name B'),
('C', 'Name C'),
)
views.py:
def requirement_add(request):
data = dict()
if request.method == 'POST':
form = AddForm(request.POST)
if form.is_valid():
list = dict(REQUIREMENTS_CHOICES) # {'C': 'Name C', 'A': 'Name A', 'B': 'Name B'}
symbols = form.cleaned_data.get('symbol') # ['A', 'B', 'C']
requirement = form.save(commit=False)
for symbol in symbols:
requirement.symbol = symbol
requirement.name = list[symbol]
requirement.save()
data['form_is_valid'] = True
requirements = Requirement.objects.filter()
context = {requirement': requirement, 'requirements': requirements}
data['html_requirement'] = render_to_string('project/requirement_list.html', context)
else:
data['form_is_valid'] = False
else:
form = AddForm()
context = {'form': form}
data['html_requirement_form'] = render_to_string('project/requirement_add.html', context, request=request)
return JsonResponse(data)
答案 0 :(得分:1)
您应该添加requirement.pk = None
,以便每次调用save
都会在数据库中插入新行:
for symbol in symbols:
requirement.symbol = symbol
requirement.name = group_requirement_list[symbol]
requirement.pk = None
requirement.save()
请参阅此处的文档https://docs.djangoproject.com/en/dev/ref/models/instances/#how-django-knows-to-update-vs-insert。
编辑:
解释:在此循环的第一次迭代中,requirement.save()
将在数据库中插入一个新行,如您所料。但在此之后requirement
将拥有新行的主键,Django将尝试更新它而不是创建新行。
替代解决方案:如果您将requirement = form.save(commit=False)
放在for循环中,则可以避免所有这些:
symbols = form.cleaned_data.get('symbol') # ['A', 'B', 'C']
for symbol in symbols:
requirement = form.save(commit=False)
requirement.symbol = symbol
requirement.name = group_requirement_list[symbol]
requirement.save()