Localization and date format

2010-04-24 Thread pjmorse
Is there any way to force a particular localization on date
formatting?

Our site (Django 1.0.2, Python 2.5) was set up with "UK" as the
language code for the U.K. This apparently didn't cause any problems
for years, but now that the person who made that decision is out of
arm's reach, it's been discovered that dates in the UK localization
are being displayed in... wait for it... Ukranian.

Swapping the language code to "en" (which would be correct) breaks
most of the rest of the site for reasons I don't fully understand yet.

Is there any way to either override the localization on date
formatting, or provide a parameter with the correct language code?

Thanks,

pjm

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



Re: OS X install, not in home directory?

2010-04-24 Thread pjmorse
On Apr 24, 3:03 am, Rob  wrote:
> Maybe this is more of a general python question, but when I run `sudo
> python setup.py install` it insists on putting the django package in ~/
> Library/Python/2.6/site-packages.  I want to install it in the system
> site-packages, so it get's picked up by apache and mod_wsgi.  For now
> I'll hand copy the files, but there must be a way with setup.py.  ?

Try the --prefix or --install-base options to `setup.py install`.
`python setup.py install --help` will run down the options for you; I
think --prefix=/Library/Python/2.6/site-packages/ is worth a shot?

pjm

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



Re: Error in image upload while copying file

2010-03-31 Thread pjmorse
On Mar 30, 10:53 am, bruno desthuilliers
 wrote:
