简体   繁体   中英

Django model DateField format in modelformset_factory

I'm trying to make a modelform_factory for my model named Book but the DateField is behaving strangely.

class Book(models.Model):
   name = models.CharField(max_length = 50)
   date = models.DateField(max_length = 50)

I have a function in my views that returns this:

modelform = modelformset_factory(Book, fields = (
    'name',
    'date',
),
can_delete=True,
widgets = {
    'date': forms.DateInput(format='%d/%m/%Y'),
})

In my template this modelform will render with a datepicker:

$('.datepicker').datepicker({ format: 'dd/mm/yyyy' });

So far so good, and everything is working as expected to this point. But when I post my form to my view again, and save the modelformset, the dd/mm/yyyy date is wrongly converted to yyyy-mm-dd .

if request.method == 'POST':
    formset = modelform(request.POST, request.FILES, queryset=Book.objects.filter(name=book))

    if formset.is_valid():
        formset.save() # This first deletes all instances that are checked for deletion
        f = formset.save(commit=False) # This filters the formset to only include filled in forms
        for form in f:
            form.save()
        return HttpResponse("success")

Does someone has any clue how I can format this dd/mm/yyyy date to correctly enter my database?

You probably need to reformat the date to match what the field requires (yyyy-mm-dd). You'll need to change the value via jQuery after using the datapicker tool which is using the dd/mm/yyyy format.

Somthing like:

  $("#dateField").on('change', function(){
      var arr = $("#dateField").val().split("/");
      var newDate = arr[2]+"-"+arr[1]+"-"+arr[0];
      $("#dateField").val(newDate);
  });

Then, you'll need to parse that string to a date type in your view before saving it with parse_date:

from datetime import datetime

date = request.POST['dateField']
pDate= parse_date(date)
form.date = pDate
form.save()

In the source: https://docs.djangoproject.com/en/2.1/_modules/django/db/models/fields/#DateField https://docs.djangoproject.com/en/2.1/ref/utils/#module-django.utils.dateparse

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