2014-04-16 143 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中選擇。選擇後,添加組件的頁面將顯示組件和數量字段。希望我回答你的問題。 –

相關問題