2014-04-16 74 views
2

如何验证unique_together错误以及如何通过view.py将自定义错误消息返回给html。请帮忙。如何在Django中使用unique_together字段验证ModelForm?

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}) 
+0

我们可以看到你的'视图'吗?将有助于了解它是基于功能还是基于类。 – rockingskier

+0

@rockingskier,我更新了views.py –

回答

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

UPDATE

相同的概念如上述,但在视图中。

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) 

或者:

  • 删除排除= [ '产品']
  • GET通的product_id的形式form = PcqForm(initial_data={'product': product_id})
  • 使用表单验证unique_together(不知道你甚至需要自定义clean然后)
+0

请注意** unique_together =(“product”,“component”)**。但是ModelForm中排除了产品。如何处理这个? –

+0

啊,是的,误读了字段。如果产品不在表格中,你如何填充? – rockingskier

+0

产品未填充,它将由用户在不同的html中选择。选择后,添加组件的页面将显示组件和数量字段。希望我回答你的问题。 –

相关问题