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

时间:2021-01-28 11:51:31

How to validate the unique_together error and how to return the custom error message to the html through the view.py. Please help.

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

model.py:

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

Form.py

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

Views.py

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 个解决方案

#1


1  

You need a custom clean function for the form

您需要为窗体创建一个自定义的clean函数。

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"))

UPDATE

更新

Same concept as above but in the view.

与上面的概念相同,但在视图中。

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)

Alternatively:

另外:

  • remove the exclude = ['product']
  • 删除排除= ['product']
  • on GET pass product_id to the form form = PcqForm(initial_data={'product': product_id})
  • 在GET上将product_id传递给form = PcqForm(initial_data={'product': product_id})
  • Use the form to validate unique_together (Not sure you even need a custom clean then)
  • 使用该表单一起验证unique_together(不确定是否需要自定义清理)

#1


1  

You need a custom clean function for the form

您需要为窗体创建一个自定义的clean函数。

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"))

UPDATE

更新

Same concept as above but in the view.

与上面的概念相同,但在视图中。

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)

Alternatively:

另外:

  • remove the exclude = ['product']
  • 删除排除= ['product']
  • on GET pass product_id to the form form = PcqForm(initial_data={'product': product_id})
  • 在GET上将product_id传递给form = PcqForm(initial_data={'product': product_id})
  • Use the form to validate unique_together (Not sure you even need a custom clean then)
  • 使用该表单一起验证unique_together(不确定是否需要自定义清理)