在Django模型中,需要在两个字段上进行验证,其中一个下拉字段选项可以使另一个字段强制性



我有两个字段。一个是一个名为付款方式的下拉列表,另一个是一个名为"检查"的字段,如果选择下拉付款方式作为检查,则该检查字段应该是强制性的,我需要在模型级别验证这一点,如果付款方式是检查和检查字段。是空的,然后增加错误。

我尚未尝试任何方法

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)

我希望以一种方式,以便在前端表格中选择付款方式检查时,检查字段应是强制性的,并且当选择的付款方式为检查和检查字段时,请引起错误。<<<<<<<<<<

您能做的就是使用一些javaScript,它将查看" pealdion_method"上的pealdion_method,如果它更改为"更改",则将所需的HTML属性添加到检查字段中:

在模板中使用类似的内容:

$(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')
   }
 });
});

然后,您需要保持abble检查peays_method并根据值的不同,请检查检查字段值是否为空。

最好的地方是干净的方法内。

在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

您视图中的业务逻辑保持不变。

最新更新