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
-~--~~~~--~~--~--~---



Full table fetches behind the scenes

2006-11-03 Thread Andres Luga

Hi,

I have a problem - when creating an object, Django performs full table
SELECT from multiple tables and multiple times. Why?

I've set up MySQL to log all queries to the database. In Django I'm
using generic views. I have the following models/tables:
1. Firm
2. Person ( ForeignKey( Firm ))
3. PassageRoll( ForeignKey( Firm ))
4. Passage ( ForeignKey( Person ) and ForeignKey( PassageRoll ))
5. Some helper tables

I'm creating the new PassageRoll, the relevant URL is set up like this:
 (r'^firms/(?P\d+)/passroll/create/', '[...].passroll_create',
  {'model': PassageRoll, 'post_save_redirect': '../..',
'login_required':'True',}),

The GET-part of the view is empty - I'm calling generic Create.

After the form of the PassageRoll is displayed, the MySQL logfile
shows that the following queries were executed:
SELECT FIRM (*)
SELECT PERSON(*) - 4 times
[...]
SELECT `django_session`.`session_key`,.
SELECT `auth_user`.`id`,...
SELECT FIRM (*)
SELECT PERSON(*) - 4 times
[...]
SELECT `auth_message`.`id`

Any ideas what might be wrong? How to find the place in blame?

Regards,

Andres

--~--~-~--~~~---~--~~
 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: automatically fill in some fields of a form, storing authenticated user

2006-09-25 Thread Andres Luga

Hi, the following are the suggestions of a Python and Django newbie,
so take with a load of salt. Also the examples are not direct
copy-paste and therefore might not work directly.

On 9/22/06, Benedict Verheyen <[EMAIL PROTECTED]> wrote:
> then data is looked up in another database and some of these values
> are then filled in the form so that when the user creates an object,
> part of the data is prefilled by fetching from another database.
> How can i fill in some fields of a form with data?
> I think i'll need to make my own Manipulator, defining the fields and
> passing default values, right?
> Is there an example around somewhere for this?

AFAIK, unfortunately no, the CreateManipulator has no knowledge about
values :(. What I ended up doing in similar situation is a bit kludge.
My model has the field Person (in database personid), which is a
foreign key to Persons table. I'm providing a default value for this
field. I use generic views and the relevant lines from my views.py
are:
def passage_create(*args, **kwargs):
   request = args[0]
   if request.GET:
  kwargs[ 'manipulator'] = MyAddManipulator( request['person'])



As you can see, I'm passing the desired value to the custom
manipulator. The manipulator itself looks like this:
class MyAddManipulator(MyModel.AddManipulator):
   def __init__(self, person_id):
  MyModel.AddManipulator.__init__(self)
  self.person_id=person_id


i.e I'm saving the value passed during the initialization. I'm using
the value in the manipulator's overridden method named flatten_data
that gets called by generic view:
class MyAddManipulator(MyModel.AddManipulator):

   def flatten_data(self):
  new_data=MyModel.AddManipulator.flatten_data(self)
  new_data['personid']=self.person_id
  return new_data


So there it is - the only way I know to provide default values if you
can't describe these in model definition. As limodou suggests, there
is another way. Maybe there is a third way, as the default value in
model can be method call. For example I have a field that gets default
value 2 years from now:
default=datetime(datetime.now().year+2, datetime.now().month,
datetime.now().day)
But I haven't experimented with this approach.


> 2. A closely related question in regards to user authentication.
> I have a model that also stores the user that is logged.
> That user field shouldn't be visible on the form and should be automatically
> filled in before the form is saved.

I have the similar situation: I have a model that has two fields:
lastupdatedon = models.DateTimeField( auto_now=True )
lastupdatedby = models.CharField( maxlength=50)

The procedure that sets the value for these looks like this
def update_logchanges(*args, **kwargs):
   kwargs = set_follow( dict( lastupdatedon=False), kwargs)
   request = args[0]
   if request.POST:
  new_data = request.POST.copy()
  new_data[ 'lastupdatedby'] = request.user
  request._post = new_data
   return create_object(*args, **kwargs)

The procedure set_follow is just a helper
def set_follow( follow, kwargs ):
   if kwargs.has_key( 'follow' ):
  new_follow = kwargs['follow']
   else:
  new_follow = {}
   for k in dict(follow).keys():
  new_follow[ str(k) ] = False
   kwargs[ 'follow' ] = new_follow
   return kwargs


I'm really hoping that this topic has a small chapter in upcoming
Django book... ;)

