简体   繁体   中英

Validation for date field

I have override date format in django modelform widget and jQuery datepicker, it given error that field is not valid

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:

{#     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. 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. 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. 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}

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