Django表单字段验证不起作用并且没有错误

时间:2021-07-18 06:11:26

标签: django django-forms django-validation

我在 Django 中有一个表单,我需要验证电话号码。执行“下一步”按钮后不会进行验证。我做了一个打印来检查是否调用了验证,我可以看到它没有被调用,并且我已经确保 validators.py 与我的表单在同一个应用程序文件夹中。

forms.py

from django import forms
from .validators import phoneNumberValidation

class customerLocalDeliveryForm(forms.Form):
    customerName = forms.CharField(label = 'Name', max_length=20, required=True)
    customerEmail = forms.EmailField(label = 'Email', max_length=50, required=True)
    
    customerMobile = forms.CharField(label = 'Mobile', max_length = 20,
    required = True, validators=[phoneNumberValidation]) 

    comments = forms.CharField(label = 'Comments', max_length = 300, widget=forms.Textarea, required = False)
    deliveryTime = forms.ChoiceField(choices = (), required=True)

    def __init__(self, *args, **kwargs):
        self.deliveryTimeList = kwargs.pop('deliveryTimeList')
        super().__init__(*args, **kwargs)
        self.fields['deliveryTime'].choices = self.deliveryTimeList

在我的 validators.py 中,它与我的表单位于同一文件夹中。我不知道为什么不调用此验证,因为当我从网页测试验证时,我没有在控制台中看到打印。

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

def phoneNumberValidation(value):
    print('here is the value')
    print(value)
    if len(value) <= 7:
        print('we are here')
        raise ValidationError(_("The phone number must be 8 digits"))
    return value

在我的 views.py 中,我在帖子部分有以下内容。这里的重点是我没有进一步检查表单的 is_valid(),因为我可以从这个 post 了解到它应该没有必要,因为验证是在客户端的浏览器中进行的。

class Payment(View):
    def __init__(self):
        #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant
        self.hd2900RestaurantObject = RestaurantUtils(restaurantName = restaurantName)
    
    def post(self, request, *args, **kwargs):
        #Check if session is still valid 
        sessionValid = webshopUtils.checkSessionIdValidity(request = request, session_id_key = session_id_key, validPeriodInDays = self.hd2900RestaurantObject.restaurantModelData.session_valid_time)
        
        #In this case the session has expired and the user will be redirected
        if sessionValid is False:
            return redirect('hd2900_takeaway_webshop')

        #Write the customer info into the data base
        webshopUtils.create_or_update_Order(session_id_key=session_id_key, request=request, deliveryType='delivery')

        #Calculate the total price followed by creation of paymentID from NETS
        totalPrice = webshopUtils.get_BasketTotalPrice(request.session[session_id_key]) + self.hd2900RestaurantObject.restaurantModelData.delivery_fee + self.hd2900RestaurantObject.restaurantModelData.bagFee

        #Create an order reference and link that to NETS reference
        reference = webshopUtils.get_order_reference(request = request, session_id_key=session_id_key)

        #Get the payment id from NETS 
        payment = NETS()
        paymentId = payment.get_paymentId(platform = platform,
        reference = reference, 
        name = 'Hidden Dimsum 2900 Takeaway',
        paymentReference ='Hidden Dimsum 2900 takeaway paymrent ref',
        unitPrice = int(totalPrice) *100)

        if paymentId.status_code == 201:
            paymentId = paymentId.json()['paymentId']

        #Put the checkout key and the payment id into the page that javascript is going to read from during payment
        checkoutKey = payment.getCheckoutKey(platform = platform)

        context = dict()
        context['paymentId'] = paymentId
        context['checkoutKey'] = checkoutKey

        return render(request, template_name="takeawayWebshop/webshopPayment.html", context = context)

0 个答案:

没有答案