在Django模型中,需要在两个字段上进行验证,其中一个下拉字段选项使另一字段成为必填项

时间:2019-05-02 06:38:52

标签: django python-3.x django-models

我有两个领域。一个是下拉菜单,称为付款方式,另一个是称为支票的字段,如果下拉菜单中的付款方法被选择为支票,则检查字段应为必填字段,如果付款方式为Checks and Checks字段,则需要在模型级别进行验证为空然后引发错误。

我还没有尝试过任何方法

PAYMENT_METHOD = (
    ('cash', 'Cash'), ('credit card', 'Credit Card'),('debit card', 'Debit Card'),
     ('cheques', 'Cheques')
)

payment_method = models.CharField(max_length=255,
                                  choices = PAYMENT_METHOD,
                                   verbose_name= "Payment Method")

cheques = models.IntegerField(blank=True, null=True)

我想要这样一种方式:在前端表单中,当我们选择付款方式支票时,checks字段应为必填字段,而当选择的付款方式为checks且checks字段为空白时,则会引发错误。 / p>

1 个答案:

答案 0 :(得分:0)

您可以做的是使用一些会在更改时查看Payment_method的JavaScript,如果更改,则将所需的html属性添加到checks字段:

在模板中使用以下内容:

$(document).ready(function(){
 $('#id_payment_method').change(function(){
   //add the attibute required to the cheques field if the cheque payments method is selected
   if (this === 'cheques') {
     $("#id_cheques").prop('required',true);
   }
   //otherwise we have to remoove the required
   else {
     $("#id_cheques").removeAttr('required')
   }
 });
});

然后,您需要尝试检查Payment_method,并根据该值检查Checks字段值是否为空。

执行此操作的最佳位置是在clean方法内部。

在django Forms.py中(我想您在这里使用ModelForm:

from django.forms import ValidationError
from django.utils.translation import gettext as _

class PaymentForm(forms.ModelForm):
    class Meta:
        model = Payment #replace by the name of your model here
        fields = ['payment_method' , 'cheques' ]

    def clean(self):
        cleaned_data = super(PaymentForm, self).clean()
        #Try to get the cleaned data of cheques and payment method
        try :
            cheques = self.cleaned_data['cheques']
        except KeyError:
            cheques = None

        try : 
            payment_method = self.cleaned_data['payment_method']

        except KeyError:
            payment_method = None

        if payment_method == 'cheques':
            #check the cheques value is not empty
            if not cheques:
                raise ValidationError(_("The cheque can't be empty with this payment method"),code='empty_cheque')

        return cleaned_data

您认为业务逻辑保持不变。