Django: date format management and unique_together -> “20/03/2020” value has an invalid date format. It must be in YYYY-MM-DD format.”]

764 views
Skip to first unread message

Jérôme Le Carrou

unread,
Mar 23, 2020, 6:27:31 AM3/23/20
to Django users
Hi,

I develop a Django project with internationalization English/French

dates have to be displayed with the dd/mm/yyyy format when user webbrowser is FR and yyyy-mm-dd when user webbrowser is EN

to do that, I use JS that test webbrowser user favorite language and display format accordingly

That works fine until I change my model to add unique_together constraint with this date

 

Now, I got the error when webbrowser is in french and I try to register date (asp_ent_dat)


date format "20/03/2020" is invalid. Correct format is "yyy-mm-dd".



Reading Django documentation about validation, I 'understand' that unique_together is the model validation that seems to fail because of date format


I try adding DATE_INPUT_FORMATS = ['%Y-%m-%d', '%d-%m-%Y', ] in settings.py, the second format corresponding to the french format I need, but it does'nt works


I can I fix my problem:

Have unique_together constraint on 3 fields including asp_ent_dat and display date in french format in my form?


models.py:

class Entree(models.Model):

    asp_ent_cle = models.AutoField(primary_key=True)
    asp_ent_loc = models.CharField("Site concerned by the operation", max_length=10, null=True, blank=True)
    med_num = models.CharField("Trial batch number", max_length=3, null=True, blank=True,)
    asp_ent_dat = models.DateField("Entry date", null=True, blank=True)
    asp_ent_pro_pay = models.CharField("Country of treatment origin in case of entry", max_length=10, null=True, blank=True)
    asp_ent_pro_sit = models.CharField("Processing source site in case of entry", max_length=10, null=True, blank=True)
    opr_nom = models.CharField("Input operator", max_length=10, null=True, blank=True)
    opr_dat = models.DateField("Entry date", null=True, blank=True)
    log = HistoricalRecords()

    class Meta:

        db_table = 'pha_asp_ent'
        verbose_name_plural = 'Entries'
        ordering = ['asp_ent_cle']
        unique_together = ['asp_ent_loc','med_num','asp_ent_dat']  

JS:

$(function(){

    if(window.navigator.language == 'fr-FR' | window.navigator.language == 'fr'){
        $("#id_asp_ent_dat").datepicker(
            {
                dateFormat: 'dd/mm/yy',
            }
        );
    } 
    else
    {
        $("#id_asp_ent_dat").datepicker(
            {
                dateFormat: 'yy-mm-dd',
            }
        );
});
Reply all
Reply to author
Forward
0 new messages