多接地式Field创建多个对象



i在我的表单中使用多人杂志。我想将所有选定的值添加到数据库中,但是我仅使用的下一个代码仅添加最后一个值哪个用户选择。我在视图中尝试创建多个数字对象。我在哪里错误?

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,以便每个呼叫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-ton-to-to-po-------------vs-vs-istert。

编辑:

说明:在此循环的第一次迭代中,requirement.save()将按照您的期望在数据库中插入一个新行。但是之后,requirement将具有新行的主要键,而Django将尝试更新它而不是创建新的键。

替代解决方案:如果将requirement = form.save(commit=False)放在for 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()

相关内容

  • 没有找到相关文章

最新更新