如何在Django中使用unique_together字段验证ModelForm?

时间:2014-04-16 15:32:06

标签: django

如何验证unique_together错误以及如何通过 view.py 将自定义错误消息返回到html。请帮忙。

model.py

class Pcq(models.Model):
    product = models.ForeignKey(Product, null=False)
    component = models.ForeignKey(Component, null=False)
    quantity = models.IntegerField('Quantity', null=False)

    class Meta:
        unique_together = ("product", "component")

    def __unicode__(self):
        return self.product.productname

Form.py

class PcqForm(ModelForm):
    class Meta:
        model = Pcq
        fields = ['component', 'quantity']
        exclude = ['product']

Views.py

def pcq_add(request, product_id):
    if request.method == 'POST':
        form = PcqForm(request.POST or None)
        if form.is_valid():
            pcq = form.save(commit=False)
            pcq.product_id = product_id
            pcq.save()
            form = PcqForm()
            successmsg = "Component added successfully! Add another Component..."
            return render(request, 'maps/pcq/pcq_add.html', {'form': form, 'product_id': product_id, 'successmsg': successmsg})
     form = PcqForm()
     return render(request, 'maps/pcq/pcq_add.html', {'form': form, 'product_id': product_id})

1 个答案:

答案 0 :(得分:1)

您需要表单的自定义清理功能

class PcqForm(ModelForm):
    class Meta:
        model = Pcq
        fields = ['component', 'quantity']
        exclude = ['product']

    def clean(self):
        cleaned_data = super(PcqForm, self).clean()
        component = cleaned_data.get('component')
        quantity = cleaned_data.get('quantity')

        if component and quantity:
            try:
                Pcq.objects.get(
                    component=component,
                    quantity=quantity,
                )
            except Pcq.DoesNotExist:
                # Yay
                pass
            else
                raise forms.ValidationError(_("Error message goes here"))

<强>更新

与上述概念相同但在视图中。

def pcq_add(request, product_id):
    if request.method == 'POST':
        form = PcqForm(request.POST or None)
        data = {
            'form': form,
            'product_id': product_id
        }
        if form.is_valid():
            pcq = form.save(commit=False)
            pcq.product_id = product_id

            try:
                pcq.save()
            except IntegrityError:
                # You'll need to check the exception that is raised
                # Handle failed unique_together
                pass
            else:
                form = PcqForm()
                data['successmsg'] =  (
                    "Component added successfully! Add another Component.")
    else:
        form = PcqForm()
        data = {'form': form, 'product_id': product_id}
    return render(request, 'maps/pcq/pcq_add.html', data)

可替换地:

  • 删除exclude = ['product']
  • GET上将product_id传递给表单form = PcqForm(initial_data={'product': product_id})
  • 使用表单验证unique_together(确定您甚至不需要自定义clean