Django: input date format different when creating object from updating it

↘锁芯ラ 提交于 2020-06-27 20:01:20

问题


When I create an object and put the date into the input text field with dd/mm/yyyy format (witch is the format I want for my app) it works fine. But when I try to modify it (it means I get the key of that object and update it in the database), the input date format changes to yyyy-mm-dd (which I think is the default) and the is_valid() method never returns True. I have done a lot of thing including override the locale formats.py file, but it still doesnt work.

Here is my settings.py:

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Caracas'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

#Path for date formats
FORMAT_MODULE_PATH  = 'config.formats'

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

My forms.py (the first class is for create, and the second for update/modify):

class CrearPizarraForm(forms.Form):
    """
    Form para crea pizarra
    """
    nombre = forms.CharField(max_length=50)
    descripcion = forms.CharField(max_length=100, widget=forms.Textarea)
    fecha_creacion = forms.DateField()
    fecha_final = forms.DateField()

    class ModificarPizarraForm(forms.Form):
    """
    Form para modificar pizarra
    """
    nombre = forms.CharField(max_length=50)
    descripcion = forms.CharField(max_length=100, widget=forms.Textarea)
    fecha_final = forms.DateField()

My create method in views.py:

@login_required
def crear_pizarra(request):
    """
    Metodo que crea una nueva pizarra llamando a CreadorPizarra
    """
    if request.method == 'POST':
        #solucion temporal al problema del formato de fecha
        form = CrearPizarraForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            #Variables que se pasaran al metodo CreadorPizarra
            nombrepiz = data['nombre']
            descripcionpiz = data['descripcion']
            fechaCreacion = data['fecha_creacion']
            fechaFinal = data['fecha_final']
            #Se obtiene el usuario actual para ponerlo de creador (verificar)
            usuario = request.user
            #Metodo que guarda la pizarra en la base de datos.
            CreadorPizarra(nombrepiz,descripcionpiz,fechaCreacion,fechaFinal,usuario)
            lista = obtener_pizarras(request)
            return render(request, 'app_pizarras/listar.html', { 'lista' : lista, })
        else:
            return render(request, 'app_pizarras/crear_pizarra.html',{'form': form, })

    form = CrearPizarraForm()
    return render(request, 'app_pizarras/crear_pizarra.html', { 'form': form, })

My modify method in views.py:

@login_required
def modificar_pizarra(request):
    """
    Metodo que sirve para modificar una pizarra de la base de datos
    """
   if request.method == 'POST':
      if request.POST.__contains__('nombre'):
          form = ModificarPizarraForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data
                #Variables que se pasaran al metodo CreadorPizarra
                nombrepiz = data['nombre']
                descripcionpiz = data['descripcion']
                fechaFinal = data['fecha_final']
                #Metodo que guarda la pizarra en la base de datos.
                modificar(nombrepiz,descripcionpiz,fechaFinal,)
                lista = obtener_pizarras(request)
                return render(request, 'app_pizarras/listar.html', { 'lista' : lista, })
            else:
                print "form no valido"
                idpiz = request.POST['idpiz']
                lista = []
                lista.append(request.POST['nombre'])
                lista.append(request.POST['descripcion'])
                lista.append(request.POST['fechafinal'])
                return render(request, 'app_pizarras/modificar_pizarra.html', { 'form': form, 'idpiz' : idpiz, 'lista' : lista })

I also created a config directory where is the formats directory that contains into the 'en' directory the overridden file formats.py for the date formats:

# -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#

# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'd/m/Y'
TIME_FORMAT = 'P'
DATETIME_FORMAT = 'N j, Y, P'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'F j'
SHORT_DATE_FORMAT = 'd/m/Y' 
SHORT_DATETIME_FORMAT = 'm/d/Y P'
FIRST_DAY_OF_WEEK = 0 # Sunday

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = (
            '%d/%m/%Y',  # '25/10/2006'
                # '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
                    # '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
                        # '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
                            # '%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'
                            )
TIME_INPUT_FORMATS = (
            '%H:%M:%S',     # '14:30:59'
                '%H:%M',        # '14:30'
                )
DATETIME_INPUT_FORMATS = (
            '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
                '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
                    '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
                        '%Y-%m-%d',              # '2006-10-25'
                            '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
                                '%m/%d/%Y',              # '10/25/2006'
                                    '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
                                        '%m/%d/%y %H:%M',        # '10/25/06 14:30'
                                            '%m/%d/%y',              # '10/25/06'
                                            )
DECIMAL_SEPARATOR = u','
THOUSAND_SEPARATOR = u'.'
NUMBER_GROUPING = 3

I think Django recognize this last part because the dates are shown in the expected format, the problem is the input when I update.


回答1:


Try setting input_formats for the DateField in the ModificarPizarraForm class:

    fecha_final = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS)

From the DateField section of the Form fields documentation:

If no input_formats argument is provided, the default input formats are:

  • '%Y-%m-%d', # '2006-10-25'
  • '%m/%d/%Y', # '10/25/2006'
  • '%m/%d/%y', # '10/25/06'



回答2:


I think your code is correct, check your templates for mistakes there.



来源:https://stackoverflow.com/questions/13458945/django-input-date-format-different-when-creating-object-from-updating-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!