1
我在我的表單中使用MultipleChoiceField。我想將所有選定的值添加到數據庫,但下一個我使用的代碼只添加用戶選擇的最後一個值。我在我的視圖中嘗試創建多個數字對象。我哪裏錯了?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)
謝謝! 'requirement.pk = None'適用於我,但我不明白它爲什麼可行xD你能解釋一下嗎?正如你可以看到代碼字段是我的PK,我也使用默認= uuid.uuid4。所以我認爲它會自動創建pk。也感謝您的鏈接。 –
不客氣!我添加了一個解釋和一個替代解決方案。 –