Regards,
Andres

--~--~-~--~~~---~--~~
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: Uploading Files

2006-09-10 Thread Andres Luga

Hi, relarted to this topic.

When using generic views, how to achieve that the file doesn't get
overwritten? For example a form for editing a person: the image file
field has no default data and when I only change the name the image is
blanked. It seems I missed something..

Regards,
Andres

> http://www.djangoproject.com/documentation/model_api/#imagefield

--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Filter "date" and FormFieldWrapper attribute error

2006-08-26 Thread Andres Luga

Hi,

when displaying a form for a new object, I'm trying to set a default
value for a date field using a filter in a template, like so:


{{ form.somefield|date:"Y-m-d" }}

This gives me an error:
'FormFieldWrapper' object has no attribute 'year'.
What am I doing wrong (I'm using generic views)?

The other solution for providing default values, that unfortunately
doesn't work either, is to set these in the view, when the request is
GET (again, generic views):
def limited_create_object(*args, **kwargs):
  #...
  if request.POST:
#
  else:
new_data = request.GET.copy()
new_data[ 'somefield' ] = str( ...)
request._get = new_data
  return create_object( *args, **kwargs)

The problem with this approach lies in create_update.py, line 56:
new_data = manipulator.flatten_data()

i.e. the data gets overwritten.

What am I missing? Any help would be greatly appreciated.

Regards,
Andres

--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Generic views and manipulating data before saving

2006-08-26 Thread Andres Luga

Hi,

I've spent many hours trying to get the following to work (I'm not
blaming Django - I'm very new to Python and Django, it was late etc).
To hopefully make the solution easier to find in Google, I write it
here. Suggestions for improvement are welcome.

Question: using generic views, how to alter the data user has POST-ed?
For example for setting the "last updated by"-field.
models.py:  lastupdatedby = models.ForeignKey(User)
*_detail.html: {{object.lastupdatedby}}

In the views.py I have a wrapper method, that modifies the data that
has been POST-ed and then passes it along to generic views for
validating and saving.

@login_required
def limited_update_object(*args, **kwargs):
  #The fields that are handled by Django are in "follow", for example:
  #follow = {'lastupdatedon': False}   <-- auto_now=True
  #kwargs['follow'] = follow

  request = args[0]<-- is this safe?
  if request.POST:
new_data = request.POST.copy()
new_data[ 'lastupdatedby' ] = str( request.user.id )
request._post = new_data

  return update_object(*args, **kwargs)


The question I have yet to find an answer: is there a more convenient
way for debugging and examining the data than raise Http404,
str(new_data)?

Regards,
Andres

--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Authentication, error "DoesNotExist at /accounts/login/", part 2

2006-08-14 Thread Andres . Luga

Hi,
the following happened to me also:
1. Created a new site
2. Removed example.com from the list of sites
3. Tried to use authentication and got the error "DoesNotExist at
/accounts/login/"
4. Deleted and rebuilt the database, authentication works.

Regards,
Andres

blue_beastie wrote on 29 Jun 2006:
"I was experiencing this problem as well, so what I ended up doing is
rebuilding dropping the entire database for my project and re-running
"./manage.py syncdb". Doing this fixed the problem. I think this
problem was caused when I removed example.com from the list of Sites in

the admin interface."


--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---