Django:从更新对象创建对象时输入日期格式不同 [英] Django: input date format different when creating object from updating it
问题描述
当我创建一个对象并将日期以dd / mm / yyyy格式(女巫是我想要的应用格式)输入输入文本字段时,它可以正常工作。但是,当我尝试修改它(这意味着我获取了该对象的密钥并在数据库中对其进行更新)时,输入日期格式更改为yyyy-mm-dd(我认为这是默认设置),并且 is_valid()
方法从不返回True。我做了很多事情,包括覆盖语言环境formats.py文件,但是它仍然无法正常工作。
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.
这是我的settings.py:
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
我的form.py(第一个类用于创建,第二个用于更新/修改):
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()
我在views.py中的创建方法:
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, })
我在views.py中的修改方法:
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 })
我还创建了一个配置目录,其中的formats目录在 en目录中包含重写的文件format.py,用于日期格式:
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
我认为Django可以识别这最后一部分,因为日期以预期的格式显示,问题出在我更新时。
I think Django recognize this last part because the dates are shown in the expected format, the problem is the input when I update.
推荐答案
尝试在ModificarPizarraForm类中为DateField设置输入格式:
Try setting input_formats for the DateField in the ModificarPizarraForm class:
fecha_final = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS)
来自表单字段文档的 DateField部分:
如果未提供input_formats参数,则默认输入格式为:
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'
这篇关于Django:从更新对象创建对象时输入日期格式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!