简体   繁体   中英

In Django models need validation on two fields, with one dropdown field option making another field mandatory

I have two fields. One is a dropdown called payment method and other is a field called cheques, if the payment method in dropdown is chosen as cheques then the cheques field should be mandatory, I need to validate this in model level, if payment method is cheques and cheques field is empty then raise error.

I haven't tried any method yet

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)

I want this in such a way that in the front end form when we chose payment method cheques, the cheques field should be mandatory and when the chosen payment method is cheques and cheques field is left blank it should raise an error.

What you can do is using some javascript that will look at payment_method on change, and if it change add the required html property to the cheques field:

Using something like this in the template:

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

Then you need to be abble to check the payment_method and depending of the value, check if the cheques field value is empty or not.

The best place to do it is inside the clean method.

In django forms.py (I am supposing your are using a ModelForm here:

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

The business logic in your view remain the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM