简体   繁体   English

验证日期字段

[英]Validation for date field

I have override date format in django modelform widget and jQuery datepicker, it given error that field is not valid 我在Django modelform小部件和jQuery datepicker中具有覆盖日期格式,它给出了错误,指出该字段无效

class Sale_Invoice_Main_Page(forms.ModelForm):
    class Meta:
        model = SaleInvoice
        fields = '__all__'
        exclude = ['created_at','updated_at','transiction_type']
        widgets = {'description' : forms.TextInput(attrs={ 'placeholder' : 'description'}),
                   'invoice_no' : forms.TextInput(attrs={ 'readonly' : 'True'}),
                   'total_amount' : forms.TextInput(attrs={ 'readonly' : 'True'}),
                   'invoice_date' : forms.DateInput(attrs={ 'class' : "vdate" },format=('%d-%m-%Y')),
                   'due_date' : forms.DateInput(attrs={ 'readonly' : "True" },format=('%d-%m-%Y')),
                    }


class SaleInvoice(models.Model):
    customer = models.ForeignKey(Customer_data , on_delete=models.CASCADE)
    invoice_date = models.DateField(null=True,blank=True)
    invoice_no = models.PositiveIntegerField(unique=True)
    due_date = models.DateField(blank=True,null=True)
    address = models.TextField()
    total_amount = models.PositiveIntegerField(null=True,blank=True)
    description = models.TextField(null=True,blank=True)
    transiction_type = models.CharField(max_length=50,blank=True)
    author = models.CharField(max_length=30)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.address

jQuery date picker: jQuery日期选择器:

{#     Date Picker#}
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $( function() {
            $( ".vdate" ).datepicker({
                dateFormat: "dd-mm-yy"
            });
        } );
    </script>

I want to find what I am doing wrong that it is given validation error 我想找到错误的提示验证错误

This can be a little tricky with localization sometimes. 有时本地化可能会有些棘手。 Normally you'd add DATE_INPUT_FORMATS to your settings. 通常,您需要将DATE_INPUT_FORMATS添加到您的设置中。 Formats from this list will be accepted when inputting data on a date field meaning adding 在日期字段上输入数据时,将接受此列表中的格式,这意味着添加

DATE_INPUT_FORMATS = [
    '%d-%m-%Y'
]

to your settings should fix your issue. 您的设置应该可以解决您的问题。 But this can be a little tricky sometimes when USE_L10N is set to True , because in this case the locale-dictated format has higher precedence and will be applied instead. 但这有时在USE_L10N设置为True时可能会有些棘手,因为在这种情况下,由区域设置指定的格式具有更高的优先级,并且将被应用。 For this reason I suggest that you don't hardcode date format in your jQuery datepicker, but rather use defaults and get date format from DATE_INPUT_FORMATS. 因此,我建议您不要在jQuery datepicker中对日期格式进行硬编码,而应使用默认值并从DATE_INPUT_FORMATS获取日期格式。 Something like this should do the trick: 这样的事情应该可以解决问题:

from django.utils import formats
# First date format in default (English) is '%Y-%m-%d', most European languages '%d.%m.%Y' etc.
date_format = formats.get_format("DATE_INPUT_FORMATS")[0]
date_format = date_format.split()[0].replace('%Y', 'YY').replace('%d', 'dd').replace('%m', 'mm')

and use it your template: 并使用它作为模板:

<script>
    $( function() {
        $( ".vdate" ).datepicker({
            dateFormat: "{{ date_format }}"
        });
    } );
</script>

This way date format will match no matter the format precedence. 无论格式优先顺序如何,日期格式都将匹配。 It is preferred that you include date format in your own context processor . 最好在自己的上下文处理器中包括日期格式。 Now it will be included in the context of all your templates. 现在,它将包含在所有模板的上下文中。

my_context_processor.py

from django.utils import formats

def common_context(request):
    ''' Common variables used in templates '''

    date_format = formats.get_format("DATE_INPUT_FORMATS")[0]
    date_format = date_format.split()[0].replace('%Y', 'YYYY').replace('%d', 'dd').replace('%m', 'mm')

    return {'date_format ': date_format}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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