> Uh. Oh, well - then you indeed have a problem :(

> Hum... Is that legacy code ? Looks pretty ugly to me - wouldn't pass a
> code review here.
> Well, assuming you're using at least Django 1.0, I suggest you get rid
> of this mess and make appropriate use of FileField /
> ImageField.upload_to:
>
> http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.mod...

Thanks, Bruno, that gives me a toehold. Yes, that's legacy code; I'm
guessing it was originally written for a pre-1.0 Django, and as noted
above the original developers suggested that downgrading Python to 2.4
would solve the problem. (Ugh.) I'll follow up on the
ImageField.upload_to and see how that does.

Thanks,

pjm

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



Re: Error in image upload while copying file

2010-03-29 Thread pjmorse
On Mar 29, 8:22 am, bruno desthuilliers
 wrote:
> On 19 mar, 20:05,pjmorse wrote:
>
> > In my application's admin console, there's a tiny form for updating
> > the image associated with a specific model.
>
> > When a file is uploaded, the application reaches this code:
>
> >         if request.method == 'POST':
> >                 file = request.FILES.copy()
>
> Err... Do you really need this line ??? I don't know what your
> remaining code (the one you didn't show) is doing exactly, but as far
> as i'm concerned, I never needed to try & copy request.FILES...

That's a good question, and one I hadn't been prepared to answer; I
didn't write this code, I just try to maintain it.

The next steps in the code are to manipulate the file name. Trying to
do this directly on request.FILES results in the error,
"'InMemoryUploadedFile' object is unsubscriptable".

Here's a wider chunk of the code. I've reformatted the comments to
make things a bit more compact.

if request.method == 'POST':
file = request.FILES.copy() # Handle profile image upload

if 'image' in file: # Profile image has been submitted
img = file['image']

# Compute filename
lst = split( img['filename'] )
random.seed()
filename = 'wmm_%d%s' %
( random.randrange(1,10,2),str( splitext( lst[1] )[1] ))
open('/tmp/' + filename, 'wb').write(img['content'])

I think this tells me that what I need to figure out is how to safely
copy an InMemoryUploadedFile object.

pjm

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



Re: Error in image upload while copying file

2010-03-29 Thread pjmorse
Continued research (I kept asking people) suggests that this is a
consequence of moving from Python2.4 to Python2.5. The options appear
to be:

* Downgrade Python to 2.4
* Find a "more compatible" copy method.

I'd really rather not downgrade Python, but I don't know how to find a
"more compatible" copy method. (My web searches so far have been
fruitless, because the keywords are too common.) Can anyone point me
in the right direction?

Thanks,

pjm

On Mar 19, 2:05 pm, pjmorse  wrote:
> In my application's admin console, there's a tiny form for updating
> the image associated with a specific model.
>
> When a file is uploaded, the application reaches this code:
>
>         if request.method == 'POST':
>                 file = request.FILES.copy()
>
> ...and fails with this error:
>
> object.__new__(cStringIO.StringO) is not safe, use
> cStringIO.StringO.__new__()
>
> The stack tracehttp://dpaste.com/hold/173776/shows me that the
> actual error is happening at a lower level than my actual call, and
> some browsing around the archives for this list tells me that (a) this
> isn't an uncommon problem, and (b) "deepcopy" seems to be the root of
> my problem.
>
> (For those who don't click through to the traceback, this is Django
> 1.0.2 final, Python 2.5.1. The traceback is from my development
> version.)
>
> How can I grab the uploaded file for future manipulation which working
> around "deepcopy"?
>
> Thanks,
>
> pjm

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



Error in image upload while copying file

2010-03-19 Thread pjmorse
In my application's admin console, there's a tiny form for updating
the image associated with a specific model.

When a file is uploaded, the application reaches this code:

if request.method == 'POST':
file = request.FILES.copy()

...and fails with this error:

object.__new__(cStringIO.StringO) is not safe, use
cStringIO.StringO.__new__()

The stack trace http://dpaste.com/hold/173776/ shows me that the
actual error is happening at a lower level than my actual call, and
some browsing around the archives for this list tells me that (a) this
isn't an uncommon problem, and (b) "deepcopy" seems to be the root of
my problem.

(For those who don't click through to the traceback, this is Django
1.0.2 final, Python 2.5.1. The traceback is from my development
version.)

How can I grab the uploaded file for future manipulation which working
around "deepcopy"?

Thanks,

pjm

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



Re: Editing a model in console: form validation fails

2010-02-04 Thread pjmorse
On Feb 3, 2:10 pm, Daniel Roseman  wrote:
> On Feb 3, 5:45 pm, pjmorse  wrote:

> > I narrowed the problem down to form validation in the view, and using
> > pdb and some debug logging commands I got the validation errors out.
> > Here's the problematic code:
> > (Pdb) pf.errors
> > {'athlete': [u'This field is required.'], 'language': [u'This field is
> > required.']}

> You don't show the code of the Athlete or AthleteProfile forms. Are
> they just standard model forms, with no excluded fields?
>
> Secondly, is the language field actually displayed on the HTML
> template for the athleteprofile form? It's significant that it's not
> in the POSTed data, which would seem to indicate that you haven't
> included the field in the template. If you've left it out for a
> reason, you should also exclude it from the form, by adding it to the
> 'exclude' tuple in the form's inner Meta class, so that it doesn't
> prevent validation.

Thanks, Daniel, good questions. The second one - that the language
wasn't actually in the field - turned out to be the key; the language
is set based on the user session inside the view (code below) but when
I followed your idea and used hidden form fields to add the athlete
and language IDs to the form, everything got assigned appropriately in
the view and validation passed.

The form code is so simple I didn't think it was relevant:

class AthleteForm(forms.ModelForm):

class Meta:
model = Athlete

class AthleteProfileForm(forms.ModelForm):

class Meta:
model = AthleteProfile

These are the associated models (I've trimmed commented code for
brevity):

class Athlete(models.Model):
def __unicode__(self):
return '%s %s' % (self.name, self.surname)

name = models.CharField(max_length=255)
surname = models.CharField(max_length=255)
country = models.ForeignKey(Country)
dob = models.DateField()
gender = models.CharField(max_length=1,choices = (('m','Male'),
('f','Female')))

user = models.ForeignKey(AdminUser,
related_name='athleter_owner_set', verbose_name = 'Creator')
modified = models.ForeignKey(AdminUser, blank = True, null = True,
related_name='athlete_modified_set', verbose_name='Modified by')

deleted = models.BooleanField(default = False)

date_created = models.DateTimeField(null = True, blank = True,
default = datetime.now)
date_modified = models.DateTimeField(null = True, blank = True,
default = datetime.now)

image = models.CharField(max_length = 255, null = True, default =
'GENERIC.jpg')


class AthleteProfile(models.Model):

def __unicode__(self):
return '%s %s' % (self.athlete.name, self.athlete.surname)

athlete = models.ForeignKey(Athlete)
language = models.ForeignKey(Language)

pbest = models.CharField("Personal
best",max_length=255,blank=True ,null = True, default = '00:00:00')
highlights = models.TextField(null = True, blank=True, default = '')
career_notes = models.TextField(blank=True ,null = True, default =
'')
personal_notes = models.TextField(blank=True ,null = True, default =
'')
additional_career_highlights = models.TextField(blank=True ,null =
True, default = '')
other_personal_bests = models.TextField(blank=True ,null = True,
default = '')
upcoming_marathons = models.TextField(blank=True ,null = True,
default = '')
wmm_highlights = models.TextField("WMM highlights",blank=True ,null =
True, default = '')
translated = models.BooleanField(default = False ,null = True, blank
= True)

It's not clear to me why the original programmer chose to normalize
the database this way, but I think their intention was to separate
translatable fields. "Language" is not displayed in the HTML template;
it's set in the view a few lines before the code I included, and based
on the user submitting the form:

def athletes_edit(request, athlete_id):
language = get_object_or_404(Language, locale =
request.session['adminlangID'])

"""
Get current athlete object
"""

athlete_obj = get_object_or_404(Athlete, pk = athlete_id)

athleteprofile, created =
AthleteProfile.objects.get_or_create(athlete = athlete_obj, language =
language)

My assumption was that when the AthleteProfileForm was created from
`athleteprofile` (which is an AthleteProfile object) that the language
value would be maintained, but apparently such is not the case.

Thanks again, Daniel, this has been a thorn in my side for several
days and now I've closed it up.

pjm

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



Editing a model in console: form validation fails

2010-02-03 Thread pjmorse
I'm trying to sort out a problem in the console with editing an
object. The user-reported problem, which I verified, is that changes
made in the edit form are not made in the database; the user gets no
error message, but their changes aren't made, either.

I narrowed the problem down to form validation in the view, and using
pdb and some debug logging commands I got the validation errors out.
Here's the problematic code:

if request.method == 'POST':
data = request.POST.copy()
import pdb; pdb.set_trace() # My debugger call

a = AthleteForm(data,instance=athlete_obj)
pf = AthleteProfileForm(data,instance=athleteprofile)

Now, in the debugger:

-> a = AthleteForm(data,instance=athlete_obj)
(Pdb) n
> /Users/morse/Sites/wmm/console/athletes/views.py(538)athletes_edit()
-> pf = AthleteProfileForm(data,instance=athleteprofile)
(Pdb) n
(Pdb) pf.is_valid()
False
(Pdb) pf.errors
{'athlete': [u'This field is required.'], 'language': [u'This field is
required.']}
(Pdb) athleteprofile.language

(Pdb) athleteprofile.athlete


So I've established that the AthleteProfile object the
AthleteProfileForm is bound to has these values set, but the
AthleteProfileForm does not. Does this mean the fields are missing
from the "data" (and therefore from the request.POST)?

(Pdb) pf.base_fields
{'athlete': , 'language': , 'pbest': , 'highlights': , 'career_notes': , 'personal_notes': , 'additional_career_highlights':
,
'other_personal_bests': , 'upcoming_marathons': , 'wmm_highlights': , 'translated': }

And, edited for brevity:

(Pdb) data


The DOB and 'pbest' fields are blatantly false, data I submitted to
establish that nothing was changing in the database. Notice that some
of the fields are part of the Athlete model and not the AthleteProfile
model.

How can I give the AthleteProfileForm correct values (either in the
form for data submission, or directly in the view code) so it will
validate? Also, is there another debugging method I can use to better
reveal what's going wrong here?

I've looked through the list archives for the last year or so and
haven't found anything similar; I fear that's because it's so obvious
everyone else is figuring it out for themselves. The site is running
on Django 1.0.2 due to decisions made before my involvement with the
project (and part of my level of frustration here is that I've never
seen this particular code working correctly, which is making it very
hard for me to understand what's going wrong.)

Thanks,

pjm

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



Re: Saving several copies of an object

2010-01-06 Thread pjmorse
On Jan 5, 1:11 pm, Matthias Kestenholz 
wrote:
> This won't do it, because ns is a Form, not a Model object. Something
> like this might work though:
>
> obj = ns.save(commit=False)
>
> for language in languages:
>     obj.id = None
>     obj.language = language
>     obj.save()
>
> Matthias

Thanks, Matthias, that does work.

Noting Daniel's comment, here's what the original code looked like:

languages = Language.objects.all()

for language in languages:
"""add required fields"""
nsForm.cleaned_data['news'] = news_obj
nsForm.cleaned_data['language'] = language
nsForm.cleaned_data['news_date'] = datetime.now()
if language == user.language:
nsForm.cleaned_data['translated'] = True
else:
nsForm.cleaned_data['translated'] = False
nsForm.save()

Following Matthias' example and taking some redundant code out of the
loop, here's the code that worked:

"""add required fields"""
nsForm.cleaned_data['news'] = news_obj
nsForm.cleaned_data['news_date'] = datetime.now()
languages = Language.objects.all()
obj = nsForm.save(commit=False)

for language in languages:
obj.id = None
obj.language = language
if language == user.race.language:
obj.translated = True
else:
obj.translated = False
obj.save()

Thanks again, everyone.

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




Saving several copies of an object

2010-01-05 Thread pjmorse
I recently picked up a Django project from another developer, and I
seem to have introduced an annoying bug.

It's a multi-language site: US, UK, DE. (Why US and UK are considered
different languages is organizational politics beyond the scope of my
work.) When a "news article" is created, its body text is used to
create three "news translations" (NewsTrans object), one for each
language.

This is done by looping over the list of languages and saving a
NewsTrans in each language. The source language is marked as already
translated, the other two are not (that is, they still need
translating).

The problem is that this is done with ns.save() (where ns is a
NewsTransForm with the submitted data), and what's actually happening
is that one NewsTrans is created, then it is updated twice, ending in
the third language.

I thought I could fix this with ns.save(force_insert=True) but that
throws errors instead: "save() got an unexpected keyword argument
'force_insert'".

The site is using Django 1.0.2.

I'm pretty much wedged on this now, so any pointers would be greatly
welcomed.
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.