Re: date format other than YYYY-MM-DD

2007-01-12 Thread Adrian Holovaty

On 1/12/07, Andres Luga <[EMAIL PROTECTED]> wrote:
> Any idea if newforms simplifies this?

Yes, newforms DateFields let you specify the input format(s). This has
yet to be integrated into the Django admin, but it will be sooner
rather than later.

Adrian

-- 
Adrian Holovaty
holovaty.com | djangoproject.com

--~--~-~--~~~---~--~~
 You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: date format other than YYYY-MM-DD

2007-01-12 Thread Andres Luga

Hi,

Any idea if newforms simplifies this?

Regards,
Andres

On 9/29/06, DavidA <[EMAIL PROTECTED]> wrote:

> I also ran into this problem so I did it that hard way: I created a
> custom model DateField and a custom form DateField. (I call them
> RelaxedModelDateField and RelaxedFormDateField meaning they are relaxed
> about what format you put the date in). Every time I look at this code
> I think "this is way too complicated to simply allow different date
> formats on input/output" which is probably one of the reasons the
> forms/manipulators/validators are all getting revisited right now.
>
> To use this, just use RelaxedModelDateField in place of
> models.DateField in your model. This works in the admin.
>
> class RelaxedModelDateField(models.DateField):
>"""A DateField that supports various date formats
>rather than just -mm-dd. The following formats
>are allowed:
>  m/-d/-6-23-2006
>  m/-d/-yy  6/23/06
>  m/-d  6/23
>  -mm-dd2006-6-23
>  mmdd  20060623
>
>In the UI, the date will be displayed as mm/dd/"""
>def __init__(self, verbose_name=None, name=None,
> auto_now=False, auto_now_add=False, **kwargs):
>models.DateField.__init__(self, verbose_name, name,
>  auto_now, auto_now_add, **kwargs)
>
>def get_internal_type(self):
>return "DateField"
>
>def to_python(self, value):
>if isinstance(value, datetime.datetime):
>return value.date()
>if isinstance(value, datetime.date):
>return value
>try:
>return toDateRelaxed(value)
>except ValueError:
>raise validators.ValidationError, gettext('Enter a valid
> date.')
>
>def get_manipulator_field_objs(self):
>return [RelaxedFormDateField]
>
>def flatten_data(self, follow, obj = None):
>val = self._get_val_from_obj(obj)
>return {self.attname:
>(val is not None and val.strftime("%m/%d/%Y") or '')}
>
> class RelaxedFormDateField(forms.DateField):
>"""A version of forms.DateField that automatically
>supports various formats of dates."""
>def __init__(self, field_name, is_required=False,
> validator_list=None):
>forms.DateField.__init__(self, field_name, is_required,
> validator_list)
>
>def isValidDate(self, field_data, all_data):
>try:
>toDateRelaxed(field_data)
>except ValueError:
>raise validators.CriticalValidationError, 'Enter a valid
> date.'
>
>def html2python(data):
>"Converts the field into a datetime.date object"
>try:
>return toDateRelaxed(data)
>except ValueError:
>return None
>html2python = staticmethod(html2python)
>
>
> And here is the routine that actually does the "relaxed" parsing:
>
> # handle many formats:
> # m/-d/-6-23-2006
> # m/-d/-yy  6/23/06
> # m/-d  6/23
> # -mm-dd2006-6-23
> # mmdd  20060623
> def toDateRelaxed(s):
>exps = (r'^(?P\d{1,2})[/-](?P\d{1,2})[/-](?P\d{4})$',
>r'^(?P\d{1,2})[/-](?P\d{1,2})[/-](?P\d{2})$',
>r'^(?P\d{1,2})[/-](?P\d{1,2})$',
>r'^(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})$',
>r'^(?P\d{4})(?P\d{2})(?P\d{2})$')
>for exp in exps:
>m = re.match(exp, s)
>if m:
>mm = int(m.group('m'))
>dd = int(m.group('d'))
>try:
>yy = int(m.group('y'))
>if yy < 100:
>yy += 2000
>except IndexError:
>yy = datetime.date.today().year
>return datetime.date(yy, mm, dd)
>raise ValueError, s
>
> Hope this helps...
> -Dave
>

--~--~-~--~~~---~--~~
 You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: date format other than YYYY-MM-DD

2006-10-10 Thread Javier Rivera

[EMAIL PROTECTED] escribió:
> Javier,
> 
>Is it possible to use this with the generic view?

No (AFAIK). You need to call it explicitly when processing the form.

Javier.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: date format other than YYYY-MM-DD

2006-10-09 Thread [EMAIL PROTECTED]

Javier,

   Is it possible to use this with the generic view?


Javier Rivera wrote:
> viestards escribió:
> >> Using the 'date' filter, you can format the output however you want,
> >> within templates.
> >>
> >> For example, to format a date as "September 17, 2006", you would do
> >> the following in a template:
> >>
> >> {{ object.pub_date|date:"F d, Y" }}
> >
> > thanks for reply, but will it work on forms?
>
> I use a small dirty trick. It's dirty, but I feel it's easier and
> quicker than building custom validators/manipulators.
>
> I have a small function:
>
> --
>
> def cadena_a_fecha(strfecha):
>  # Eliminamos todos los posibles separadores
>  strfecha=strfecha.replace("-","")
>  strfecha=strfecha.replace("/","")
>  strfecha=strfecha.replace(" ","")
>  strfecha=strfecha.replace(".","")
>  # Probamos varios metodos
>  try:
>  fecha=time.strptime(strfecha,"%d%m%y")
>  except ValueError :
>  fecha=time.strptime(strfecha,"%d%m%Y")
>
>  return datetime.date(fecha[0],fecha[1],fecha[2])
>
> --
>
> It takes a string, removes the usual data separators and try to convert
> it to a datetime using the python strptime.
>
> In the form view code I did something like that
>
> 
> def formulario(request,visita_id):
> 
>  if request.POST :
>  datos = request.POST.copy()
>  errores = manipulador.get_validation_errors(datos)
>  if errores.has_key('Fecha') :
>  # Error de fecha, vamos a intentar convertirla
>  try:
>  fecha = cadena_a_fecha(datos['Fecha'])
>  except :
>  pass
>  else :
>  datos['Fecha']=fecha.strftime("%Y-%m-%d")
>  errores=manipulador.get_validation_errors(datos)
> 
> ---
>
> I use the usual form stuff. But if I detect an error on the date field
> (Fecha in Spanish) I just throw the string to the previous function. If
> it doesn't raise an exception I use the return to build a sting that
> django will accept and call get_validation_errors again.
>
> It's not pretty, not very portable, prone to break when the main
> manipulator code/system change, but... well it's easy.
> 
> Javier.


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: date format other than YYYY-MM-DD

2006-09-29 Thread DavidA

viestards wrote:
> thanks, suppose I have to do it this way. I just hoped to have a
> sollution that works in admin pages too.

I also ran into this problem so I did it that hard way: I created a
custom model DateField and a custom form DateField. (I call them
RelaxedModelDateField and RelaxedFormDateField meaning they are relaxed
about what format you put the date in). Every time I look at this code
I think "this is way too complicated to simply allow different date
formats on input/output" which is probably one of the reasons the
forms/manipulators/validators are all getting revisited right now.

To use this, just use RelaxedModelDateField in place of
models.DateField in your model. This works in the admin.

class RelaxedModelDateField(models.DateField):
"""A DateField that supports various date formats
rather than just -mm-dd. The following formats
are allowed:
  m/-d/-6-23-2006
  m/-d/-yy  6/23/06
  m/-d  6/23
  -mm-dd2006-6-23
  mmdd  20060623

In the UI, the date will be displayed as mm/dd/"""
def __init__(self, verbose_name=None, name=None,
 auto_now=False, auto_now_add=False, **kwargs):
models.DateField.__init__(self, verbose_name, name,
  auto_now, auto_now_add, **kwargs)

def get_internal_type(self):
return "DateField"

def to_python(self, value):
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
try:
return toDateRelaxed(value)
except ValueError:
raise validators.ValidationError, gettext('Enter a valid
date.')

def get_manipulator_field_objs(self):
return [RelaxedFormDateField]

def flatten_data(self, follow, obj = None):
val = self._get_val_from_obj(obj)
return {self.attname:
(val is not None and val.strftime("%m/%d/%Y") or '')}

class RelaxedFormDateField(forms.DateField):
"""A version of forms.DateField that automatically
supports various formats of dates."""
def __init__(self, field_name, is_required=False,
validator_list=None):
forms.DateField.__init__(self, field_name, is_required,
validator_list)

def isValidDate(self, field_data, all_data):
try:
toDateRelaxed(field_data)
except ValueError:
raise validators.CriticalValidationError, 'Enter a valid
date.'

def html2python(data):
"Converts the field into a datetime.date object"
try:
return toDateRelaxed(data)
except ValueError:
return None
html2python = staticmethod(html2python)


And here is the routine that actually does the "relaxed" parsing:

# handle many formats:
# m/-d/-6-23-2006
# m/-d/-yy  6/23/06
# m/-d  6/23
# -mm-dd2006-6-23
# mmdd  20060623
def toDateRelaxed(s):
exps = (r'^(?P\d{1,2})[/-](?P\d{1,2})[/-](?P\d{4})$',
r'^(?P\d{1,2})[/-](?P\d{1,2})[/-](?P\d{2})$',
r'^(?P\d{1,2})[/-](?P\d{1,2})$',
r'^(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})$',
r'^(?P\d{4})(?P\d{2})(?P\d{2})$')
for exp in exps:
m = re.match(exp, s)
if m:
mm = int(m.group('m'))
dd = int(m.group('d'))
try:
yy = int(m.group('y'))
if yy < 100:
yy += 2000
except IndexError:
yy = datetime.date.today().year
return datetime.date(yy, mm, dd)
raise ValueError, s

Hope this helps...
-Dave


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: date format other than YYYY-MM-DD

2006-09-29 Thread viestards

> I have a small function:

> I use the usual form stuff. But if I detect an error on the date field
> (Fecha in Spanish) I just throw the string to the previous function. If
> it doesn't raise an exception I use the return to build a sting that
> django will accept and call get_validation_errors again.
>
> It's not pretty, not very portable, prone to break when the main
> manipulator code/system change, but... well it's easy.
>
> Javier.

thanks, suppose I have to do it this way. I just hoped to have a
sollution that works in admin pages too.

Viestards

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: date format other than YYYY-MM-DD

2006-09-29 Thread Javier Rivera

viestards escribió:
>> Using the 'date' filter, you can format the output however you want,
>> within templates.
>>
>> For example, to format a date as "September 17, 2006", you would do
>> the following in a template:
>>
>> {{ object.pub_date|date:"F d, Y" }}
> 
> thanks for reply, but will it work on forms?

I use a small dirty trick. It's dirty, but I feel it's easier and 
quicker than building custom validators/manipulators.

I have a small function:

--

def cadena_a_fecha(strfecha):
 # Eliminamos todos los posibles separadores
 strfecha=strfecha.replace("-","")
 strfecha=strfecha.replace("/","")
 strfecha=strfecha.replace(" ","")
 strfecha=strfecha.replace(".","")
 # Probamos varios metodos
 try:
 fecha=time.strptime(strfecha,"%d%m%y")
 except ValueError :
 fecha=time.strptime(strfecha,"%d%m%Y")

 return datetime.date(fecha[0],fecha[1],fecha[2])

--

It takes a string, removes the usual data separators and try to convert 
it to a datetime using the python strptime.

In the form view code I did something like that


def formulario(request,visita_id):

 if request.POST :
 datos = request.POST.copy()
 errores = manipulador.get_validation_errors(datos)
 if errores.has_key('Fecha') :
 # Error de fecha, vamos a intentar convertirla
 try:
 fecha = cadena_a_fecha(datos['Fecha'])
 except :
 pass
 else :
 datos['Fecha']=fecha.strftime("%Y-%m-%d")
 errores=manipulador.get_validation_errors(datos)

---

I use the usual form stuff. But if I detect an error on the date field 
(Fecha in Spanish) I just throw the string to the previous function. If 
it doesn't raise an exception I use the return to build a sting that 
django will accept and call get_validation_errors again.

It's not pretty, not very portable, prone to break when the main 
manipulator code/system change, but... well it's easy.

Javier.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: date format other than YYYY-MM-DD

2006-09-28 Thread [EMAIL PROTECTED]

It is hard to use it with related objects... Inside a for loop I can´t
know which original object to reference (at least with the template
language) and if I use the for to loop through the original object
instead of the form, I have to use it for all other fields of the form,
with no help for ForeignKeys and ManyToMany fields.


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: date format other than YYYY-MM-DD

2006-09-27 Thread Don Arbow
This was answered here last month:http://groups.google.com/group/django-users/browse_frm/thread/f0e7d503401a7186/1d378aa769159983?#1d378aa769159983As Jay mentioned, you need to use the object value, not the formfield. The date filter requires a datetime instance, which the formfield is not  and so has no day attribute (or year or month attributes for that matter). DonOn Sep 27, 2006, at 4:08 PM, viestards wrote: Using the 'date' filter, you can format the output however you want,within templates.For example, to format a date as "September 17, 2006", you would dothe following in a template:{{ object.pub_date|date:"F d, Y" }} thanks for reply, but will it work on forms? Right now I get:'FormFieldWrapper' object has no attribute 'day'and mark on line{{form.registrationDate|date:"d.m.Y"}}Viestards Jay P. 
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups "Django users" group.  To post to this group, send email to django-users@googlegroups.com  To unsubscribe from this group, send email to [EMAIL PROTECTED]  For more options, visit this group at http://groups.google.com/group/django-users  -~--~~~~--~~--~--~---



Re: date format other than YYYY-MM-DD

2006-09-27 Thread viestards

> Using the 'date' filter, you can format the output however you want,
> within templates.
>
> For example, to format a date as "September 17, 2006", you would do
> the following in a template:
>
> {{ object.pub_date|date:"F d, Y" }}

thanks for reply, but will it work on forms?
 Right now I get:
'FormFieldWrapper' object has no attribute 'day'
and mark on line
{{form.registrationDate|date:"d.m.Y"}}

Viestards

> Jay P.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: date format other than YYYY-MM-DD

2006-09-27 Thread Jay Parlar

On 9/27/06, viestards <[EMAIL PROTECTED]> wrote:
>
> Hi everyone!
>
> As far as I know date format is hardcoded into Django as -MM-DD.
> Is there any way to change it globally?
> If not what is best way to change date format in forms to other? For
> now, I change date format in view from dd.mm. but I doubt it's the
> best way to do such things.

Using the 'date' filter, you can format the output however you want,
within templates.

For example, to format a date as "September 17, 2006", you would do
the following in a template:

{{ object.pub_date|date:"F d, Y" }}

Jay P.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



date format other than YYYY-MM-DD

2006-09-27 Thread viestards

Hi everyone!

As far as I know date format is hardcoded into Django as -MM-DD.
Is there any way to change it globally?
If not what is best way to change date format in forms to other? For
now, I change date format in view from dd.mm. but I doubt it's the
best way to do such things.

Viestards

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---