Re: PUNTARE CON DJANGO SU BILANCIATORE ORACLE ATTRAVERSO IL TSNAME

2011-10-18 Thread Ian
On Oct 18, 2:37 am, mxm982  wrote:
> Ciao ragazzi ho realizzato una piccola applicazione in Django che
> aggiorna delle tabelle di uno schema gia preesistente. Ora ho la
> necessita di puntare al rach della db attraverso appunto il tsname non
> tramite sid come viene richiesto dal file setting.py potete aiutarmi

If you don't have a TNS name, you can identify the database by
hostname, listener port, and SID.  See the second example at:
https://docs.djangoproject.com/en/1.3/ref/databases/#id11

Cheers,
Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: PayPal Adaptive Payments

2011-10-09 Thread Ian
So I got the basic merchant functionality working, but I can't figure
out the best way to automatically split the payment 3 ways... advice?

On Oct 9, 3:02 pm, Ian  wrote:
> Thanks, Markus! That looks perfect!
>
> Shawn, I was more curious if this is even possible to do with django.
> I was just doing research and wanted to know if there was a better
> payment system tailored for django (the 'merchant' project looks
> perfect)
>
> thanks guys!
>
> On Oct 8, 4:26 pm, Markus Gattol  wrote:
>
>
>
>
>
>
>
> > Rather than reinventing the wheel take a look 
> > athttps://github.com/agiliq/merchantIt'spossible to split one payment into
> > 90,5,5 as you want, all you need to do is write a little logic atop
> > merchant.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: PayPal Adaptive Payments

2011-10-09 Thread Ian
Thanks, Markus! That looks perfect!

Shawn, I was more curious if this is even possible to do with django.
I was just doing research and wanted to know if there was a better
payment system tailored for django (the 'merchant' project looks
perfect)

thanks guys!

On Oct 8, 4:26 pm, Markus Gattol  wrote:
> Rather than reinventing the wheel take a look 
> athttps://github.com/agiliq/merchantIt's possible to split one payment into
> 90,5,5 as you want, all you need to do is write a little logic atop
> merchant.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



PayPal Adaptive Payments

2011-10-08 Thread Ian
I've been looking at this:
https://www.x.com/docs/DOC-3084

but I'm trying to set it up with Adaptive Payments.

Basically, I need a payment to be split between a few users... so if I
purchase something from seller A:
seller A gets 90%
person B gets 5%
person C gets 5%

This is easy to do with PayPal's Adaptive Payments, and I've done it
with PHP, but I'm trying to get it working on Django.  Any advice?

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django image upload

2011-10-06 Thread Ian
So should I put it in a try/catch block to verify it's an image?

Also, how do I go about saving it as a different name (as the ID of
the model, for example)?

On Oct 6, 7:26 pm, Kurtis Mullins  wrote:
> ImageField uses PIL (Python Imaging Library) to verify if it's a valid
> image, if I understand it correctly.
>
>
>
>
>
>
>
> On Thu, Oct 6, 2011 at 6:21 PM, Ian  wrote:
> > Ah! Got it working! How do I make sure the files are only images?  Is
> > there a way to check the extension?  Also, how would I rename the
> > file?
>
> > Thanks!
>
> > On Oct 6, 3:46 pm, bazaarsoft  wrote:
> > > Noticed a couple of typos in my reply:
>
> > > > I have "MEDIA_ROOT = '/Users/storefiles/' in my settings.py folder,
>
> > > file, not folder
>
> > > > and the upload_to param in my model set to 'pluginFiles/%Y/%m/%H/%M/'.
>
> > > is actually 'pluginFiles/%Y/%m/%d/%H/%M/'
>
> > > jay
>
> > > On Oct 6, 2:41 pm, bazaarsoft  wrote:
>
> > > > > Also, I'm confused whether upload_to should be set in settings.py or
> > > > > models.py
>
> > > > It's actually a mix - if you have MEDIA_ROOT defined in settings.py,
> > > > then it will use that as the first part of the path. Then, what you
> > > > pass in the upload_to field will be appended to that. So, in my case,
> > > > I have "MEDIA_ROOT = '/Users/storefiles/' in my settings.py folder,
> > > > and the upload_to param in my model set to 'pluginFiles/%Y/%m/%H/%M/'.
> > > > What ultimately happens, then, is that the file gets stored here:
>
> > > > /Users/storefiles/pluginfiles/2011/10/06/02/38/somefile.zip
>
> > > > So, you must have at least one of those set and the path must be fully
> > > > write enabled for whatever process is running your Django app. For my
> > > > testing, I just made /Users/storefiles writable by everyone since I
> > > > don't really care about securing that directory on my dev Mac.
>
> > > > jay
>
> > > > On Oct 6, 1:08 pm, Ian  wrote:
>
> > > > > I can't seem to get it working.  It won't let my sync the database
> > > > > with this code:
> > > > > image = ImageField(upload_to=None[, max_length=100, **options])
>
> > > > > Also, I'm confused whether upload_to should be set in settings.py or
> > > > > models.py
>
> > > > > Thanks!
>
> > > > > On Oct 6, 6:11 am, BILLION Sébastien 
> > > > > wrote:
>
> > > > > > Hi,
>
> >http://www.nitinh.com/2009/02/django-example-filefield-and-imagefield/
>
> > > > > > It the same for ImageField
>
> > > > > > BILLION S�bastien
>
> > > > > > the Answer to the ultimate question of life, the universe and
> > everything
> > > > > > is 42
>
> > > > > >http://www.sebastienbillion.com/<http://www.sebastienbillion.com/>
>
> > > > > > Le 06/10/2011 05:22, Ian a �crit :
>
> > > > > > > Hey Everyone,
>
> > > > > > > I'm new to django, but I love it so far!
>
> > > > > > > I'm trying to figure out how to upload an image (restrict it to
> > images
> > > > > > > only) and resave it as a different name.
> > > > > > > Eventually, I'll want to upload it to S3, but for now, I'm just
> > > > > > > testing it on my computer with runserver (so I'm not sure where
> > it
> > > > > > > should be saving it).
>
> > > > > > > There are hundreds of tutorials for this online, but they are
> > either
> > > > > > > outdated or more complex than I'm looking for.
>
> > > > > > > Right now, I have a template with the form in it.  I'm not sure
> > where
> > > > > > > to go from there.
>
> > > > > > > Thanks so much!
> > > > > > > Sorry if this question is too basic!
>
> > --
> > 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
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django image upload

2011-10-06 Thread Ian
So should I put it in a try/catch block to verify it's an image?

Also, how do I go about saving it as a different name (as the ID of
the model, for example)?

On Oct 6, 7:26 pm, Kurtis Mullins  wrote:
> ImageField uses PIL (Python Imaging Library) to verify if it's a valid
> image, if I understand it correctly.
>
>
>
>
>
>
>
> On Thu, Oct 6, 2011 at 6:21 PM, Ian  wrote:
> > Ah! Got it working! How do I make sure the files are only images?  Is
> > there a way to check the extension?  Also, how would I rename the
> > file?
>
> > Thanks!
>
> > On Oct 6, 3:46 pm, bazaarsoft  wrote:
> > > Noticed a couple of typos in my reply:
>
> > > > I have "MEDIA_ROOT = '/Users/storefiles/' in my settings.py folder,
>
> > > file, not folder
>
> > > > and the upload_to param in my model set to 'pluginFiles/%Y/%m/%H/%M/'.
>
> > > is actually 'pluginFiles/%Y/%m/%d/%H/%M/'
>
> > > jay
>
> > > On Oct 6, 2:41 pm, bazaarsoft  wrote:
>
> > > > > Also, I'm confused whether upload_to should be set in settings.py or
> > > > > models.py
>
> > > > It's actually a mix - if you have MEDIA_ROOT defined in settings.py,
> > > > then it will use that as the first part of the path. Then, what you
> > > > pass in the upload_to field will be appended to that. So, in my case,
> > > > I have "MEDIA_ROOT = '/Users/storefiles/' in my settings.py folder,
> > > > and the upload_to param in my model set to 'pluginFiles/%Y/%m/%H/%M/'.
> > > > What ultimately happens, then, is that the file gets stored here:
>
> > > > /Users/storefiles/pluginfiles/2011/10/06/02/38/somefile.zip
>
> > > > So, you must have at least one of those set and the path must be fully
> > > > write enabled for whatever process is running your Django app. For my
> > > > testing, I just made /Users/storefiles writable by everyone since I
> > > > don't really care about securing that directory on my dev Mac.
>
> > > > jay
>
> > > > On Oct 6, 1:08 pm, Ian  wrote:
>
> > > > > I can't seem to get it working.  It won't let my sync the database
> > > > > with this code:
> > > > > image = ImageField(upload_to=None[, max_length=100, **options])
>
> > > > > Also, I'm confused whether upload_to should be set in settings.py or
> > > > > models.py
>
> > > > > Thanks!
>
> > > > > On Oct 6, 6:11 am, BILLION Sébastien 
> > > > > wrote:
>
> > > > > > Hi,
>
> >http://www.nitinh.com/2009/02/django-example-filefield-and-imagefield/
>
> > > > > > It the same for ImageField
>
> > > > > > BILLION S�bastien
>
> > > > > > the Answer to the ultimate question of life, the universe and
> > everything
> > > > > > is 42
>
> > > > > >http://www.sebastienbillion.com/<http://www.sebastienbillion.com/>
>
> > > > > > Le 06/10/2011 05:22, Ian a �crit :
>
> > > > > > > Hey Everyone,
>
> > > > > > > I'm new to django, but I love it so far!
>
> > > > > > > I'm trying to figure out how to upload an image (restrict it to
> > images
> > > > > > > only) and resave it as a different name.
> > > > > > > Eventually, I'll want to upload it to S3, but for now, I'm just
> > > > > > > testing it on my computer with runserver (so I'm not sure where
> > it
> > > > > > > should be saving it).
>
> > > > > > > There are hundreds of tutorials for this online, but they are
> > either
> > > > > > > outdated or more complex than I'm looking for.
>
> > > > > > > Right now, I have a template with the form in it.  I'm not sure
> > where
> > > > > > > to go from there.
>
> > > > > > > Thanks so much!
> > > > > > > Sorry if this question is too basic!
>
> > --
> > 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
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django image upload

2011-10-06 Thread Ian
Ah! Got it working! How do I make sure the files are only images?  Is
there a way to check the extension?  Also, how would I rename the
file?

Thanks!

On Oct 6, 3:46 pm, bazaarsoft  wrote:
> Noticed a couple of typos in my reply:
>
> > I have "MEDIA_ROOT = '/Users/storefiles/' in my settings.py folder,
>
> file, not folder
>
> > and the upload_to param in my model set to 'pluginFiles/%Y/%m/%H/%M/'.
>
> is actually 'pluginFiles/%Y/%m/%d/%H/%M/'
>
> jay
>
> On Oct 6, 2:41 pm, bazaarsoft  wrote:
>
>
>
>
>
>
>
> > > Also, I'm confused whether upload_to should be set in settings.py or
> > > models.py
>
> > It's actually a mix - if you have MEDIA_ROOT defined in settings.py,
> > then it will use that as the first part of the path. Then, what you
> > pass in the upload_to field will be appended to that. So, in my case,
> > I have "MEDIA_ROOT = '/Users/storefiles/' in my settings.py folder,
> > and the upload_to param in my model set to 'pluginFiles/%Y/%m/%H/%M/'.
> > What ultimately happens, then, is that the file gets stored here:
>
> > /Users/storefiles/pluginfiles/2011/10/06/02/38/somefile.zip
>
> > So, you must have at least one of those set and the path must be fully
> > write enabled for whatever process is running your Django app. For my
> > testing, I just made /Users/storefiles writable by everyone since I
> > don't really care about securing that directory on my dev Mac.
>
> > jay
>
> > On Oct 6, 1:08 pm, Ian  wrote:
>
> > > I can't seem to get it working.  It won't let my sync the database
> > > with this code:
> > > image = ImageField(upload_to=None[, max_length=100, **options])
>
> > > Also, I'm confused whether upload_to should be set in settings.py or
> > > models.py
>
> > > Thanks!
>
> > > On Oct 6, 6:11 am, BILLION Sébastien 
> > > wrote:
>
> > > > Hi,
>
> > > >http://www.nitinh.com/2009/02/django-example-filefield-and-imagefield/
>
> > > > It the same for ImageField
>
> > > > BILLION S�bastien
>
> > > > the Answer to the ultimate question of life, the universe and everything
> > > > is 42
>
> > > >http://www.sebastienbillion.com/<http://www.sebastienbillion.com/>
>
> > > > Le 06/10/2011 05:22, Ian a �crit :
>
> > > > > Hey Everyone,
>
> > > > > I'm new to django, but I love it so far!
>
> > > > > I'm trying to figure out how to upload an image (restrict it to images
> > > > > only) and resave it as a different name.
> > > > > Eventually, I'll want to upload it to S3, but for now, I'm just
> > > > > testing it on my computer with runserver (so I'm not sure where it
> > > > > should be saving it).
>
> > > > > There are hundreds of tutorials for this online, but they are either
> > > > > outdated or more complex than I'm looking for.
>
> > > > > Right now, I have a template with the form in it.  I'm not sure where
> > > > > to go from there.
>
> > > > > Thanks so much!
> > > > > Sorry if this question is too basic!

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django image upload

2011-10-06 Thread Ian
I can't seem to get it working.  It won't let my sync the database
with this code:
image = ImageField(upload_to=None[, max_length=100, **options])

Also, I'm confused whether upload_to should be set in settings.py or
models.py

Thanks!

On Oct 6, 6:11 am, BILLION Sébastien 
wrote:
> Hi,
>
> http://www.nitinh.com/2009/02/django-example-filefield-and-imagefield/
>
> It the same for ImageField
>
> BILLION S�bastien
>
> the Answer to the ultimate question of life, the universe and everything
> is 42
>
> http://www.sebastienbillion.com/<http://www.sebastienbillion.com/>
>
> Le 06/10/2011 05:22, Ian a �crit :
>
>
>
>
>
>
>
> > Hey Everyone,
>
> > I'm new to django, but I love it so far!
>
> > I'm trying to figure out how to upload an image (restrict it to images
> > only) and resave it as a different name.
> > Eventually, I'll want to upload it to S3, but for now, I'm just
> > testing it on my computer with runserver (so I'm not sure where it
> > should be saving it).
>
> > There are hundreds of tutorials for this online, but they are either
> > outdated or more complex than I'm looking for.
>
> > Right now, I have a template with the form in it.  I'm not sure where
> > to go from there.
>
> > Thanks so much!
> > Sorry if this question is too basic!

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django image upload

2011-10-05 Thread Ian
Hey Everyone,

I'm new to django, but I love it so far!

I'm trying to figure out how to upload an image (restrict it to images
only) and resave it as a different name.
Eventually, I'll want to upload it to S3, but for now, I'm just
testing it on my computer with runserver (so I'm not sure where it
should be saving it).

There are hundreds of tutorials for this online, but they are either
outdated or more complex than I'm looking for.

Right now, I have a template with the form in it.  I'm not sure where
to go from there.

Thanks so much!
Sorry if this question is too basic!

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Randomly clearing database tables

2011-10-05 Thread Ian Kelly
On Tue, Oct 4, 2011 at 2:28 PM, msbuck  wrote:
> Below is the settings. I am fairly new to python unit testing so my
> understanding of things could be better. But right now, if I select
> Run As -> Python Unit Test will my project is selected, it runs all of
> my Django tests and clobbers my working db as a result. The test
> runner also appears to be ignoring my @skipUnless decorators that
> should prevent db tests from running if settings.IS_TEST is set to
> False. I'm getting frustrated again!

I haven't used PyDev, but I would imagine it's probably importing the
management commands and running them programmatically, rather than
simply trying to run manage.py.  That would explain why your IS_TEST
is False.  According to the docs, PyDev has a DJANGO_SETTINGS_MODULE
variable.  I suggest setting that to an alternate settings.py that
contains your test settings.

I still can't see any reason why the tests would be flushing your
tables, though.  Does it happen when you issue manage.py test (using
the oracle backend) as well, or only from PyDev?  Could there be
something in your app tests that might be causing the flush?

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Randomly clearing database tables

2011-10-04 Thread Ian
On Oct 4, 10:30 am, msbuck  wrote:
> Good news! Yesterday, I was repeatedly starting the development server
> from Eclipse which is on the Run As  -> menu which cascades to Run
> Server or Run Python Unit Test. I must have accidently clicked that we
> I really wanted to start my server. That command runs the PyDev Test
> runner and that's what clears out my tables. Now I just have to figure
> out how to disable the option in Eclipse or get it to do nothing. Any
> suggestions in this area would be appreciated and thanks to all for
> the suggestions.

What does your DATABASES setting look like?  Everything test-related
is supposed to be run under a separate schema and tablespace to avoid
modifying actual data.  It sounds like something is running in the
wrong place.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Platform system with Django?

2011-09-26 Thread Ian
So I already have my site up and running in PHP/mySQL, but I want to
move to Django (and learn it in the process!)

The way I do it now is have a main table of posts, and the table of
posts has a column called "site".  If the user accesses myproject.com/
mySite, it loads the posts from the database for everything with the
condition site=="mySite"
So I do it the same way in Django?  Use the same logic, with Django's
sites framework?

That makes my life easy since the application logic is already done!
How do I handle the subdomain, though?

Thanks!

On Sep 26, 9:26 am, jmontoya  wrote:
> You can use pinax is based in django and it has a lots of "website
> templates", intranet, blog, social etc
> You can easly customized it ...
>
> http://pinaxproject.com/
>
> Regards,
>
> Julio
>
> On Sep 26, 6:18 am, Ian  wrote:
>
>
>
>
>
>
>
> > I'm new to django, and at this point all I've done is the tutorial.
>
> > But my end goal is to create a website that serves as aplatform
> > system.
>
> > I want users to go to my site, create an account, edit some settings/
> > preferences, and a subdomain (can you do this with django?).
>
> > Then within each subdomain, other people can register as users to this
> > particular subdomain, post things, etc.
>
> > Is it possible to do this?  I can imagine the structure and how to get
> > the second part working (having users register on a particular
> > subdomain site, post things, etc), but I'm having trouble figuring out
> > where to get started with the first part (creating the subdomain site)
>
> > Is there a tutorial or guide to get me started with thisplatform
> > concept?  Thanks so much!

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Platform system with Django?

2011-09-25 Thread Ian
I'm new to django, and at this point all I've done is the tutorial.

But my end goal is to create a website that serves as a platform
system.

I want users to go to my site, create an account, edit some settings/
preferences, and a subdomain (can you do this with django?).

Then within each subdomain, other people can register as users to this
particular subdomain, post things, etc.

Is it possible to do this?  I can imagine the structure and how to get
the second part working (having users register on a particular
subdomain site, post things, etc), but I'm having trouble figuring out
where to get started with the first part (creating the subdomain site)

Is there a tutorial or guide to get me started with this platform
concept?  Thanks so much!

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How can I use {{variable}} in custom templatetag?

2011-08-08 Thread Ian Clelland
On Mon, Aug 8, 2011 at 4:36 PM, Josh  wrote:

> >
>>
>> >If you need to push back a value in a variable call related_entries, then
>>> you will want to set a value in the context dictionary:
>>
>> >
>>
>> >context[related_entries] = 
>>
>>
> Correction on earlier mail when trying some other things. I do this in the
> def render. This looks like:
>
> class RelatedEntryNode(template.Node):
>
> def __init__(self, model, number, categories, varname):
> self.model = model
> self.number = int(number)
> self.categories = template.Variable(categories)
> self.varname = varname
>

Ok, so this means that:
self.model is a string; literally, in your example, "weblog.entry"
self.number is an integer
self.categories is a variable reference -- you can resolve it at render
time, to obtain the value of object.categories (or, depending on what object
happens to be, Django could try object['categories'], or
object.categories(), or a few other things -- the important thing is that
the Django template framework will do the work of getting you a value)
self.varname is another string; in this case, "related_entries"

Now, I *think* that you want self.model to be a Variable as well, just like
self.categories, because I *don't think* that you are actually interested in
the string "weblog.entry" -- I think that you want the value of the entry
attribute of the weblog object. You want Django to resolve that value for
you at template render time.


>
> def render(self, context):
> related = self.categories.resolve(context)
> context[self.varname] = related
> return ''
>
>
> >
>>
>> >You won't be able to resolve it as a Variable, because it (presumably)
>>> doesn't even exist >before you call your custom tag, but once you set it on
>>> the context object, it will be >available to the rest of the template.
>>
>>
>>> This I don't understand. As I understand Django (but correct me if I'm
>>> wrong) the related_entries should be a dictionary or list  of
>>> Entry-instances.
>>
>>
>>
That depends entirely on what *you* want *your template tag* to do. Given
all of your descriptions, though, I'm led to believe that you want your tag
to create a new variable, which you can use in your template. So, when you
put

{% get_related_entries weblog.entry 5 from object.categories as
related_entries %}

in your template, {{related_entries}} doesn't exist as a variable *before*
your tag, but *after* your tag, it has some value, which you will have
computed in the render() method.

In that case, then *in your node class*, self.related_entries is just a
string -- the name of the variable to create. In your example, it happens to
be the string "related_entries", but you could have written

{% get_related_entries weblog.entry 5 from object.categories as
cheeseburger_hotel %}

and then self.related_entries would contain the string "cheeseburger_hotel".
But that's fine, because your render() method is going to compute some
value, probably a list of Entry instances in this case, and then it will
create a new context variable, with the statement;

context[self.related_entries] = 

And that is what is going to create the context variable
{{related_entries}}, or {{cheeseburger_hotel}}, or whatever the template
author asked for.


I hope that helps -- I think that you may be confusing things by using the
same names for your python variables as you do for your template variables,
when they really are very different things.



-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How can I use {{variable}} in custom templatetag?

2011-08-08 Thread Ian Clelland
On Mon, Aug 8, 2011 at 2:20 PM, Josh  wrote:

> >It sounds like you're not resolving the variable at all in your render
> method --
> >
> >When you construct the template node, you work with Variable objects,
> which represent the >context variable as it exists in the template source
> (eg, html).
> >
> >At the point where you actually render your output, you want to resolve
> that Variable, so >that the template framework actually determines what the
> contents of that variable should >be, given the current context.
> >
> >The example at
> https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#passing->template-variables-to-the-tag
> shows how it should be done. Construct a Variable object in
> >node.__init__(), and use variable.resolve(context) in node.render()
> >
> >Ian
>
> I already tried that route from the sample and that creates the unicode
> error. Relevant parts of my code are below.
>
>
These are my assumptions about the bits of code you've posted:


> models.py
> categories = models.ManyToManyField('Category', blank=True, null=True,
> default = None)
>

Assumption: categories is a field defined within a standard Django model;
Category is another model you have defined.


>
> {% get_related_entries weblog.entry 5 from object.categories as
> related_entries %}
>  {% for entry in related_entries %}
>   {{ entry.title }}
>  {% endfor %}
>
>
Assumption: weblog and object are context variables provided to the template
from the view. object is an instance of the model with the categories m2m
field you showed above.

I'm not sure how weblog.entry is relevant.



>
> def __init__(self, model, number, categories, varname):
> self.categories = template.Variable(categories)
>

Assumption: model, number, categories, and varname are the parameters from
the template tag you show in the template snippet above. I am guessing that
they are all just the strings, exactly as they appear in the template.

>
>
> def render(self, context):
> related = self.varname.resolve(context)
> return related
>

At this point, I presume that you have defined self.varname in __init__
above, as "self.varname = varname", and you have just chosen not to paste
that line.


>
> *Caught AttributeError while rendering: 'unicode' object has no attribute
> 'resolve'*
>

First off, self.varname, if I am correct, is just the string
"related_entries" here. It doesn't have a "resolve" method, because it's
just a string. Variable objects, like self.context, have a "resolve"
method.

If you want to access the categories that you have mentioned in the
template, then you can use
self.categories.resolve(context)

If you want to access "weblog.entry", then you will need to create a
Variable from it, like you did with categories:

def __init__(...):
...
self.model = template.Variable(model)
...

and then resolve it in render(), as self.model.resolve(context)

If you need to push back a value in a variable call related_entries, then
you will want to set a value in the context dictionary:

context[related_entries] = 

You won't be able to resolve it as a Variable, because it (presumably)
doesn't even exist before you call your custom tag, but once you set it on
the context object, it will be available to the rest of the template.

Hope this helps,

Ian




*
> *
> When I view the entry.categories from the manage shell, it returns a list
> of categories (I also tried with from object instead of object.categories in
> the templatetag, but that gave the same error)
>
> In [7]: c.categories.all()
> Out[7]: [, , ]
>
> Somehow I have to iterate the list of categories (which consist of the name
> and not the Category.id and retrieve other entries with the same category in
> the Node render. I have been looking into include-tags too, but I also got
> iterating errors. I cannot imagine that there isn't an easy solution for
> these kind of queries. These kind of queries are pretty common to perform,
> but how ???
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/KsGYSEO2NUkJ.
>
> To post to this group, send email to django-users@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.
>



-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How can I use {{variable}} in custom templatetag?

2011-08-08 Thread Ian Clelland
On Mon, Aug 8, 2011 at 12:14 PM, Josh  wrote:

> >{% get_related_entries weblog.entry 5 from object.categories as
> related_entries %}
>
> I found that out already. Now I'm pretty sure the problem is in the
> rendering. As far as I can tell ( I don't know how to test template tags in
> a shell ) I get a list of the names of the categories back.
>
>
>- When I try to iterate the list, I get the  'Caught TypeError while
>rendering: 'Variable' object is not iterable' error.
>- When I don't iterate the variable I get the 'Caught TypeError while
>rendering: int() argument must be a string or a number, not 'Variable'
>- When I try to append queries (with Q or the normal way, because I
>need an OR relation), that works neither.
>
> It sounds like you're not resolving the variable at all in your render
method --

When you construct the template node, you work with Variable objects, which
represent the context variable as it exists in the template source (eg,
html).

At the point where you actually render your output, you want to resolve that
Variable, so that the template framework actually determines what the
contents of that variable should be, given the current context.

The example at
https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#passing-template-variables-to-the-tag
shows
how it should be done. Construct a Variable object in node.__init__(), and
use variable.resolve(context) in node.render()

Ian


>
>-
>
> ??? I don't know how to continue. I'm thinking now of solving this outside
> Django in a 'normal' python script (somehow) and pass the values as
> formatted html back to the template. That shouldn't be necessary I think.
> I'm sure I'm overlooking a very fundamental issue with templates and
> templatetags, but I just don't get it (yet).
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/yYKP0Xoz9XkJ.
>
> To post to this group, send email to django-users@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.
>



-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: object value distinct for ForeignKey

2011-07-27 Thread Ian Clelland
On Wed, Jul 27, 2011 at 9:29 AM, Ian Clelland  wrote:

>
>
> On Mon, Jul 25, 2011 at 11:29 AM, Alfredo Alessandrini <
> alfreal...@gmail.com> wrote:
>
>> Hi,
>>
>> I've a model testDB with a foreignkey "country" related to another
>> database.
>>
>> I need to retrieve the unique value of country.common_name.
>>
>> With this
>>
>> country_list = testDB.objects.values('country').distinct
>>
>> I can retrieve the unique value, but only the ID.
>>
>> In [63]: testDB.objects.values('country').distinct
>> Out[63]: > {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
>> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
>> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
>> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
>> {'country': 0L}, {'country': 0L}, {'country': 0L}, '...(remaining
>> elements truncated)...']>
>>
>> How can I  retrieve the attribute "common_name" of the country object?
>>
>
> The "" is usually a clue that what you have retrieved is
> actually a method, and you haven't called that method yet.
>
> Try:
> testDB.objects.values('country').distinct()
>
> (Although you should probably also read the note here:
> https://docs.djangoproject.com/en/1.3/ref/models/querysets/#distinct to
> see why you might want to  be writing
> testDB.objects.order_by().values('country').distinct() )
>
>

And this time, I'll actually respond after reading the last line of your
question -- if what you want is a list of distinct country *names*, where
the name is a field on the country object, you are looking for somethng like
this:

testDB.objects.order_by().values('country__common_name').distinct()


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: object value distinct for ForeignKey

2011-07-27 Thread Ian Clelland
On Mon, Jul 25, 2011 at 11:29 AM, Alfredo Alessandrini  wrote:

> Hi,
>
> I've a model testDB with a foreignkey "country" related to another
> database.
>
> I need to retrieve the unique value of country.common_name.
>
> With this
>
> country_list = testDB.objects.values('country').distinct
>
> I can retrieve the unique value, but only the ID.
>
> In [63]: testDB.objects.values('country').distinct
> Out[63]:  {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
> {'country': 0L}, {'country': 0L}, {'country': 0L}, '...(remaining
> elements truncated)...']>
>
> How can I  retrieve the attribute "common_name" of the country object?
>

The "" is usually a clue that what you have retrieved is
actually a method, and you haven't called that method yet.

Try:
testDB.objects.values('country').distinct()

(Although you should probably also read the note here:
https://docs.djangoproject.com/en/1.3/ref/models/querysets/#distinct to see
why you might want to  be writing
testDB.objects.order_by().values('country').distinct() )


>
> thanks in advance,
>
> Alfredo
>
> --
> 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
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: in my model, how can I tell when I'm saving a new item

2011-07-25 Thread Ian Clelland
On Mon, Jul 25, 2011 at 4:05 PM, webcomm  wrote:

> > Thanks.  Any idea why the following isn't working in my News class?
> > The processing doesn't get to that exit call, even if it's a new item.
> >
> > def save(self, *args, **kwargs):
> > if not hasattr(self,'id'):
> > import sys
> > sys.exit('must be a new item')
> > super(News, self).save(*args, **kwargs)
>
>
> hasattr doesn't work in this situation, or I'm not using it right.  In
> any case, the following works:
>
>def save(self, *args, **kwargs):
> if not self.id:
>import sys
>sys.exit('a new item')
> super(News, self).save(*args, **kwargs)
>

webcomm,

Whether you have defined an 'id' field in your model, or let Django do it
for you, each of your objects will "have" an id attribute, and so
hasattr(my_object, 'id') will always be true. The *value* of that attribute
might be None, though, and that's why works when you simply test self.id,
like you did above.

hasattr is generally useful in a function when you are not sure what kind of
object has been passed in, or if you want to tell whether an object has been
augmented with a specific attribute. When you know that the attribute
exists, then you can use getattr(self, "id"), or just access the attribute
directly (like "self.id")


That being said, though, there are situations where you can't rely on an id
being a guarantee that the object already exists. Like any field, it is
possible to specify the id when creating an object in memory, like this:

new_object = News(id=1, headline="Breaking news!", content="Database
broken!")
new_object.save()

This object will have an id set when the save() method checks for it, and so
any code that you needed to run for new items will be skipped.

In fact, this is exactly what happens when you load fixtures, either with
"manage.py loaddata", or by using fixtures in tests.

If there is code that absolutely has to run when a new object is created,
(or code that needs to run on update, but absolutely cannot run on new
objects before insertion), then you may be better off using a post-save
signal handler, and checking the "created" argument that gets passed to it.


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: 'settings' referenced before assignment

2011-07-20 Thread Ian Clelland
On Wed, Jul 20, 2011 at 1:14 PM, ydjango  wrote:

> Occasionally I see this error in my app,
>
> UnboundLocalError: local variable 'settings' referenced before
> assignment
>
> I have in my views .py
>
> from django.conf import settings
> other imports...
>
> def new_view(request):
>if not request.user.is_authenticated():
>return HttpResponseRedirect(settings.ENV_URL) <-=== this
> is where error is thrown.
>...
>
> What could be the reason? How can I prevent from occurring.
>
> I am using django 1.1, python 2.5 and mod_wsgi
>
>
If, later in your view function, you have an assignment to settings,
something like

settings = "abcde"

then, when the Python parser first examines your function, it will classify
settings as a local variable, regardless of whether it is imported above or
not. Accessing that local variable before its first assignment will be
considered an error, and Python will refuse to compile the function.

To fix this, you should either put "global settings" at the top of your
function (if you really do want to overwrite it), or remove the assignment
to the 'settings' variable (if you don't), or change the name of the
variable you assign to (if it was an accident).


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Calling a custom templatetag inside a block/extrahead-block?

2011-07-04 Thread Ian Clelland
On Monday, July 4, 2011, Thomas Weholt  wrote:
> I've created a templatetag called {% kolibri_imports %} which I use
> the in the head-section of my templates. It imports related to
> stylesheets, javascript libraries etc for my kolibri-package. This
> works fine when I've control over the base-template I'm extending, but
> when I want to extend a template which defines a extrahead for me to
> add stuff to, I get an error trying to call my
> kolibri_imports-templatetag. Now I want to call that templatetag
> inside a
>
> {% block extrahead %}
> {% kolibri_imports %}
> {% endblock %}
>
> but I get the following error:
>
> Invalid block tag: 'kolibri_imports', expected 'endblock' or 'endblock
> extrahead'
>
> So; How can I call a defined templatetag inside my {% block extrahead
> %}-block? I've tried
>
> {% block extrahead %}
> {{kolibri_imports }}
>
> But that didn't produce anything.
>
> This is probably simple, but ... thanks for you input.
>
> --
> Mvh/Best regards,
> Thomas Weholt
> http://www.weholt.org
>
> --
> 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 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

Are you loading the template tag library in the template that extends the base?

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Calling a custom templatetag inside a block/extrahead-block?

2011-07-04 Thread Ian Clelland
On Monday, July 4, 2011, Thomas Weholt  wrote:
> I've created a templatetag called {% kolibri_imports %} which I use
> the in the head-section of my templates. It imports related to
> stylesheets, javascript libraries etc for my kolibri-package. This
> works fine when I've control over the base-template I'm extending, but
> when I want to extend a template which defines a extrahead for me to
> add stuff to, I get an error trying to call my
> kolibri_imports-templatetag. Now I want to call that templatetag
> inside a
>
> {% block extrahead %}
> {% kolibri_imports %}
> {% endblock %}
>
> but I get the following error:
>
> Invalid block tag: 'kolibri_imports', expected 'endblock' or 'endblock
> extrahead'
>
> So; How can I call a defined templatetag inside my {% block extrahead
> %}-block? I've tried
>
> {% block extrahead %}
> {{kolibri_imports }}
>
> But that didn't produce anything.
>
> This is probably simple, but ... thanks for you input.
>
> --
> Mvh/Best regards,
> Thomas Weholt
> http://www.weholt.org
>
> --
> 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 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

Are you loading the tem

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Strip_tags and non english char issue

2011-06-26 Thread Ian Clelland
On Fri, Jun 24, 2011 at 5:21 PM, ydjango  wrote:

> Just checking if anyone has any pointers?
> We are using Django 1.1.4
>
> On Jun 15, 2:03 pm, ydjango  wrote:
> > I have rich text (in utf8) which I want to show in standard browser
> > tooltip.
> >
> > I strip html tags using strip_tags as they show as html tags in
> > tooltip.
> >
> > Issue is that it seems strip_tags is stripping or converting certain
> > turkish characters like ü   into weird special chars?
> >
> > I am unable to use django template's safe tag as data goes from django
> > view to xml to javascript.
> >
> > We are using UTF8 encoding in DB.
> >
> > Any ideas on how to solve?
>
>
It's very hard to say what might be going on here -- the strip_tags filter
is very simple, and is mostly just a regular expression applied to your
input. A large number of other people, I am sure, are using the tag without
noticing any such problem.

The one spot in the code that I can see that might cause problems is
django.utils.encoding.force_unicode -- it's possible that you are passing
something unexpected to that, and it is performing a conversion which
produces the characters you are seeing.

If you want to troubleshoot this, I would suggest the following:

1. Can you confirm that the data is really in the database in UTF8?

2. What do you get when you query the database from Django? At a minimum, I
would run a Django shell, import the models, and get a problematic instance
out of the database for printing. If you print the fields ("print
repr(my_instance.field_name)"), you should be able to see a proper unicode
object, something like u"This is the text with the ü")

>>> from my_app.models import MyModel
>>> my_instance = MyModel.objects.get(id=1234)
>>> print repr(my_instance.field_name)

3. What happens when you pass that string to force_unicode?

>>> from django.utils.encoding import force_unicode
>>> print repr(force_unicode(my_instance.field_name))

4. What are you actually getting as HTML output? Django should be outputting
unicode, so you will have to ensure that your web server is providing an
appropriate Content-Type header, or that you have a  tag in the html
header that specifies unicode. If those aren't there, then your browser will
have to guess the document encoding, and might be guessing wrong.

Hopefully that should get you enough visibility on the problem to see what
is happening. If none of that provides any clarity, then try posting those
answers here, and someone might be able to tell what's going on.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Inconsistent keyword filtering on FK

2011-06-23 Thread Ian Clelland
On Thu, Jun 23, 2011 at 2:21 PM, Cal Leeming [Simplicity Media Ltd] <
cal.leem...@simplicitymedialtd.co.uk> wrote:

> The problem:
>>
>> Utility.objects.filter(person=1144) # works fine
>> Payee.objects.filter(person=26) # gives us FieldError: Cannot resolve
>> keyword 'person' into field
>>
>
> Is this what you need??
>
> Payee.objects.filter(
> person = Person(id=26)
> )
>
> or.. Payee.objects.filter(
> person__id = 26
> ) - but this would be slightly more performance hitting i think.
>

or just

Payee.objects.filter(person_id=26)

person__id is a field lookup on the person model, so (in theory) Django will
contruct the SQL join, and test the person.id column. person_id is a column
in the payee table, and Django will construct SQL which compares against
that.

I don't know if there's any practical difference in performance -- I would
hope that any decent SQL query optimizer should be able to change

select payee.* from payee join person on (payee.person_id = person.id) where
person.id = 26

into

select payee.* from payee where person_id = 26


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-21 Thread Ian Clelland
On Tue, Jun 21, 2011 at 7:30 AM, Nan  wrote:

>
>
> > Your view function may indeed be too complex to test properly, and it
> sounds
> > like it is too tightly coupled with with the API call -- there is no way
> to
> > call the view without having it call the actual 3rd-party API as imported
> at
> > the top of the file.
>
> I'd be a little confused as to how to factor that out.  I mean, in the
> actual app that call is refactored behind a function that wraps the
> third-party API, and I could theoretically monkey-patch something over
> that function call for unit testing.  But the view still has to return
> an HttpResponse, and a blank one.
>

You're right, the view does need to return an HttpResponse; there's nothing
you can do about that. My point about tight coupling was that your view has
also been made responsible for instantiating the API wrapper that it thinks
it needs, and there's no way to tell it not to. In other frameworks, I would
immediately suggest using dependency injection -- the view depends on an API
wrapper instance, so it shouldn't be creating that instance; that should be
provided to it:

def my_view(request, api):
...
result = api.call(msg)

because then you could call my_view(request, theAPI()) in most
circumstances, but my_view(request, fake_api) in test code. Unfortunately,
the view is almost always called directly by Django, and you don't have much
control over its parameters.


> > The other way is to make your view function as simple as possible --
> simple
> > enough that it is obviously correct, without any unit tests. Take
> > *everything* that can affect the message which is passed to the API, and
> > abstract that into another function that the view can call. Then test
> *that*
> > function as a unit.
>
> Yes, it is very complex: it has to assess about 30 different potential
> states via nested conditionals.  It's actually broken down into a
> number of sub-functions that each deal with a few sub-states; and
> while refactoring might be a good idea, I wouldn't want to even
> attempt that before having some good unit tests in place!
>
> I think what you're suggesting (correct me if I'm wrong) is to have
> the top-level view function be the only place the API is called, and
> to use only a single call; every other sub-function that reaches an
> exit state should instead return a string containing the message to
> send?
>

That's what I was suggesting; that way the view becomes simple enough that
anyone looking at it can be assured of its correctness, without a host of
unit tests. Those tests can be applied to the functions that actually
construct the messages. But, see below -- I didn't realise that this effort
was to aid in refactoring the code.


>
> Thinking aloud, my concern then becomes that some of the sub-functions
> must actually make multiple API calls.  So we'd have to be returning
> tuples or something instead.
>
> > If theAPI is a class, then give it methods like setTestMode() and
> > resetTestMode(), and use them in your setUp and tearDown methods. Then,
> if
> > test mode is enabled, don't actually make the third party call, just
> store
> > the passed-in message in a module-level or class-level list and return
> > success. After your view returns, check the list to see that the message
> was
> > correct.
>
> Oh!  Thank you!  I didn't understand before how a mock API might make
> that possible -- it makes a lot more sense now.  That soudns like the
> perfect way to do it.
>
> At least until we've got enough tests to make sure the refactoring is
> correct, I need to be able to create the tests without touching the
> actual view logic, so testing what the API receives makes the most
> sense to me.
>

If this is all for a refactoring, then you're probably on the right track
there -- instrument the existing object for testing, rather than
restructuring the view first. Get the code into a state where you can trust
it, and then you can start restructuring it to make it more easily testable
in the future.

Good luck! :)


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Possible bug in form validation

2011-06-20 Thread Ian Clelland
On Mon, Jun 20, 2011 at 1:49 PM, Shawn Milochik  wrote:

> I know that, whenever someone finds a "bug" in Django they're usually doing
> something incorrectly. Hopefully someone will point out what I need to do to
> make this work.
>

I don't know if it's considered 'correct' or not, but the max_value
constructor parameter is only used at instantiation time, to add a validator
to the field.

You can easily add the validator manually in your own constructor if you
need to. You may also want to set the max_value attribute, if you use it
elsewhere, but it is not used internally by the form machinery.


>
> However, this is looking like a legitimate bug to me.
>
> http://dpaste.com/hold/556603/
>
>
I've updated with a working example, as http://dpaste.com/hold/556805/

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-20 Thread Ian Clelland
On Mon, Jun 20, 2011 at 4:25 PM, Nan  wrote:

>
> Hm, I'm not worried about receiving a valid response from the third-
> party API, just about testing the value of the "msg" parameter that's
> passed into it.  I need to test the msg parameter because it is in
> turn essentially a proxy for which state was reached in my_view.
>
> my_view is actually a great deal more complex than in the example, and
> is indeed broken into many smaller function calls.  I need to unit
> test to make sure that the logic is correct -- and since all those
> function calls return empty HttpResponse objects, I can't use their
> return values to test the correctness of their logic.
>

Your view function may indeed be too complex to test properly, and it sounds
like it is too tightly coupled with with the API call -- there is no way to
call the view without having it call the actual 3rd-party API as imported at
the top of the file.

There are a couple of ways out of this -- one is to use mocks, as suggested
before. Coupled with the dependency injection pattern, you would normally do
something to have the testing framework pass the mock API to the view, and
then you would query the mock at the end of the test to see what was passed
to it. Since Django's test framework is based around end-to-end testing
(making requests through TestCase.client and examining the response
returned,) this can be difficult to achieve.

The other way is to make your view function as simple as possible -- simple
enough that it is obviously correct, without any unit tests. Take
*everything* that can affect the message which is passed to the API, and
abstract that into another function that the view can call. Then test *that*
function as a unit.


>
> Just brainstorming here, could there be a way around this by placing a
> logging call of some sort in theAPI.call() that would only be executed
> during unit testing, and then to test the contents of the log?
>

This sounds like turning your API wrapper into a mock object at test time --
it might be the easiest way to do it, if you go the mock route.

If theAPI is a class, then give it methods like setTestMode() and
resetTestMode(), and use them in your setUp and tearDown methods. Then, if
test mode is enabled, don't actually make the third party call, just store
the passed-in message in a module-level or class-level list and return
success. After your view returns, check the list to see that the message was
correct.

Depending on the tests you have, you may want to have a way to tell the API
to return success or various kinds of failure. Most mocking frameworks have
ways of telling the mock objects what to return before making the method
calls.

At some point, though, I would start to become wary of putting too much
testing code in the real classes. (I'm sure there's an unpleasant name for
that kind of pattern)


>
>
> On Jun 20, 6:20 pm, DrBloodmoney  wrote:
> > On Mon, Jun 20, 2011 at 3:52 PM, Nan  wrote:
> > > I'm not testing the third-party service.  I need to test *what I send
> > > to them*.  I.e. that the output of my_view is correct.  The trouble is
> > > that neither my_view nor the API call actually returns the output that
> > > I need to check.
> >
> > > Does that make sense?
> >
> > Mock is one good solution. Here's what I've done in the past
> > (basically half-assed mock):
> >
> > 1. Have representative data sets that are good for the service (eg.
> > whatever you send to them, and whatever they send you in return).
> > 2. Monkey patch the call:
> >
> > def hackety_patch():
> > from StringIO import StringIO
> > data = StringIO(testdata_response_from_API)
> > data.seek(0)
> > return data.read()
> >
> > # in TestCase subclass
> > def setUp(self):
> > third_party.api.urllib2.urlopen = hackety_patch
> >
> > def tearDown(self):
> > third_party.api.urllib2.urlopen = urllib2.urlopen
> >
> > 3. Break up your API calling code into more testable units to truly
> > isolate your independent code from the API calling code. It'll be much
> > easier to catch problems in the API integration code.
>
> --
> 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
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: storing django object into javascript variable/array

2011-06-15 Thread Ian Clelland
On Wed, Jun 15, 2011 at 7:27 AM, jay K.  wrote:

> Hello,
>
> I've posted my question before, but I believe I didn't provide enough
> detail. I intend to present my issue again, this time with more
> detail.
>
> Let me tell you that I am not a django developer, so I have very
> limited exposure to django. I just know html, css, javascript, jquery,
> php (also java and c++, so I'm familiar with object-oriented
> programming).


...


>
> Now, I manage to see the output of the javascript written above
> through Firefox's "View - Page Source" and it comes up like this
>
> //BEGINNING
> var city_schools = ["EC","St. Giles Central","St. Giles Highgate"];
>
> var city_latitudes = ["58","88","25"];
>
> var city_longtitudes = ["7","99","100"];
>
> //END
>
>
> I have a separate javascript file where I add the code for the google
> map. What I want to do is to be able to access each of the
> city_schools, city_latitudes, and city_longitudes and use its data to
> I can mark the schools inside a google map. It would be ideal if I
> could retrieve the info as if it was a js array, but any method that
> works is more than welcome
>

What you have is very clearly a JavaScript array, as you asked for the first
time you posed this question. In fact, by copying the code, you have
produced three JavaScript arrays.

What you haven't done, in this newest version of your question, is show
exactly what it is you want. We now have a rough idea of what your models
look like, but no idea at all why the JavaScript output you have pasted is
insufficient.

You say that you know JavaScript, so what you're going to have to do is come
up with a sample of what you'd *like* to see as the template output, and
hopefully we can help you with the Django template code to produce that
output.

[Also, it really doesn't help to be posting and reposting the same question,
just hours apart -- it just looks very impatient]

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Could not decode to UTF-8 column 'cpostal'

2011-06-13 Thread Ian Clelland
On Sun, Jun 12, 2011 at 11:27 PM, Cal Leeming [Simplicity Media Ltd] <
cal.leem...@simplicitymedialtd.co.uk> wrote:

> I could be wrong, but I'm fairly sure that \xc3\xa3 is a 4 byte unicode
> sequence (which is essentially UTF-16).


No, it's a two-byte sequence -- the UTF-8 encoding of code point
U+00E3, 'LATIN SMALL LETTER A WITH TILDE'.

The original mysql data is probably the latin-1 byte string
'...Famalic\xe3o...'; str.decode('iso-8859-1') converts that into a unicode
string with the U+00E3 code point, and then unicode.encode('utf-8') is
representing that as \xc3\ca3. All correct, up to this point.

It looks like, after this decoding has occurred, and everything is stored,
either the sqlite adapter is returning the wrong data type when retrieving
data from the database, or admin is presenting something unexpected back to
sqlite when saving.

A couple of questions to the original poster might clarify a bit --

1. When do you get this error in admin? When looking at an object list page?
Or looking at an object detail page? Or only when saving objects?

2. Was your custom text_factory used only when you were porting the data
from mysql to sqlite? Or is it still present in your running application?
(And if so, where do you register it?)

3. Are you sure that the data is being stored and retrieved from the
database correctly? What output do you get from the python shell to confirm
that? (It's easy to retrieve wrong data that looks "right enough" when
printed to a terminal). If I was pulling correct data from the database, I
would expect to see something like this:

> from myapp.models import MyModel
> object_from_database = MyModel.objects.get(id=123)
> object_from_database.field_name   # not using "print" here
u'4760 Vila Nova de Famalic\xe3o'

Anything else -- missing the "u", or showing \xc3\xa3 instead of \xe3 here,
would suggest that something is wrong in the database (either stored
incorrectly, or being mis-translated somewhere on retrieval)

4. If you can get the right data out of the database in the python shell,
then can you save it from there as well? If everything above works, then try
doing this:

> object_from_database.save()

and see if you get the same error. If so, posting a traceback from that
might help pinpoint the problem.



-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: forms messing up css, help?

2011-06-11 Thread Ian Clelland
I have no idea what you mean by "stop working" -- without knowing what the
code looked like before, I don't know how it worked before. The usual rule
is that if something worked before, and doesn't work now, then the problem
is in something that you did in between.

Now if this is a new view, and has never worked at all, then that's
different.

At a first glance, you are using "render_to_response" in your view. This
method creates a Context object out of the dictionary that you pass it (in
your case, {'form': form} ).

A Context object doesn't know anything about the request, so {{ request.path
}} won't work in the template. It also doesn't have any ContextProcessors
applied, so you won't have access to context variables like {{ STATIC_URL
}}. The *only* variable that will be available in your template is {{ form
}}, because you passed it in.

What you want is a RequestContext object, rather than a Context object. You
can get one in your template, by adding one parameter to render_to_response:

from django.template import RequestContext
...
def contact(request):
...
render_to_reponse(
'/var/djcode/oneadmin/templates/oneadmissions/contact.html',
{'form': form},
context_instance=RequestContext(request)
)

That should give you a functioning template.

Ian

On Fri, Jun 10, 2011 at 9:27 PM, raj  wrote:

> I also noticed one more thing, in general, all html functions stopped
> working with render_to_response i think. Like i have a function that
> gets the current path ({% request.path == ".." %}). That also isn't
> working. And even when I hard-code it, it doesn't make a difference.
> any suggestions?
>
> On Jun 11, 12:17 am, raj  wrote:
> > Another thing i just noticed, When i view the source of my contact
> > form, all the css/javascript includes are missing part of the path
> > where i placed a {{ STATIC_URL }} tag. Why isn't this tag being
> > rendered? Thank you.
> >
> > On Jun 11, 12:14 am, raj  wrote:
> >
> >
> >
> >
> >
> >
> >
> > > Hey guys, Whenever i try and add a contact form (from the django book)
> > > into my current website, all my css/javascripts stop working. What is
> > > the issue? Here are my codes:
> >
> > > #views.py
> >
> > > def contact(request):
> > > if request.method == 'POST':
> > > form = ContactForm(request.POST)
> > > if form.is_valid():
> > > cd = form.cleaned_data
> > > send_mail(
> > > cd['subject'],
> > > cd['message'],
> > > cd.get('email', 'nore...@example.com'),
> > > ['siteow...@example.com'],
> > > )
> > > return HttpResponseRedirect('/contact/thanks/')
> > > else:
> > > form = ContactForm()
> > > return render_to_response('/var/djcode/oneadmin/templates/
> > > oneadmissions/contact.html', {'form': form})
> >
> > > #forms.py
> >
> > > from django import forms
> >
> > > class ContactForm(forms.Form):
> > > subject = forms.CharField()
> > > email = forms.EmailField()
> > > message = forms.CharField()
> > > name = forms.CharField()
> >
> > > #urls.py
> > > urlpatterns = patterns('',
> > >     ...
> > >  (r'^contact-form/', views.contact),
> > > ...
> > >  )
> >
> > > I have my static folder and everything created properly, its working
> > > perfectly fine until i input the chapter on forms. Help please!
>
> --
> 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
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: storing django object into javascript array

2011-06-10 Thread Ian Clelland
On Fri, Jun 10, 2011 at 7:48 AM, jay K.  wrote:

>
> Hello,
>
> I am not a django developer, but I have a background on html, css,
> javascript, jquery and php.
>
> I was wondering if you can help me with a question regarding django,
> since I'm working on a website built on django (which was not started
> by me)
>
> I want to store a django object into a javascript array. So far I have
> this code:
>
> In my template file:
>
> 
>
> var map_schools = {{ city.school_set.all }};
>
> 
>
> Unfortunately the django object is not stored as desired, but instead
> it gets stored like the following:
>
> var map_schools = [<School: Oxford, Eckersley>]
>
>
[] is the printable representation of your query
set (what you get when you call city.school_set.all()) -- what you need to
do is build up a JavaScript literal that you can insert into the code. There
are two fairly simple ways of doing this:

1. Use a loop in the template:

var map_schools = [{% for school in city.school_set.all %}"{{
school|escapejs }}"{% if not forloop.last %},{% endif %}{% endfor %}];

You'll notice a couple of things there:
  - there is a "for" loop there, to iterate over all of the schools in the
result set
  - the quotes are present in the template, to make sure that the school
names are strings in the JavaScript
  - there is a test after every string to see if a "," is needed as a
separator (some javascript implementations are not very forgiving if you put
a comma after the last element)
  - Every school name is passed through the "escapejs" filter, to avoid
breaking out of the string.

2. Construct a JSON string in python:

In your view, do something like this:

from django.utils.simplejson import dumps
...
school_list = dumps([school.name for school in city.school_set.all()])

and then add school_list to the context variables that are passed to the
template. Then in the template, you can just use {{ school_list }}, and it
will be a properly formatted JavaScript array.



-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: 'ValuesListQuerySet' object has no attribute 'META'

2011-06-10 Thread Ian Clelland
On Fri, Jun 10, 2011 at 5:55 AM, javatina  wrote:

>
> = in views.py: ===
> see formatted http://dpaste.com/hold/552703/
>
> same as:
>
> def test(request, slug=None):
>slugs = Concept.objects.filter(status__slug = 'active').order_by('-
> published_on').values_list('slug', flat=True)
>try:
>concept = Concept.objects.get(slug = slug, status__slug =
> 'active')
>except Page.DoesNotExist:
>raise Http404
>
>slugs_list = list(slugs)  # ==> problem line
>
>
>

> =  traceback =
> http://dpaste.com/552702/
>

 According to your traceback, when you call list(slugs), on line 446, it is
not using the python list() built-in, but calling what appears to be a list
function that you have defined earlier (around line 400)

My initial guess would be that you have something like this above the code
you have pasted:

def list(request):
...
context_instance=RequestContext(request)
...

And that call is throwing an exception, because you are passing a QuerySet
into RequestContext(), which is expecting an HttpRequest, and its
accompanying META attribute.

Check to see if that's the case, and rename your list() view if it is.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: 'ValuesListQuerySet' object has no attribute 'META'

2011-06-09 Thread Ian Clelland
On Thu, Jun 9, 2011 at 11:00 AM, javatina  wrote:

> I need a list of all IDs for model records. So, I do this
> concept_ids = Concept.objects.values_list('concept_id', flat=True)
>
> concept_ids is a ValuesListQuerySet - I got it. According to docs
> since ValuesListQuerySet is a subclass of QuerySet I can do
> list(concept_ids) - see
>
> https://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated
>
> However, I am getting on this line
> 'ValuesListQuerySet' object has no attribute 'META' error.
>
> For the sake of experimentation, if I try
> concept_ids = list(Concept.objects.all())
>
> I am getting 'QuerySet' object has no attribute 'META'. But this is
> like in docs (see link above):
> entry_list = list(Entry.objects.all())
>
> What am I doing wrong?
>


What are you doing with the list once you generate it? Are you just running
that single line of code, for instance, in a Python shell, or is this error
generated in a view?

"META", in all caps like that, is only used in Django as an attribute of an
HttpRequest object. The string "META" doesn't even occur in the db package,
so I can't imagine how simply wrapping a QuerySet in a list() call could
trigger an exception like that.

Can you post the rest of the code around this, or at least more of a
traceback, unless that is really all that there is? And if it is, then I'd
really like to take a look at your model definition.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Trouble with simple aggregation

2011-06-08 Thread Ian Clelland
On Wed, Jun 8, 2011 at 10:11 AM, Thomas Weholt wrote:

> Say I got a model like so:
>
> class Article(models.Model):
>title = models.CharField(max_length=100)
>text = models.TextField()
>category = models.CharField(max_length=20)
>author = models.CharField(max_length=50)
>
> Article.objects.create(title="Foo", text="Story about foo",
> category="adventure", author="jane")
> Article.objects.create(title="Bar", text="Story about bar",
> category="adventure", author="joe")
> Article.objects.create(title="Cheese", text="Story about cheese",
> category="adventure", author="joe")
> Article.objects.create(title="Perl", text="Story about perl",
> category="horror", author="jane")
> Article.objects.create(title="Java", text="Story about java",
> category="horror", author="joe")
> Article.objects.create(title="Pizza", text="Story about pizza",
> category="cooking", author="joe")
>
> I've tried to use aggregation to find how many articles written by joe
> there are of each category, but so far I'm not getting anywhere.
>
> Desired output:
>
> [
>{'category': 'adventure', 'count': 2},
>{'category': 'horror', 'count': 1},
>{'category': 'cooking', 'count': 1}
> ]
>
> I just cant get my head wrapped around the orm aggregation, in this is
> easy using raw SQL, but I don't want to.
>

Is this not something like:

Article.objects.values('category').annotate(count=models.Count('id'))

? The idea being that you group the objects by category, and then count the
number of distinct ids within each category.

The docs mention that the default ordering can get in the way of this
sometimes, so you probably want to clear it first, like this:

Article.objects.values('category').annotate(count=models.Count('id')).order_by()

That should get you all of the data for your desired output -- it might not
be an actual list of actual dicts, but it should be structured in the same
way.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: SystemError from django.conf.settings

2011-05-30 Thread Ian Clelland
On Sat, May 28, 2011 at 10:50 PM, Cameron wrote:

> So I have this stack trace on my production server. I can't reproduce
> it locally and it doesn't occur with an older version of the same site
> deployed on the same server.
>
> Traceback (most recent call last):
>  File "./dependencies/django/core/handlers/wsgi.py", line 222, in
> __call__
>from django.conf import settings
> SystemError: ../Objects/tupleobject.c:118: bad argument to internal
> function
>


> 1. Anyone seen this before? The only other reference that I can find
> to that line of python is here (http://bugs.debian.org/cgi-bin/
> bugreport.cgi?bug=581626)
>

I've never seen this before. Looking at the Python source (you mentioned
that you're running 2.5.2 from Debian lenny,) this looks to me like it has
to be an error in a C module somewhere -- probably a third-party module, but
it's possible it's in the Python core somewhere.

The line itself is a sanity check in PyTuple_SetItem, which shouldn't even
be available to Python code (tuples are supposed to be immutable, right?) It
would only get triggered if it got called somehow with an argument that
wasn't actually a tuple, or with a tuple for which another reference existed
somewhere (besides in the initializing code).


>
> 2. Any tips on how I can find out what has changed to cause it? Aside
> from rolling back through weeks of revisions to find what triggered
> it.
>

If it's happening on settings import, then try importing settings manually
from a python shell. You may see more of a stacktrace that way. If you still
get the error, but can't pinpoint the failing line, then try running it
through the debugger, and step from line to line until you see it. If you're
lucky, there will be call to a function in an external module that triggers
it, and you'll be able to narrow the possibilities down to that one module.

Failing that, a binary search through weeks or even months of revisions
should only take O(lg n) time -- a small consolation, but searching weeks of
development is only a couple of iterations more than searching a few days.


> 3. I am about to try upgrading python to a newer version, is that
> likely to make any difference? I have already tried 2 different
> versions of uwsgi (0.9.6.8 and 0.9.7.2), but I don't want to mess
> around with the production environment too much, or risk breaking the
> live sites.
>

If the error is in one of the python core modules, then it may have been
fixed recently; but I haven't seen any reports of failures in tupleobject.c
other than the Trac bug that you turned up. See if there are any other
compiled modules in the system that you can update first.


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: json serialization question

2011-05-27 Thread Ian Clelland
On Tue, May 24, 2011 at 8:36 AM, Sells, Fred
wrote:

> My code looks like this
>
> records = models.Residents.objects.extra( where=[], params=[...])
> data = serializers.serialize('json', records, ensure_ascii=False,
> fields=('fname','lname', 'pt'))
> return HttpResponse(data)
>
> After experimenting the "ensure_ascii=False" seems to get rid of the
> Unicode prefix which is not used in my work.
>
> which returns
> [
> {"pk": "7", "model": "app.residents", "fields": {"lname": "Mouse ",
> "pt": "0", "fname": "Minnie "}},
> ...]
>
> I was surprised to see the subnode "fields" in the output.  Perhaps I'm
> just old school having does basic cgi with json and pretty much forced
> the format.
>
> 1. However is the above the "best practice" or is there an option to
> strip the meta data.
>

I don't think that anyone would condone this as a 'best practice' -- the
Django serializers are meant to dump django objects, say into session data,
or into database fixtures, and they are really designed to be read by the
deserializers when the object needs to be reconstructed.

If you are passing data from Django to a browser's JavaScript thread using
JSON, then you probably want to either

1. Use an API framework, such as Piston (google: django-piston) or TastyPie
(google: django-tastypie) to handle serialization of outgoing data. These
are very useful if you expect to be receiving data from the browser in the
same format for creating or updating objects, but they can be a lot of
overhead for small applications, so you may want to

2. Write your own serialization. It's quite simple, and Django does an
excellent job of packaging the simplejson library (deferring to the system
installed version, if it's available, and newer than Django's). All you need
to do is something like this:

from django.utils import simplejson as json
...
records = models.Residents.objects.extra( where=[], params=[...])
data = json.dumps(records.values('fname','lname','pt'))
return HttpResponse(data, mimetype='application/json')

records.values(...) should return just the dictionary that you want to use.
json.dumps(...) will convert that into a JSON string, which you can then
return as an HttpResponse.


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Selecting distinct months from a QuerySet

2011-05-18 Thread Ian Turner
Hi,

I would like to get a distinct list of months from a datetime field on an 
already defined QuerySet.

SQL that I would use manually to get distinct from all records on the model.
SELECT DISTINCT MONTH(`some_datetime_field`) as `month` FROM `some_model` 
ORDER BY `month`

I don't need the year so .dates() gives me too much information to loop 
over.  Any ideas?

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Email app is breaking long lines, any fix?

2011-05-17 Thread Ian Clelland
On Tue, May 17, 2011 at 1:02 PM, John Crawford wrote:

> Actually, upon looking more at the output, it has *both* "utf-8" and
> "us-ascii" as the charset.


Actually, it doesn't. It only has utf-8. The first nine lines of your pasted
output are the actual email headers. Following the blank line is the email
body, which begins with three lines that *look* like headers, but are
actually just part of the message, and any email client would just render
them as text at the top of the message.

(In addition to the blank line, this is alse evidenced by the fact that the
'=' in 'charset='us-ascii'" was escaped as '=3D', as is normal for
quoted-printable-encoded text)


> I'm not sure if this is the result of code
> changes I've made, or I just missed it the first time around - but my
> Django email output now looks like this:
>
> -- MESSAGE FOLLOWS --
> Content-Type: text/plain; charset="utf-8"
> MIME-Version: 1.0
> Content-Transfer-Encoding: quoted-printable
> Subject: some_subject
> From: m...@test.com
> To: m...@test.com
> Date: Tue, 17 May 2011 19:58:16 -
> Message-ID: <20110517195816.16624.1004@CRAY>
> X-Peer: 127.0.0.1
>
> Content-Type: text/us-ascii; charset=3D"us-ascii"
> MIME-Version: 1.0
> Content-Transfer-Encoding: 7bit
>
> this is a test of a really long line that has more words that could
> possibl=
> y fit in a single column of text.
>  END MESSAGE 
>
> So although I'm creating a MIMEText object with a plain, "us-ascii"
> string - somewhere, Django is sending a charset of "utf-8". At least
> if I read this correctly.
>
> So does anyone know how to tell Django to *not* send "utf-8"? Thanks.
>

What are you *actually* doing to send this email? It sounds like you are
creating some kind of object and passing that as the body to send_mail,
while send_mail is expecting text, and is just coercing your object into a
string and using that as the message body.

It is definitely possible to tell Django not to use UTF-8 encoding, but you
won't be able to use the send_mail shortcut to do it. You will have to use
an EmailMessage object directly[1]. You should be able to instantiate an
EmailMessage, set the headers yourself, and call send() on it.

(Also, 'text/us-ascii' is not a registered MIME type; you probably want to
say something like 'text/plain; charset=us-ascii')


[1]
http://docs.djangoproject.com/en/1.3/topics/email/#the-emailmessage-class


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Encrpting urls to hide PKs

2011-05-12 Thread Ian Clelland
On Thu, May 12, 2011 at 12:29 AM, Wesley Childs wrote:

> Why cant you do something like this to avoid exposing data if people are
> guessing primary keys
>
> if request.user == Users.objects.get(id=pk-url):
> Show data
> Else:
> raise 404 or redirect to home page
>
> The above requires a logged in a user but you get the idea of not allowing
> people to start guessing to expose data.
>

You can't do this, in this case, *because* it requires a logged-in user.
Specifically, the OP is looking for a way to authenticate a user based on
their knowledge of a 'secret' URL, but if the URLs are predictable, then
discovering the secrets is trivial. Your solution is fine once the user has
been logged in, although some people would say that it can still give away
too much information*

Honestly, I can think of exactly two ways for the original poster to achieve
his goal (and I've deployed systems using each of these):

1. Sign** the ID with a secret known only to the web server. Put the ID and
the signature in the URL somewhere, and, when the user hits the view, sign
the ID again, and verify that the signatures match. This doesn't hide the ID
at all, but it ensures that nobody can forge a url with a different ID than
the server gave them.

2. Generate a unique token for each record, randomly. Use a UUID, they're
great for that. Then use the token in the URL, and look for the token in the
database when the user comes back to the confirmation view. If your tokens
are actually random, and large enough (say, 64 bits), then anybody trying to
guess them will be wasting their time.


-- 
Regards,
Ian Clelland



* By looking at the database IDs, people can gauge how heavily the system is
being used, or if they see a key for someone else's record, they can
estimate when that record was created, by comparing it to their own data.

** And by sign, I mean HMAC.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Decimal * Float problem

2011-05-11 Thread Ian Clelland
On Wed, May 11, 2011 at 1:14 AM, Colin Corbett wrote:

> Thanks!  Solved:
>
> In models.py:
>
> class OurProducts(models.Model):
>  code = models.CharField(max_length=60)
>  name = models.CharField(max_length=80)
>  price = models.DecimalField (max_digits=8, decimal_places=2)
>
>  def combined_price(self):
>from decimal import Decimal
>return round(self.price * Decimal(0.65),2)
>

For the sake of anyone searching the group for this issue in the future,
that last method should be:


>  def combined_price(self):

>from decimal import Decimal
   return (self.price * Decimal('0.65')).quantize(Decimal('0.01'))

Python will sensibly throw an exception if you try to create a Decimal from
a float directly, so Decimal(0.65) will not work. Also, the round() function
will turn your carefully calculated decimal value *back* into a float; you
should use .quantize() instead.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: 500 message with POST

2011-05-02 Thread Ian Clelland
On Mon, May 2, 2011 at 7:45 AM, Robert Cross  wrote:

> I'm a Django newbie and I'm trying to do some minor tests with POST methods
> (I need an automated/scriptable way to get data into my Django database).
> Using the following code
>
> @csrf_exempt
> def posttest(request):
> z=request.POST.get('data', 'no data')
> html="POST TestData supplied was \""
> html=html+z
> html=html+"\""
> return HttpResponse(html)
>
> When I run a test upload it fails:
>
> $ wget --post-data 'data=Something'
> http://localhost:8000/posttest?data=Command
> Line
> --2011-05-02 15:30:03--  http://localhost:8000/posttest?data=CommandLine
> Resolving localhost (localhost)... 127.0.0.1
> Connecting to localhost (localhost)|127.0.0.1|:8000... connected.
> HTTP request sent, awaiting response... 500 INTERNAL SERVER ERROR
> 2011-05-02 15:30:03 ERROR 500: INTERNAL SERVER ERROR.
>
> If I don't supply any post data then it appears to work (301 followed by
> 200 codes, but still gives the expected html).
>
> Any ideas what I'm doing wrong? (Get methods seem to work - but I'd prefer
> not to use them because they're not technically correct for a DB update
> function)
>
>
I'm not sure where the 500 error is coming from -- if you can get wget to
show you the HTTP response, then you should be able to see the actual error
and traceback in there (as long as you have DEBUG enabled, you should get
back a formatted HTML document with the error message in it)

If you can't get the error output, then try at least printing the html
variable before the view function returns. You'll at least know if if gets
that far, or if the error is happening somewhere else. Just watch the
console where your server is running, and you should see the output of any
print statements.

The fact that, on GET, you are getting a 301 first means that the URL that
you are providing is not the correct one for the resource. You probably have
"/posttest/" defined in your urls.py, but you are using wget to access
"/posttest" (no trailing slash). On a GET request, it is perfectly safe to
just issue a redirect to the correct URL, but it is not necessarily safe for
POST requests. I believe that Django will issue the redirect anyway, buy the
user agent is *not* supposed to just blindly post the data to the new URL
without some sort of user interaction.

To eliminate this as a possible error source, try putting the trailing "/"
on the URL in the command line:

$ wget --post-data 'data=Something'
http://localhost:8000/posttest/?data=CommandLine

Then you should get { 'data': 'CommandLine' } in request.GET, and { 'data':
'Something' } in request.POST.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Accessing ImageField temporary file to dynamically change upload_to storage path

2011-04-26 Thread Ian Turner
I'm in need of direction to access the temporary file that is stored
in memory or on disk from an ImageField/FileField so that I can read
it before it gets moved to its final location.

The topics I've found all deal with only modifying the storage path
based on other fields in a model.  My requirement is reading EXIF/IPTC/
XMP data to grab the Date created of a photo.

Providing a callable to "upload_to" gives an instance but the image
field doesn't have a file associated with it yet (working logically).
So how can I access the temporary memory or file to read it?

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: cx_Oracle error: ImproperlyConfigured

2011-04-24 Thread Ian
On Apr 23, 12:29 pm, kamal sharma  wrote:
> No it was .profile of mine. Now I have set the LD_LIBRARY_PATH in app.wsgi
> as mentioned below and when I print the os.environ in the beginning of
> views.py then it shows that newly added value.

It's clear that your LD_LIBRARY_PATH is fine at this point, since the
library must be loaded in order to get the ORA-01804 error.  The
problem, as Jirka and I have suggested, is that the rest of your
Oracle installation is still not visible to the process, which is
preventing the client from reading its data files.  Why this is the
case is unclear without knowing more details about your system.  Is
the Oracle directory readable by the WSGI user?  Is the WSGI process
running inside a chroot jail?

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: cx_Oracle error: ImproperlyConfigured

2011-04-22 Thread Ian
On Apr 21, 11:40 pm, kamal sharma  wrote:
> When i try the same code from python Shell then it is working fine.

Okay, so it does sound to me like it's your web server blocking access
to the entire ORACLE_HOME directory.

Is it running under a chroot jail?  If so, then you will need to copy
your entire Oracle client installation into the jail and use the
chrooted path for your ORACLE_HOME and LD_LIBRARY_PATH.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: cx_Oracle error: ImproperlyConfigured

2011-04-21 Thread Ian
On Apr 21, 11:03 am, kamal sharma  wrote:
> Error while trying to retrieve text for error ORA-01804
>
> Here is my code to fetch the data from database.
>
> def cases(request, dbname, prnum=None, message=''):
>
>     connection = cx_Oracle.Connection("%s/%s@%s" % ('foo', 'bar', 'xyz'))
>     cursor = cx_Oracle.Cursor(connection)
>     sql = "SELECT fielname FROM tablename where rownum < 10"
>     cursor.execute(sql)
>     names = [row[0] for row in cursor.fetchall()]
>     cursor.close()
>     connection.close()

First of all, why are you creating your own connection instead of
using the Django ORM?

Anyway, the proper way to create a cx_Oracle connection is with the
cx_Oracle.connect factory function, and the proper way to create a
cursor is with the connection.cursor() method.  See the cx_Oracle docs
and the DB-API docs for details.  However, I think there is something
more going on here.

ORA-01804:  failure to initialize timezone information
Cause:  The timezone information file was not properly read.
Action: Please contact Oracle Customer Support.

This and the fact that cx_Oracle wasn't able to look up the error code
itself suggest that there may be something wrong with your Oracle
client installation.  Or it may be that your webserver is also
blocking access to the files in the client directory.  What happens if
you try the same code from a Python shell?

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: cx_Oracle error: ImproperlyConfigured

2011-04-21 Thread Ian
On Apr 21, 9:39 am, kamal sharma  wrote:
> Here is the error I am getting now:
>
> cd /usr/local/lib
>
> /usr/local/lib> sudo ln
> /opt/app/oracle/products/11.2.0/lib/libclntsh.so.10.1
> ln: ./libclntsh.so.10.1 is on a different file system
>
> /usr/local/lib> cd /usr/lib/
> /usr/lib> sudo ln /opt/app/oracle/products/11.2.0/lib/libclntsh.so.10.1
> ln: ./libclntsh.so.10.1 is on a different file system

Right, it's not possible to create hard links across file systems.
Create a soft link instead using "ln -s" (soft links are usually
preferable anyway).

> Also set this in .cshrc file
>
> setenv LD_LIBRARY_PATH "$ORACLE_HOME/lib32:$ORACLE_HOME/lib"
> setenv LD_LIBRARY_PATH /usr/X11R6/lib:/usr/local/lib
>
> echo $LD_LIBRARY_PATH
> /usr/X11R6/lib:/usr/local/lib
> echo $ORACLE_HOME/
> /opt/app/oracle/products/11.2.0/

Is this in your .cshrc file or the WSGI user's .cshrc?  And are you
sure it's using csh and not bash?

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: compressing uploaded file

2011-04-20 Thread Ian Clelland
On Wed, Apr 20, 2011 at 1:02 AM, Daniel Gerzo  wrote:

> On 20.4.2011 2:22, Julio Ona wrote:
>
>> Hi Daniel,
>>
>> you should see:
>> http://docs.python.org/library/bz2.html#module-bz2
>>
>> <http://docs.python.org/library/bz2.html#module-bz2>or
>> http://docs.python.org/library/gzip.html#module-gzip
>>
>
> Hello Juliom, thanks for reply.
>
> I have of course seen both of these before I sent the mail, unfortunately I
> couldn't figure out how to use it on my InMemoryUploadedFile object.
>
>  But basically you should import the compress function from the library
>> and use it.
>>
>> <http://docs.python.org/library/gzip.html#module-gzip>from bz2 import
>>
>> compress
>>
>> [...]
>>
>>
>> def handle_uploaded_subtitles(self, files):
>>for file in files:
>>sub_file = SubtitleFile(file_name=file.name, etc)
>>bz_file = compress(file)
>>
>
> I wish it would be that easy :-)
>
> What you are proposing fails with Exception:
>
> bzfile = compress(file)
> argument 1 must be convertible to a buffer, not InMemoryUploadedFile
>
>
Well, an InMemoryUploadedFile isn't a real file, so I'm not surprised that
that doesn't work. You'll have to pull the data out of it, and compress
that.

Try something like this:

def handle_uploaded_subtitles(self, files):
   for uploaded_file in files:
   sub_file = SubtitleFile(file_name=file.name, etc)
   data = bz2.compress(uploaded_file.read())
   # Here I'm assuming that SubtitleFile.file is a real file object
   sub_file.file.write(data)
   sub_file.file.close()

If your files are large, then you can read them in lines, or in chunks, and
use a BZ2Compressor object to compress them one-at-a-time.

Further, I wasn't able to find a method in the mentioned libraries that
> would make this possible, or at least I didn't figure out how to pass an
> InMemoryUploadedFile to them to compress it.
>
> When I try to do this:
>
> file.write(zlib.compress(file.read()))


Don't do that -- I'm pretty sure that writing a file that you already have
open for reading will produce undefined results.

(Also, I'd try to stay away from using 'file' as a variable name -- it just
hides the built-in file type name, and makes it hard to tell what, say,
file.read refers to)


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Debugging a unittest

2011-04-20 Thread Ian Clelland
On Tue, Apr 19, 2011 at 3:44 PM, Thomas Weholt wrote:

> I'm wondering if anybody has a hint on how to debug a unittest, or any
> other piece of code in django, for that matter, using a debugger like
> winpdb?
> I'm trying to to a winpdb manage.py test photo, which runs my unittest
> for my photo app, but winpdb crashes. Are there alternatives? What is
> the best way to do this?


 I don't know about winpdb, but if it's compatible with pdb, then I just do
this:

class ExampleTestCase(TestCase):
def test_something(self):
# some test code
# ...
import pdb; pdb.set_trace()
# ...
# rest of the test code

Then run your tests normally, and the debugger will automatically be invoked
at the 'pdb.set_trace()' line.

To speed things up, you can run
./manage.py test app.ExampleTestCase.test_something

And only the one test that you specify will actually be run.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: how to call user-defined database functions through the Django query syntax?

2011-04-20 Thread Ian Clelland
On Wed, Apr 20, 2011 at 8:18 AM, Andrew Dalke  wrote:

> I'm using MySQL and sometimes SQLite as the backend database. Both
> databases let me add user-defined functions. I've made a set of UDFs
> specific to my problem domain, which is chemsitry.
>
> How do I call them from a database query? Currently I'm using a raw()
> call, which made for some rather ugly SQL construction.
>

It sounds like you could do this with a QuerySet.extra() call (
http://docs.djangoproject.com/en/1.3/ref/models/querysets/#extra)

I don't know how you would use those with Q objects, though.

>
> Ideally I would like something like
>
> q = (models.Q(title__icontains="test") &
>   models.Q(structure_smiles = smartsmatch(smarts="[C;!H0]"))
>
>  -or-
>
> q = (models.Q(title__icontains="test") &
>   models.Q(structure_smiles__smartsmatch = "[C;!H0]"))
>
>
> which would get mapped to
>
>title LIKE 'test' AND structure_id = structure.id AND
> oe_matches(structure.smiles, "[C;!H0]")
>
>
You could do something like:
myModel.objects.filter(title__icontains="test").extra(where='oe_matches(structure.smiles,
"[C;!H0]")')

You could encapsulate the extra() call in a function call that annotates a
QuerySet that you pass to it, but it's 'outside' of the ORM at that point.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unidirectional relations

2011-04-20 Thread Ian Clelland
On Tue, Apr 19, 2011 at 7:28 PM, Jacob Kaplan-Moss wrote:

> 2011/4/19 Juan Pablo Romero Méndez :
> > Is it possible to create unidirectional relations within django's orm?
> >
> > What I mean is a situation where a parent has a children_set of
> > references to children, but the children don't have any reference to
> > the father.
>
> See the documentation for ForeignKey.related_name:
>
> http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name
> .
> In particular, note the part about what `related_name="+"` does.
>

Jacob,
That sounds like it would create exactly the opposite situation from what is
wanted.

class Parent(models.Model):
pass
class Child(models.Model):
parent = models.ForeignKey(Parent, related_name='+')

would give a child a reference to their parent, without the parent having a
child_set attribute.

I think Mike has the right idea; using a separate 1:many table to avoid
explicit fields on the child model, but, of course, SQL being what it is, it
is still possible to construct a query that joins the tables and
reconstructs the link from child to parent.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Using composition in Django

2011-04-16 Thread Ian Clelland
On Sat, Apr 16, 2011 at 1:35 PM, Guevara  wrote:

> Hello!
> I have two class, Person and employee, i need make a composition for
> this (Prefer composition over inheritance):
>
> class Person(models.Model):
>name = models.CharField(max_length=50)
>date_inclusion = models.DateField()
># others fields
>
> class Employee(models.Model):
>person = models.OneToOneField(Person, primary_key=True)
>address = models.OneToOneField(Address, primary_key=True)
>
>
> The SQL generate is:
>
>
> BEGIN;
> CREATE TABLE "person_person" (
>"id" serial NOT NULL PRIMARY KEY,
>"name" varchar(50) NOT NULL,
>"date_inclusion" date NOT NULL,
> )
> ;
> CREATE TABLE "employee_employee" (
>"person_id" integer NOT NULL PRIMARY KEY,
>"address_id" integer NOT NULL PRIMARY KEY,
> )
> ;
>
>
> This is correct? Should generate the id of the employee?
>

I don't think it's correct -- a database table shouldn't have two distinct
primary keys. It's the "primary_key=True" part of your Employee model fields
that is doing this, and is also stopping an "id" field from being
automatically generated.

If you write Employee like this:

class Employee(models.Model):
   person = models.OneToOneField(Person)
   address = models.OneToOneField(Address)

Then it will generate SQL like this:

CREATE TABLE "employee_employee" (
   "id" serial NOT NULL PRIMARY KEY,
   "person_id" integer NOT NULL,
   "address_id" integer NOT NULL
)
;

which is probably closer to what you're expecting.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Nested admin command problem

2011-04-07 Thread Ian Clelland
On Thu, Apr 7, 2011 at 3:10 AM, Hamdy  wrote:
> Hi,
>
> I'm having a case in which I'm making an admin command that takes some
> options
> This's great and works just fine
> the problem appears when trying to call another command from within
> the first
>
> option_list = BaseCommand.option_list + (
>        make_option('--host',
>                             default='127.0.0.1'), )
>
>    def handle(self, *args, **options):
>        # change some settings
>        call_command('test', *args, **options)   # Here's the problem
>        #call_command('test', *args, **options) # This didn't help too
>
> the test command has no --host and thus we get an error that test
> command has no test option
> Any ideas how to overcome this ?

Can you just take 'host' out of the options dictionary?

def handle(self, *args, **options):
self.host = options.pop('host') # 'host' isn't in options anymore
   # do some more stuff
call_command('test', *args, **options)


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Using ifnotequal with a list object not working

2011-04-07 Thread Ian Clelland
On Thu, Apr 7, 2011 at 12:25 PM, aaron  wrote:
> Hi there,
> I'm trying to do something quite simple within my html using ifnotequal (dj
> 0.96). The code within my html is as follows:
>             {% ifnotequal {{the_types.0}} "Nothing dude" %}
>                 {{the_types.0}}
>             {% endifnotequal %}

Take out the {{ }} around the variable inside of the {% ifnotequal %}
tag. Those braces are just for inserting the value of the variable
into HTML content, not for referencing it inside of a template tag.

{% ifnotequal thetypes.0 "Nothing dude" %}
...
{% endifnotequal %}
should work.


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: select_related() changes type of DecimalField?

2011-04-04 Thread Ian
On Apr 4, 12:05 pm, Carsten Fuchs  wrote:
> Is this a bug in Django?
> If not, is there a better solution to the problem than using
> isinstance() in every place where I have to compare DecimalField values?
> (I'm still quite new to Python, and might be overlooking something
> obvious...)

Yes, this appears to be a bug.  If you would, please create a ticket
for it in the Django Trac so that we don't forget about it.

Thanks,
Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Seeking Django Counsel when adding a new model using South and a custom field for my ProtectedFileField subclass

2011-03-27 Thread Ian Clelland
On Sun, Mar 27, 2011 at 1:47 PM, Matteius  wrote:
> add_introspection_rules([], ["^student_portal\.fields
> \.ProtectedFileField"])
...
>  ! Cannot freeze field 'student_portal.assignment.provided_files'
>  ! (this field has class
> classcomm.student_portal.fields.ProtectedFileField)


Without looking too carefully at whether your introspection rules are
correct, the first thing that jumps out at me is that South sees the
field class as "classcomm.student_portal.fields.ProtectedFileField",
while you have registered an introspection rule for
"^student_portal\.fields\.ProtectedFileField".

The "^" at the beginning of your regex anchors the expression to the
start of the string, so it will only match if your class name begins
with "student_portal".

Try changing the regex in your add_introspection_rules call to either:

"student_portal\.fields\.ProtectedFileField" -- removing the "^" so
that it can match anywhere within the string, or

"^classcomm\.student_portal\.fields\.ProtectedFileField" -- preserving
the "^", but adding the "classcomm." that South sees as the start of
the full class name.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Repetition in urls.py

2011-03-24 Thread Ian Clelland
On Thu, Mar 24, 2011 at 12:40 PM, Ryan Osborn  wrote:
> I was just wondering if there was a simple way to condense this as
> with django 1.2 I could add all this in to a dictionary like:
>
> info_dict = {'model': Entry, 'date_field': 'created', 'paginate_by':
> 10}


Can you not set your info_dict just like that, and then rewrite it like this:

YearArchiveView.as_view(**info_dict),name='blog_archive_year'),
url(r'(?P\d{4})/(?P[a-z]{3})/$',


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



decorators and generic views

2011-03-24 Thread Ian Stokes-Rees
I think with the move to class-based Generic Views it is necessary to update 
this documentation:

Limiting access to generic views 

To limit access to a *generic 
view*<http://docs.djangoproject.com/en/dev/ref/generic-views/>, 
write a thin wrapper around the view, and point your URLconf to your wrapper 
instead of the generic view itself. For example:

from django.views.generic.date_based import object_detail
@login_requireddef limited_object_detail(*args, **kwargs):
return object_detail(*args, **kwargs)

I am trying to put an @login_required decorator around ListView.as_view(...) 
but not having any luck.  Advice on how properly map from urls.py to a 
function in the wrapped view would be appreciated.  My current best attempt 
is below

Cheers,

Ian

urls.py BEFORE:

from gridportal.wsmr.models import WSMRTask
from gridportal.wsmr.views  import list, create, view, edit, 
copy, delete, reset

urlpatterns = patterns('',
(r'tasks/?$' , ListView.as_view(model=WSMRTask)), # 
working, but no access control

urls.py AFTER:

from gridportal.wsmr.models import WSMRTask
from gridportal.wsmr.views  import list, create, view, edit, 
copy, delete, reset

urlpatterns = patterns('',
(r'tasks/?$' , list()), # not working

views.py AFTER:

@login_required()
def list(*args, **kwargs):
return ListView.as_view(model=WSMRTask)

I get the exception:

_wrapped_view() takes at least 1 argument (0 given)


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Configuring common site URL paths for use in templates

2011-03-23 Thread Ian Stokes-Rees
I have a bunch of regular site paths that I'd like to be able to refer to 
both in my Python code and in my  templates, e.g.

settings.py:
site_root = "/portal"
contact_url = site_root + "/contact"
sitemap_url = site_root + "/sitemap"
login_url = site_root + "/account/login"
logout_url = site_root + "/account/logout"
newspost_url = site_root + "/news/post"

and then make these accessible in some random template using somthing like 
the following:

404.html:
{% extends "base.html" %}
{% block content %}
Sorry, we couldn't find that page.

Maybe it has moved -- why not look in the 
Site Directory?

If it seems like an error, please contact 
us.
{% endblock %}

Can anyone suggest a good way of doing this?

TIA,

Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: DatabaseError: ORA-03127: no new operations allowed until the active operation ends

2011-03-22 Thread Ian
On Mar 22, 5:38 am, Paolo Corti  wrote:

> I have solved this by downgrading the cx_Oracle library from 5.1 to
> 5.0.1
> I am using Oracle 11.2
> Now works well both on Django 1.2.5 and 1.3 RC with Python 2.6
> best regards
> P

Thanks for letting us know.  I haven't yet tried cx_Oracle 5.1 myself,
so I suppose I'll have to install it and see if this reproduces.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How make CSRF middleware emit html4 rather than xhtml1.0 (closing tags issue) so will validate?

2011-03-14 Thread Ian Clelland
On Mon, Mar 14, 2011 at 10:57 AM, Chris Seberino  wrote:
> My Django app's html won't validate because CSRF middleware adds
> hidden
> tags like this...
>
>  name='csrfmiddlewaretoken' value='ebcf3d41f32a70a209e27ef7fdf06d72' />
>
> The only problem is the slash "/>" at the end.
>
> How make Django templates not automatically add hidden tags that won't
> validate?

You have access to a context variable called "csrf_token", which just
contains the actual token string. If you don't like the output of the

{% csrf_token %}

template tag, then just write it yourself in a template. The simplest
way would be to put, in your template, some code like this:





(Note the '{{', '}}' delimiters, rather than '{%', '%}')

A more complicated, but more reusable way to do it would be to write
your own template tag (it's really simple, you can use the CSRF-token
code in django/template/defaulttags.py as a starting point) which
would render whatever markup you need.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django+ oracle, working with apache(mod_python, wsgi) and in runserver, ora-03114 in fastcgi

2011-03-01 Thread Ian
On Mar 1, 10:26 am, Ian  wrote:
> It appears that the error is actually from the previous (working)
> request when Django subsequently tries to close the database
> connections and fails, and since the error goes uncaught, it kills the
> server.
>
> It's pretty weird that it would fail in this way.  What happens if you
> explicitly close the database connections at the end of your view?

You'll also need to disable your middleware to test this, in case some
middleware needs the connections active after the view returns.

Also, does this error appear at all in your Apache logs?  I wonder if
it was occurring there as well and just going unnoticed.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django+ oracle, working with apache(mod_python, wsgi) and in runserver, ora-03114 in fastcgi

2011-03-01 Thread Ian
On Mar 1, 4:23 am, lipt0n  wrote:
> Django 1.2.3
> python 2.6
> cx_oracle 5.0.4
> oracle 10 XE
>
> $ cat /var/log/nginx/localhost.error_log
> 2011/02/28 16:52:39 [error] 11159#0: *47 FastCGI sent in stderr:
> "Traceback (most recent call last):
>   File "/usr/lib/python2.6/site-packages/flup-1.0.3.dev_20110111-
> py2.6.egg/flup/server/fcgi_base.py", line 574, in run
>     protocolStatus, appStatus = self.server.handler(self)
>   File "/usr/lib/python2.6/site-packages/flup-1.0.3.dev_20110111-
> py2.6.egg/flup/server/fcgi_base.py", line 1159, in handler
>     result = self.application(environ, start_response)
>   File "/home/intranet/libs/django/core/handlers/wsgi.py", line 248,
> in __call__
>     signals.request_finished.send(sender=self.__class__)
>   File "/home/intranet/libs/django/dispatch/dispatcher.py", line 162,
> in send
>     response = receiver(signal=self, sender=sender, **named)
>   File "/home/intranet/libs/django/db/__init__.py", line 84, in
> close_connection
>     conn.close()
>   File "/home/intranet/libs/django/db/backends/__init__.py", line 70,
> in close
>     self.connection.close()
> OperationalError: ORA-03114: not connected to ORACLE" while reading
> response header from upstream, client: 192.168.1.105, server:
> localhost, request: "GET /accounts/menuleft/122/ HTTP/1.1", upstream:
> "fastcgi://127.0.0.1:9001", host: "192.168.1.50", referrer: "http://
> 192.168.1.50/accounts/menuleft/"
> 2011/02/28 16:54:46 [error] 11159#0: *56 connect() failed (111:
> Connection refused) while connecting to upstream, client:
> 192.168.1.105, server: localhost, request: "GET /accounts/menuleft/
> 122/ HTTP/1.1", upstream: "fastcgi://127.0.0.1:9001", host:
> "192.168.1.50", referrer: "http://192.168.1.50/accounts/menuleft/";


It appears that the error is actually from the previous (working)
request when Django subsequently tries to close the database
connections and fails, and since the error goes uncaught, it kills the
server.

It's pretty weird that it would fail in this way.  What happens if you
explicitly close the database connections at the end of your view?

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django+ oracle, working with apache(mod_python, wsgi) and in runserver, ora-03114 in fastcgi

2011-02-28 Thread Ian
On Feb 28, 10:04 am, lipt0n  wrote:
> Hi
> my application works fine in apache as mod_python and wsgi, also work
> great when I run manage.py runserver
> but I have to move it on nginx.
>
> so I run it by 'python2.6 manage.py runfcgi host=127.0.0.1 port=9001 --
> settings=settings'
> and it works fine until it have to connect to the database (oracle in
> my situation) and i get " Unhandled Exception",
> when I checked logs its what I found :
> "
> OperationalError: ORA-03114: not connected to ORACLE" while reading
> response header from upstream, client: 192.168.1.105, server:
> localhost, request: "POST / HTTP/1.1", upstream: "fastcgi://
> 127.0.0.1:9001", host: "192.168.1.50", referrer: "http://
> 192.168.1.50/"
> "
>
> ORACLE enviroment vars are set correctly, what can I do to fix this?

Could you post the full traceback?  That may be helpful in figuring
out what is happening.  Also, what versions of Django, Oracle, and
cx_Oracle are you using?

Thanks,
Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How to check if string is in Hebrew

2011-02-28 Thread Ian Clelland
On Sun, Feb 27, 2011 at 3:01 PM, ydjango  wrote:
> Hebrew is within the unicode range 0x590 to 0x5ff.
>
> I tried
> if lang_string[0] >= u'0x590' and lang_string[0] <= u'0x5ff':
>
> but it does not seem to work.

That isn't the correct syntax for unicode string literals. What you
are trying to do should look like this:

if lang_string[0] >= u'\u0590' and lang_string[0] <= u'\u05ff':

(See http://docs.python.org/reference/lexical_analysis.html#strings
for all the details on \u, \U, \x and their friends)

Testing just the first character of the string may or may not work for
general input; that depends entirely on your problem (and your users).
If it were me, I would define a utility function like this:

def char_is_hebrew(char):
return char >= u'\u0590' and char <= u'\u05ff'

and then test all of the characters in the string, either with

if any(map(char_is_hebrew, lang_string)):


or

if all(map(char_is_hebrew, lang_string)):


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: User Profiles?

2011-02-15 Thread Ian Clelland
> user=User.objects.create_user(username=username,email=email,password=password)
>    except django.db.utils.IntegrityError:
>        print 'user exists'
>        user=User.objects.get(username=username)
>    user.firstname=first_name
>    user.lastname=last_name
>    user.save() #make sure we have the user before we fiddle around
> with his name
>    #up to here, things work.
>    user.profile.age=34
>    user.save()

> The question is, why doesn't the age update?

This doesn't do what you are expecting, simply because saving the user
object is different from saving the profile object. (user.save() just
updates a row in the auth_user table, which doesn't affect the
accounts_userprofile table at all.)

The way I would do it is this:

profile = user.get_profile()
profile.age = 34
profile.save()

Try that, and see if it updates the database.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: images

2011-02-15 Thread Ian McDowall


On Feb 15, 10:16 am, Praveen Krishna R 
wrote:
> *plz Check django official docs to find out how static files are served on
> production and development server.*
> *
> *
> *in the dev server include a similiar snippet into your projects
> urls.py, urlpatterns:*
> *
> *
> *(r'^site_media/(?P.*)$',
> 'django.views.static.serve',{'document_root':
> 'D:/djangoprojects/praveensprofile/templates/static'}),*
> *
> *
> ***and in the templates something similar to the below text.*
> *
> *
> *
> *
> *
> *
> On Tue, Feb 15, 2011 at 1:07 PM, Szabo, Patrick (LNG-VIE) <
>
>
>
> patrick.sz...@lexisnexis.at> wrote:
> > How do i check the logs !?
> > I'm using the integrated webserver.
>
> > Kind regards
>
> > . . . . . . . . . . . . . . . . . . . . . . . . . .
> > Patrick Szabo
> >  XSLT-Entwickler
> > LexisNexis
> > Marxergasse 25, 1030 Wien
>
> > mailto:patrick.sz...@lexisnexis.at
> > Tel.: +43 (1) 534 52 - 1573
> > Fax: +43 (1) 534 52 - 146
>
> > -Ursprüngliche Nachricht-
>
> > Von: django-users@googlegroups.com [mailto:django-users@googlegroups.com]
> > Im Auftrag von Kenneth Gonsalves
> > Gesendet: Dienstag, 15. Februar 2011 11:05
> > An: django-users@googlegroups.com
> > Betreff: Re: images
>
> > On Tue, 2011-02-15 at 11:00 +0100, Szabo, Patrick (LNG-VIE) wrote:
> > > Unfortunately i only get the "alt text" shown and not the image.
> > > The image is in the same directory as the template.
>
> > check your logs to see where it is searching for your image
> > --
> > regards
> > KG
> >http://lawgon.livejournal.com
> > Coimbatore LUG rox
> >http://ilugcbe.techstud.org/
>
> > --
> > 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
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.
>
> > --
> > 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
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.
>
> --
> Thanks and Regards,
> *Praveen Krishna R*

Just to slightly expand on what Praveen said. Static files are served
differently from templates.

Templates are loaded from views using a configured template path.

Static files are served by your web server according to its
configuration. If you are using the development web server then you
need to configure Django as Praveen suggests to set the media path.
if you are serving any other static content then you have already done
this. As and when you move to a production web server, you will need
to configure that appropriately. You should be able to leave the links
unchanged (unless you do something daft) and just configure the web
server correctly.

Cheers, Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: TemplateSyntaxError at /polls/updatepath/ Caught AttributeError while rendering: 'RawQuerySet' object has no attribute 'all'

2011-02-11 Thread Ian Clelland
On Thu, Feb 10, 2011 at 9:10 AM, hank23  wrote:
> So when I go to build the entries for my drop down list then I would
> iterate over the query results like you suggested and at that point
> where I iterate over the results then I can also set the different
> select option attributes (html option tag attributes - value and
> visible-choice)  to the various values contained in each object
> returned in the queryset. Right?

I don't see why not. Of course, I don't see what your models look
like, either, but you should be able to do something like this:


{% for obj in my_raw_queryset %}
{{ obj.visible_choice }}
{% endfor %}


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: FormPreview with file upload problems

2011-02-10 Thread Ian Stokes-Rees
This problem is more subtle than I had originally appreciated.  Textual data 
is just re-submitted via an embedded hidden form, and the security hash is 
used to ensure that it hasn't been modified.  File data is harder to cope 
with.  There are a few options:

1. The originally uploaded file is held in some temporary location during 
the preview stage and then moved to the final location on "submit".  This 
allows uploaded files to be part of the validation/preview processing 
chain.  The problem is that they must be removed if the final "submit" never 
happens.  It is also tricky figuring out how to put these files in some 
"temporary" location.

2. The original preview form does not include files.  These are only 
uploaded with the final "submit".  This should "just work", but the down 
side is that there is no easy way to validate things like file not uploaded 
(mandatory upload files) or that the file format/content is as expected.

3. The originally uploaded file is processed like all is well and assumes a 
"submit" will happen.  The final "submit" process then has to re-link the 
pre-uploaded file to the form object before saving it.

If there are other alternatives, I'd love to know what they are.  1. and 3. 
seem like the best plans.  I feel like I should move forward with 1.

Comments welcome.

Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



FormPreview with file upload problems

2011-02-10 Thread Ian Stokes-Rees
I've followed the instructions here:

http://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-preview/

to setup a form preview system.  The problem is that my form includes a 
mandatory file upload.  I modified the form template to include:



however I still have problems processing the uploaded form, with the 
"preview" step returning an error stating:

   - This field is required.

Even when the file has been supplied.  Can someone advise how I can 
modify/manage FormPreview to handle uploaded files?

Thanks,

Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



upload_to chicken and egg problem

2011-02-10 Thread Ian Stokes-Rees
I would like to do the following:

class WSMRTask(GridTask):
tasktype= "wsmr"
mtz_fp  = FileField("MTZ file", upload_to=WSMRTask.path_gen)

class GridTask(Model):
tasktype= "unspec"
def path_gen(instance, filename):
return "%s/%s" % (WSMR_RELPATH, self.tasktype, self.taskname, 
self.filename)

since the properties to generate the upload_to pathname+filename come from 
the model instance itself.  I can't do this since the WSMRTask isn't defined 
at the point when I reference it (inside the class def).  Any good 
suggestions about how I can do this *other* than the obvious option of 
creating a separate module of functions that support the specific class?  
That is *so* not OO, but I'll do it if it is the only option.

Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



FormPreview and ModelForms

2011-02-10 Thread Ian Stokes-Rees
I'm using FormPreview with a ModelForm.  My done() method gets the request 
and the cleaned_data once form.is_valid() evaluates to True.  I'm wondering 
if I need to do anything special to use the cleaned_data or handle the 
form-uploaded files.  My current class definition is:

class WSMRTaskFormPreview(FormPreview):
def done(self, request, cleaned_data):
WSMRTaskForm(request.POST, request.FILES).save() 
return HttpResponseRedirect(reverse('success'))

but I'm wondering if it should be:

class WSMRTaskFormPreview(FormPreview):
def done(self, request, cleaned_data):
WSMRTaskForm(cleaned_data, request.FILES).save()  # cleaned_data 
instead of request.POST
return HttpResponseRedirect(reverse('success'))

or even:

class WSMRTaskFormPreview(FormPreview):
def done(self, request, cleaned_data):
if request.FILES.has_key('mtz_fp'):
WSMRTaskForm(request.POST, request.FILES).save() 
return HttpResponseRedirect(reverse('success'))
else:
return HttpResponseRedirect(reverse('missing_files'))

TIA, Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: TemplateSyntaxError at /polls/updatepath/ Caught AttributeError while rendering: 'RawQuerySet' object has no attribute 'all'

2011-02-10 Thread Ian Clelland
all() is a method on a Manager instance, that returns a QuerySet
containing every row in the table, without filtering. It is used
because you can't iterate over a Manager, only over a QuerySet.

As an example, if MyModel is a model, then MyModel.objects is a
Manager. If you tried to do this in python:

for obj in MyModel.objects:
# something

You would see an exception raised. In this case, you need to iterate
over MyModel.objects.all().

A RawQuerySet, though, is already a QuerySet. You can just iterate
over it, and it will just return every row that your SQL produces.
(Actually, that's pretty much all you can do with it, there's no way
for the ORM to add any other filtering or ordering to your custom SQL)

So, instead of trying to call all() on the QuerySet, just iterate over
it -- rather than

{% for obj in my_raw_query_set.all %}

just do

{% for obj in my_raw_query_set %}


On Thu, Feb 10, 2011 at 7:28 AM, hank23  wrote:
> I'm trying to use raw SQL to retrieve the information that I want to
> display in a dropdown list. Here's the error that I'm getting:
>
> TemplateSyntaxError at /polls/updatepath/
> Caught AttributeError while rendering: 'RawQuerySet' object has no
> attribute 'all'
>
> I'm not sure what this is trying to tell me. I used the same SQL
> syntax that is shown in the documentation at:
>
> http://docs.djangoproject.com/en/dev/topics/db/sql/
>
> Can somebody explain this to me? thanks.
>
> --
> 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 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>



-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: csrf cookie security

2011-02-10 Thread Ian Clelland
On Thu, Feb 10, 2011 at 5:21 AM, Lior Sion  wrote:
> It's been a while since I dealt with those things, but what about this
> scenario:
>
> The attacker detects the CSRF code using an attack resembling the
> scenario here:
>
> http://wiki.developerforce.com/index.php/Secure_Coding_Secure_Communications#Secure_Communications_and_Cookies
>
> [to save some time, this is the quote:
>
> Failure to set the Secure flag for security-critical cookies is the
> most common vulnerability in this category. Simply setting a cookie
> over an HTTPS connection does not prevent it from being returned over
> HTTP unless the Secure flag is set. Even if your site does not have an
> HTTP version, malicious parties on the network may be able to steal
> session cookies.
>
> There are several ways to achieve this. For example, the attacker may
> insert references to HTTP URLs to your application into sites that
> your users are likely to visit. Assume your application is 
> https://app.example.com,
> and your users frequent a discussion forum/blog at http://exampleappblog.com.
> ExampleAppBlog allows commenters to include limited HTML in their
> posts, including img tags. A commenter inserts HTML into one of their
> comments like the following:
>
> http://app.example.com/example-logo.png";
> class="external free" title="http://app.example.com/example-logo.png";
> rel="nofollow">http://app.example.com/example-logo.png" />
> When a user authenticated to app.example.com views this comment, their
> browser will fire off a request for example-logo.png over an insecure
> HTTP connection. Since the app.example.com cookie was not set Secure,
> the browser will include the cookie over this connection — exposing it
> to the network.
>
> ]
>
> Once they have the CSRF cookie, they use the site itself (example.com)
> and post malicious code there with the right CSRF.
>
> I agree it's not an easy attack, but why not turning on the secured
> flag for cookies on https?

This is a general attack against cookies; certainly, if an attacker
can steal all of your cookies, and can interfere with your network
connection, he can do a lot, with or without CSRF protection.

More specifically, the attack you present is more relevant to the
session cookie than the the CSRF-token cookie. If an attacker can
sniff your connection, and retrieve the cookies from it, then why not
just grab your session cookie (it's no more or less secure than the
CSRF cookie), and use it to impersonate you on the site? He won't even
need the CSRF token; he can just use any GET request to a page with a
form on it to get a new one.

If you are worried about an attacker who can sniff your network, you
have more to worry about than the 'secure' flag on your CSRF cookies.
You need to make sure that your login credentials (username/password)
are never sent in the clear, that your session cookie is never sent in
the clear, and that essentially your whole site is protected by SSL,
such that a request coming in over plain HTTP, even if properly
authenticated, is still rejected. Once you have this in place, the
secure flag on the CSRF cookie becomes irrelevant. An attacker can't
do any more damage with it than he could by any other means.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: csrf cookie security

2011-02-09 Thread Ian Clelland
On Wed, Feb 9, 2011 at 11:51 AM, Brian Craft  wrote:
> I thought, rather, that the csrf token was a cookie that was put in a
> hidden form field.

You're absolutely right; I wasn't thinking about that side of the token.

> With firebug or webkit dev tools you can see the django csrf token in
> the cookies. I would also refer you to middleware/csrf.py, where you
> can see it doing the set_cookie.
>
> I thought the security of the csrf token relied on the fact that the
> 3rd party wouldn't know what value to put in the hidden form field.
> The csrf middleware is, I believe, validating the value in the form
> field, against the value in cookie. But when it creates the form, it
> uses the value in the cookie.
>
> If the token is stored in an insecure cookie, it can be sniffed. Then
> I don't understand what prevents the attacker from constructing a
> valid form.

If you want a secure cookie, that means that your entire site (or at
least the form-handling bits) must already be protected by SSL (since
a secure cookie will only be returned over an SSL connection).

The threat model you are proposing, then, sounds like this: There is a
website, running Django, using Django's CSRF protection, in which all
of the form-handling views are only accessible over HTTPS, but there
are other resources in the same domain (or its subdomains) which are
accessible over HTTP.

Further, there is an attacker, who can sniff the unencrypted HTTP
traffic, and can construct an HTML page at a different site (this is
Cross-Site Request Forgery, after all)

A lot of the potential damage seems to be mitigated by another check
in django/middleware/csrf.py, for HTTPS requests only, that inpects
the referer header of the incoming request, to ensure that the browser
was not submitting the form from a different site. To get around that,
the attacker would have to be able to construct a form on the
SSL-protected site (a serious html-injection vulnerability would have
to be present), or cause the request to be submitted over plain HTTP
-- but the site is already HTTPS-only, so there shouldn't be any
form-handling code listening on that port.

Does this threat model correspond to what you're thinking? If so, I
don't see away around the CSRF protection (at least, not one that
involves the victim's browser)


-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: csrf cookie security

2011-02-09 Thread Ian Clelland
On Wed, Feb 9, 2011 at 11:23 AM, Brian Craft  wrote:
> I notice that the csrf token is not secure, i.e. the Set-Cookie is
> constructed w/o the "secure" option, so the browser will send it
> in-the-clear. It's trivial, then, for a 3rd party to discover the csrf
> token.
>
> Am I missing something?

The CSRF token isn't a cookie (or at least, it shouldn't be) -- it's a
form field. The security principle behind the CSRF token isn't so much
that it's not discoverable, as much as that an attacker can't
construct a link that gets your browser to submit it to the server.

If you site is under SSL (you're talking about secure-only cookies, so
I presume that this is the case,) then the CSRF token should only
appear in the HTML forms that the server sends to your browser, and
the POST requests that your browser makes back, both of which should
be protected.

If the CSRF token was set in a cookie, then it would be sent with
every single request that the browser made, and it really would be
trivial for an attacker to get you to make a valid request of the web
server, whether he could discover the contents of that cookie or not.
(SSL wouldn't even help; he could construct an https:// link just as
easily.) That's not how it's supposed to be set up, though.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Slow performance with Django when connected to Oracle

2011-02-08 Thread Ian
On Feb 8, 3:15 pm, dw314159  wrote:
> I am observing the same behavior in the Django shell. Here the actual
> query runtime is about the same between Oracle and PostgreSQL back-
> ends, but the total turnaround time is about 18 times longer with
> Oracle. I believe the following code demonstrates this case:
>
> from django.db import connection
> import minilims.log.models as log
> import time
> time_list = []
> for n in range(0, 20):
>  t1 = time.time()
>  entries = log.Param.objects.filter(log = 6).order_by('stuff', 'id')
>  entry = [x for x in entries]
>  t2 = time.time()
>  time_list.append(t2 - t1)
> print len(connection.queries), 'queries ran.'
> average_time = sum(time_list) / len(time_list)
> # display minimum, average, and maximum turnaround time
> print min(time_list), average_time, max(time_list)
> # display average query time
> print sum([float(x['time']) for x in connection.queries]) /
> len(connection.queries)
>
> The above code in the shell using a PostgreSQL backend reports:
>
> >>> # display minimum, average, and maximum turnaround time
> >>> print min(time_list), average_time, max(time_list)
>
> 0.203052997589 0.211852610111 0.234575033188
>
> >>> # display average query time
> >>> print sum([float(x['time']) for x in connection.queries]) / 
> >>> len(connection.queries)
>
> 0.0557
>
> However, running the same code with an Oracle back-end, after
> restarting the shell, results in:
>
> >>> # display minimum, average, and maximum turnaround time
> >>> print min(time_list), average_time, max(time_list)
>
> 3.59030008316 3.64263659716 4.33223199844
>
> >>> # display average query time
> >>> print sum([float(x['time']) for x in connection.queries]) / 
> >>> len(connection.queries)
>
> 0.05825
>
> Any ideas?

What does the model look like, and how many rows does your query
return?  The Oracle backend has to do some extra processing over the
data to get its results into the expected format.  This may be what
you're seeing, although I would be surprised if it is really
dominating the query time by that much.  LOB columns can also slow the
backend down significantly, since we have to make extra round-trips to
the database to read their contents.  Neither of these things would be
included in the recorded query time.

If your model includes LOB columns or has a large number of fields,
then your best bet is probably to use QuerySet.defer() or
QuerySet.only() to limit the fields returned to those that are
specifically of interest.

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Slow performance with Django when connected to Oracle

2011-02-08 Thread Ian
On Feb 7, 9:44 pm, dw314159  wrote:
> Django gurus:
>
> Hello, I am experiencing very slow performance with Django when
> connected to an Oracle database. The exact same Django application
> runs far faster with PostgreSQL and SQLite, with the same source data
> loaded into each database. Looking at the information embedded in
> “connection.queries” after making an Oracle query through Django, it
> appears that the queries themselves run very quickly (runtimes are
> comparable to those measured with PostgreSQL and SQLite), but the
> whole turnaround time for a query in Oracle far exceeds the reported
> query time.
>
> I’ve tried the built-in Oracle backend engine and django-oraclepool
> 0.7; neither improve performance. (With django-oraclepool, I also gave
> sufficient time for the connections to pool before taking
> measurements). Using cx_Oracle outside of Django on the same
> workstation to connect to the same Oracle database, the query
> turnaround time is very quick.
>
> Is this problem connected to the fact that Django is reported to drop
> the database connection between queries, and therefore must reconnect
> to Oracle every time a query is executed? Or is there a Django
> configuration option that must be specified to make the best use of
> Oracle?

Django actually closes the connection after each HTTP request, not
each individual query.  This means that if you were running your
timing tests in a request-less environment (i.e. through the Django
shell), you would not expect to see any slowdown caused by this.  It
also means that if you are running more than a few queries to serve
each request, the overall effect may be less noticeable.

Have you tried tracing the code during a request?  It would be helpful
to have at least a general idea of where it's spending so much time.

Cheers,
Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Including apps for inherited models in INSTALLED_APPS

2011-02-08 Thread Ian Stokes-Rees
I'm (reasonably) happy to include base models in INSTALLED_APPS, but
this argument:

On 2/8/11 4:32 AM, Tom Evans wrote:
> Explicit is better than implicit. If you want models from app 'base'
> installed on your system, you add the 'base' app to INSTALLED_APPS.
> Otherwise, its a series of $MAGIC working out what apps/DB tables are
> required, and $MAGIC is never good - might as well be using rails.

feels fairly arbitrary -- the whole point of a web framework like Django
is that "magic happens", and stuff "just works".

Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: read-only Form.as_* views

2011-02-07 Thread Ian Stokes-Rees


On 2/7/11 5:29 PM, Ian Stokes-Rees wrote:
> This sounds good.  Form Preview could be useful, but right now I just
> want to be able to use Generic Views (DetailView.as_view()) to render
> the default context object using "as_table()", but I'm failing to do that.
>
> {{ object.as_table }} returns nothing, whereas, {{ object.name }} etc.
> works just fine.  I don't understand why object.as_table wouldn't
> work.  Below are some code fragments.

I think I can answer my own question: as_table() is a method of
ModelForm objects, not Model objects.  So I tried pointing DetailView at
WSMRTaskForm, but now I get the exception:

type object 'WSMRTaskForm' has no attribute '_default_manager'


Frustrating!  Any suggestions?  It doesn't seem unreasonable to want the
DetailView to be able to render the "default" tabular view of the Model
created by:

class WSMRTaskForm(ModelForm):
class Meta:
model = WSMRTask

Thanks,

Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: read-only Form.as_* views

2011-02-07 Thread Ian Stokes-Rees
This sounds good.  Form Preview could be useful, but right now I just want 
to be able to use Generic Views (DetailView.as_view()) to render the default 
context object using "as_table()", but I'm failing to do that.

{{ object.as_table }} returns nothing, whereas, {{ object.name }} etc. works 
just fine.  I don't understand why object.as_table wouldn't work.  Below are 
some code fragments.

Cheers,

Ian

urls.py:
(r'task/(?P\d+)/?$'  , DetailView.as_view(model=WSMRTask)),

to

templates/wsmr/wsmrtask_detail.html:


{{ object.as_table }}



-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Including apps for inherited models in INSTALLED_APPS

2011-02-07 Thread Ian Stokes-Rees


On 2/7/11 3:50 PM, Shawn Milochik wrote:
> Because when the model isn't abstract, the fields
> in the base model aren't created for the subclass -- the subclass has
> a foreign key to an instance of the base model.
> That last bit should explain why you need to have the base app in
> installed apps.

Not really -- it explains why adding it makes things work, but it
doesn't explain why I *have* to include it.  "syncdb" is smart enough to
figure out that DerivedModel(BaseModel) has django.db.models.Model
*somewhere* in its super-class ancestry, so I don't see why it can't
also be smart enough to then figure out that "BaseModel" needs to be
included for ORM automatically.

Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



read-only Form.as_* views

2011-02-07 Thread Ian Stokes-Rees
I love the fact that I can quickly and easily get a "view" of my objects in 
Django, but is there any current way to get "read-only" views of objects 
where fields are not editable?  I want to be able to display the "forms" 
once they are completed but with the fields displayed just as table entries 
or textareas which can't be edited.  In other words, no  or  
tags.

TIA.  Ian Stokes-Rees

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Including apps for inherited models in INSTALLED_APPS

2011-02-07 Thread Ian Stokes-Rees
On 2/7/11 3:38 PM, Shawn Milochik wrote:
> Is your base model abstract? If it is not, then the ORM will want to
> create it in the database.

No, it isn't abstract.  It has a particular content model and methods
associated with it.  When you say the ORM will "want" to create it in
the DB, do you mean:

1. It should figure this out on its own and create the base model table; or
2. The ORM needs this so it must be listed in INSTALLED_APPS to have the
relevant table created in the DB.

Right now it looks like the situation is 2., but I'm wondering if there
is a good reason why it can't be 1.

Thanks,

Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Including apps for inherited models in INSTALLED_APPS

2011-02-07 Thread Ian Stokes-Rees
Does it make sense that inherited models also need their apps included in 
INSTALLED_APPS?  Right now if I have:

base/models.py:

class MyBaseModel(django.db.models.Model):
   stuff

and then elsewhere:

derived/models.py:

class MyDerivedModel(base.MyBaseModel):
   stuff

I need to include both "derived" and "base" in my INSTALLED_APPS list in 
settings.py, otherwise the table for the MyBaseModel content is never 
created.  It seems to me that "syncdb" should be able to "see" that 
MyDerivedModel has MyBaseModel as a super class in the chain to 
django.db.models.Model and consequently create the necessary tables for 
MyBaseModel.

Or have I just misunderstood why it was necessary for me to include "base" 
in order to get the tables created properly by "manage.py syncdb"?

TIA, Ian Stokes-Rees

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: working django with existing database

2011-01-31 Thread Ian
On Jan 31, 3:29 am, arief nur andono  wrote:
> oh please...
>
> i need only to query the table, have no access to modified the table
>
> why there is no way query the database and then make the output as object??

You don't need to modify the table.  That was just a recommendation.
I also suggested changing the precision (max_digits) and scale
(decimal_places) in your models file to match what is actually used in
your data.  If you have no idea what to use, then
DecimalField(max_digits=38, decimal_places=19) is *probably* safe.

If updating the models is going to be too laborious, then you should
probably look at a different ORM.  I don't know whether SQLAlchemy
will do a better job introspecting your database, but it's worth a
shot and can be used in conjunction with TurboGears or Pylons.

Cheers,
Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: working django with existing database

2011-01-31 Thread Ian
On Jan 31, 12:20 am, arief nur andono 
wrote:
> class TempJmlGangguanPyl(models.Model):
>     singkatpyl = models.CharField(max_length=4, blank=True)
>     singkatgrd = models.CharField(max_length=4, blank=True)
>     jumlah_gangguan = models.DecimalField(null=True, max_digits=0,
> decimal_places=-127, blank=True)
>     lama_gangguan = models.DecimalField(null=True, max_digits=0,
> decimal_places=-127, blank=True)
>     class Meta:
>         db_table = u'temp_jml_gangguan_pyl'

It appears that your numeric columns are all decimal-precision
floating-point (i.e. "FLOAT" or "NUMBER" with no precision or scale
specified), which is a bit of a corner case.  The basic problem is
that Django core has no field for this.  DecimalField can only handle
fixed-point, and FloatField uses binary precision.  If these columns
are actually used to store fixed-point data, you could manually update
the generated models (or preferably the original schema) with the
actual precision and scale of the data.  If they are truly floating-
point, then you would probably need to write a custom DecimalField
class.  I wouldn't recommend changing them to FloatField in any case,
because that could result in a loss of precision.

A similar problem can be encountered with "NUMBER(p, s)" columns where
s < 0 or s > p.  Both these scenarios are perfectly valid in Oracle,
but are (somewhat arbitrarily) disallowed by the DecimalField
validation.

I'll make a note of this.  At the very least, there should be a more
descriptive error message for when this comes up.

Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django and Oracle XE - Empty models file

2011-01-27 Thread Ian
On Jan 27, 3:53 am, Nathanael Dyke  wrote:
> I've only recently started playing with Django to undertake a technology
> assessment of the various frameworks available. As part of the assessment it
> needs to integrate with a legacy Oracle XE database (I know) which will
> contain customer data, with the default database being MySQL and containing
> all the project site data.
>
> When running inspectdb on the Oracle XE database it produces an empty models
> file except for the import header. When running this against the MySQL
> database the models table is created correctly.
>
> Does anyone have any suggestions on resolving this problem?

Hi Nathanael,

inspectdb on Oracle will only find tables in the Django user's
schema.  It doesn't inspect views or synonyms or tables in other
schemas.  I would guess that one of these describes your situation.

Ian

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django form(s) for intermediary models

2011-01-26 Thread Ian Lewis
Hi,

What you want to do here is use a Django "Formset" which contains your
ModelForms. Since you want to show one form per person
regardless of whether they are a member or not we can't use the
modelformset_factory() and will have to do some manipulation of the
initial data using the formset_factory() function instead. I haven't
actually run and tested the code below (user beware) but you'll need
to do something similar in order to do what you're describing.

See:
http://docs.djangoproject.com/en/dev/topics/forms/formsets/
http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets

Using the Membership form (I called it MembershipForm) from the previous poster:

from django.forms.models import formset_factory

def myview(request, group_id):
group = Group.objects.get(pk=group_id)

MembershipFormset = formset_factory(form=MembershipForm, extra=0)
if request.method == 'POST':
formset = MembershipFormset(request.POST)
if formset.is_valid():
# since the formset itself isn't a ModelFormset
# we need to loop over the individual ModelForms
# and save() them.
for form in formset.forms:
form.save()
# Do something
else:

# Make a person_id to membership mapping.
memberships = dict(map(lambda m: (m.person_id, m),
groups.membership_set.all()))
initial = {}
We need to order by pk (or some other field) here so that the
form indexes match.
for i,person in enumerate(Person.objects.all().order_by("pk")):
prefix = form.get_default_prefix()
membership = memberships.get(person.pk, None)

# Here we create the initial data.
# Add data for the each initialized form here.
# initial data is needed for every person in order
# to set the number of forms.
initial.update({
'%s-%s-person' % (prefix, i): person if membership else None,
'%s-%s-date_joined' % (prefix, i):
membership.date_joined if membership else None,
})
formset = MembershipFormset(initial=initial)

# do something


On Wed, Jan 26, 2011 at 8:46 AM, aa56280  wrote:
>> In your case it would become something like:
>>
>> class Membership(ModelForm):
>>         class Meta:
>>                 model = Membership
>>                 fields = ('person', 'date_joined')
>>                 widgets = {
>>                         'person' : CheckBox(),
>>                         'date_joined': TextInput(),
>>                 }
>
> I need a form for each person though because a Group could have many
> members.
>
> --
> 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 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>



-- 
Ian

http://www.ianlewis.org/

-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: URLField strange error

2011-01-19 Thread Ian Clelland
On Wed, Jan 19, 2011 at 10:37 AM, galago  wrote:
> Django 1.2.4,
> Python 2.7
> All is coded as it should be. debugger shows error in python code as You
> said. Maybe it will be fixed in the future. Exception is only when i put [ .
> When i put [] all is ok :)

Yes, either a bare '[' or ']' in the URL hostname will trigger this error.

Oddly, the URLValidator in django.core.validators should be catching
the ValueError that is coming back from urllib2; Django should already
be handling this. How are you trying to insert the value? Is this
being handled through a ModelForm, or are you saving the model
manually?

Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: URLField strange error

2011-01-19 Thread Ian Clelland
On Wed, Jan 19, 2011 at 6:29 AM, galago  wrote:
> When I try to insert that string to urlfield: http://asd[d I get strange
> exception:
>
> Invalid IPv6 URL
>
> How to correct it to show message and not error 500?

You will likely need to post some more information: What version of
Django, and what version of Python are you using?

A very quick search suggests that this is a new exception emitted by
Python 2.7; Django's URLField tries to validate the url with an actual
network connection, using Python's urllib2.

The URL you are trying to insert may be just valid enough to get past
the regex checks, and is then parsed by Python as an IPv6 address, and
rejected.

I don't have python 2.7 installed anywhere to check this, but if true,
this may be a bug in Django: Either the regex checks should be
tightened, or the new exception should be caught in the URL Validator.

Without some more info, this is all speculation anyway, though.

Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: South introspection doesn't get registrered

2011-01-17 Thread Ian Clelland
On Mon, Jan 17, 2011 at 9:18 AM, OryBand  wrote:
> Hello.
>
> I am using a simple custom Model:
>
> from django.db.models import ImageField
> class ImageWithThumbsField(ImageField):
>    def __init__(self, verbose_name=None, name=None, width_field=None,
> height_field=None, sizes=None, **kwargs):
>        self.verbose_name=verbose_name
>        self.name=name
>        self.width_field=width_field
>        self.height_field=height_field
>        self.sizes = sizes
>        super(ImageField, self).__init__(**kwargs)
>
> And this is my introspection rule, which I add to models.py:
>
> from south.modelsinspector import add_introspection_rules
> from lib.thumbs import ImageWithThumbsField
> add_introspection_rules(
>    [
>        (
>            (ImageWithThumbsField, ),
>            [],
>            {
>                "verbose_name": ["verbose_name", {"default": None}],
>                "name":         ["name",         {"default": None}],
>                "width_field":  ["width_field",  {"default": None}],
>                "height_field": ["height_field", {"default": None}],
>                "sizes":        ["sizes",        {"default": None}],
>            },
>        ),
>    ],
>    ["^core/.models/.lib.thumbs.ImageWithThumbsField",])
>
> However, when trying to convert my app (named "core") to south, I get
> "freeze" errors, like the rule wasn't registered:
>
>  ! Cannot freeze field 'core.additionalmaterialphoto.photo'
>  ! (this field has class lib.thumbs.ImageWithThumbsField)
>  ! Cannot freeze field 'core.material.photo'
>  ! (this field has class lib.thumbs.ImageWithThumbsField)
>  ! Cannot freeze field 'core.material.formulaimage'
>  ! (this field has class lib.thumbs.ImageWithThumbsField)
>
>  ! South cannot introspect some fields; this is probably because they
> are custom
>  ! fields. If they worked in 0.6 or below, this is because we have
> removed the
>  ! models parser (it often broke things).
>  ! To fix this, read http://south.aeracode.org/wiki/MyFieldsDontWork
>
> Does anybody know why?

Try changing the last line of your introspection rule, from
>  ["^core/.models/.lib.thumbs.ImageWithThumbsField",])
to something like
 ["^lib.thumbs.ImageWithThumbsField",])

It looks like South is not recognizing your field type, as it is using
a different package name than you are.

It may also need to be something like
'core.models.lib.thumbs.ImageWithThumbsField'
or
'core.models.ImagesWithThumbsField'
depending on how your package is structured.

At the very least, I'm pretty sure that the slashes you have in your
regex are incorrect, and won't ever match.

Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Query Set involving Model Method

2011-01-16 Thread Ian Clelland
On Sun, Jan 16, 2011 at 6:51 AM, Mikhail Korobov  wrote:
> It doesn't work that way. ORM translates you queries to SQL and the DB
> is responsible for filtering. It is not possible to translate
> arbitrary python function to SQL or pass it to DB engine. So you have
> to formulate you query using .filter syntax or raw SQL.

This is absolutely correct. You can't mix python functions with SQL functions.

>
> Another possibility is to denormalize data: add 'complete' field to
> the model and recalculate it on save (or whenever it make sense). This
> is often a good solution and it is better than complex queries in
> terms of performance.

There are some downsides to this method, though: It does take up some
space in the database; it requires some processing every time an
object is updated (and if your calculation involves any related
objects, then you have to do it whenever *they* are updated, as well.)
Additionally, if you ever change those rules, then you have to
recalculate the value of that field for every instance in the
database.

That doesn't mean that it's a bad idea -- I use it all the time -- but
you should at least think about it before doing it.

An alternative, if you want to keep the code simple, and don't mind
that it's less efficient than caching the field value, is to pull out
the values from the database with the ORM, and then filter them in
python:

filter(lambda x: x.complete(), DinnerHost.objects.all())

or even like this:

[x for x in DinnerHost.objects.all() if x.complete()]


>
> On 16 янв, 19:16, rmschne  wrote:
>> Thanks. I'm still messing with this; but don't think it quite what I'm
>> looking for.
>>
>> I want/need the Model Definition function complete() for use at the
>> record level.  I did this as a function since the rules are not based
>> simply on the value of the fields.
>>
>> Ideally, I'd like to have the class DinnerHoseManager(modes.Manager)
>> use the complete() function to help return the query set for where
>> complete()=True.  How to put that into this class?
>>
>> It's not the simple filter. Need a little more complexity to
>> determining "complete" based on the two if statements.
>
> --
> 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 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>



-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Generate a unique username for django.contrib.auth

2011-01-14 Thread Ian Clelland
On Wed, Jan 12, 2011 at 1:11 PM, Micah Carrick  wrote:
> I cannot use uuid4().hex because that's 32 characters... I need <30.

uuid4().hex[:30] is almost as random as uuid4().hex

There are no timers, MAC addresses, or other non-random sections in a
UUID4, so taking any 30-character slice from it should get you 120
bits of pure random goodness.

-- 
Regards,
Ian Clelland


-- 
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 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: QuerySetManager breakage with r14389

2011-01-12 Thread Ian Clelland
On Wed, Jan 12, 2011 at 6:23 AM, Russell Keith-Magee
 wrote:
> On Thu, Jan 6, 2011 at 5:29 AM, Ian Clelland  wrote:
>> Hi,
>>
>> I've been using Simon Willison's QuerySetManager[1] pattern for a
>> while now, and since upgrading to Django 1.2.4, it has been breaking
>> when I try to call a method on a RelatedManager constructed from it.
>>
>> There was a change in r14389 (14390 in the 1.2.X branch) which causes
>> this code to break -- where there was a simple delegation before from
>> the RelatedManager to the QuerySetManager to the model, there now
>> appears to be an infinite recursion, with the RelatedManager and
>> QuerySetManager trying to call each other's get_query_set methods.
>>
>> Has anybody seen this before? I am presuming that the change to
>> Django's related.py is correct, and that the QuerySetManager code just
>> needs to be updated to properly support Multi-db, but I don't know
>> where to start fixing it.
>
> Hi Ian,
>
> Sorry for taking so long to get back to you.
>
> No - I haven't seen this before; and I can't see an obvious reason
> that the snippet should have stopped working.
>
> If you want to make sure this is addressed, you should open a ticket
> in Trac. What you are report is an apparent regression in a recent
> changeset, so it would constitute a release-blocking bug for 1.3.

Thanks, Russ --

Looking at the QuerySetManager code, I couldn't tell if it was even
doing the right thing by unconditionally overriding __getattr__, or if
that was an incorrect solution that just happened to work until
related.py was fixed.

I've posted it on Trac, as ticket #15062.

(Glad to know it wasn't just lost in the noise :) )

Regards,
Ian Clelland


-- 
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: Retrieving data from Oracle DB table with column name containing special character

2011-01-06 Thread Ian
On Jan 6, 6:14 pm, Vikram  wrote:
> Hi,
>
> I have an existing table in my Oracle db called Sess. Few columns in
> this table have names that end with the character '#'. I am unable to
> run the command syncdb.
>
> Steps I did so far:
> 1. python manage.py inspectdb > models.py
> 2. Spruced up models.py to reflect only single table called Sess.
> 3. Running python manage.py syncdb

syncdb is only used to create tables.  If the table already exists,
then there is no reason to run it.

>   File "D:\Vikram\Personal\Python\django\database\monitor\models.py",
> line 15, in Sess
>     serial# = models.DecimalField(null=True, max_digits=10,
> decimal_places=2, blank=True)
> NameError: name 'serial' is not defined

The '#' symbol is not allowed in Python identifiers.  Python
interprets the statement above as being just the identifier 'serial',
and the rest of the line is interpreted as a comment.

You need to name the field as something that does not include the '#'
symbol and use the 'db_column' option to tell Django that the name of
the column in the database is different.  For example:

serial = models.DecimalField(null=True, max_digits=10,
decimal_places=2, blank=True, db_column='serial#')

Cheers,
Ian

-- 
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: Ordering columns in from clause

2011-01-06 Thread Ian Clelland
On Thu, Jan 6, 2011 at 7:35 AM, Vlastimil Zima  wrote:
> Recently I found out that distinct() can not be called on queries that
> are ordered as the result query is kind of
>
> SELECT DISTINCT table.id, table.ordering_column FROM table ORDER BY
> table.ordering_column ASC
>
> In ticket http://code.djangoproject.com/ticket/11568 was said that
> this will not be fixed, bacuse this is intentional behaviour of
> ordering.
>
>
> So code
>
> SomeModel.objects.order_by('ordering_column').values_list('pk')
>
> leads to SQL
>
> SELECT table.id, table.ordering_column FROM table ORDER BY
> table.ordering_column ASC
>
> instaed of simple
>
> SELECT table.id FROM table ORDER BY table.ordering_column ASC
>
> My question is, what is the intention? I could not find out any
> advantage that comes from this kind of query.

It is not valid SQL to order by a column that is not in the result set.

MySQL allows you to do that, but that is a MySQL-specific feature.
PostgreSQL, certainly, does not allow this, and there is no real
advantage gained (aside from a slightly smaller response) by excluding
the ordering column.



Regards,
Ian Clelland


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



QuerySetManager breakage with r14389

2011-01-05 Thread Ian Clelland
Hi,

I've been using Simon Willison's QuerySetManager[1] pattern for a
while now, and since upgrading to Django 1.2.4, it has been breaking
when I try to call a method on a RelatedManager constructed from it.

There was a change in r14389 (14390 in the 1.2.X branch) which causes
this code to break -- where there was a simple delegation before from
the RelatedManager to the QuerySetManager to the model, there now
appears to be an infinite recursion, with the RelatedManager and
QuerySetManager trying to call each other's get_query_set methods.

Has anybody seen this before? I am presuming that the change to
Django's related.py is correct, and that the QuerySetManager code just
needs to be updated to properly support Multi-db, but I don't know
where to start fixing it.

Thanks,
Ian


The simplest test case I can get to reproduce this problem looks like
this:

from django.db import models
from django.contrib.auth.models import User
from helpers import QuerySetManager

class TestModel(models.Model):
user = models.ForeignKey(User)
string = models.CharField(max_length=64, null=True, blank=True)
objects = QuerySetManager()
class QuerySet(models.query.QuerySet):
pass

>>> user = User.objects.get(username='testuser')
>>> user.testmodel_set.create(string="test")
Traceback (most recent call last):
  File "", line 1, in 
user.testmodel_set.create(string="test")
  File "/Users/ian/.virtualenvs/testcode/lib/python2.6/site-packages/
django/db/models/fields/related.py", line 423, in create
return super(RelatedManager, self.db_manager(db)).create(**kwargs)
  File "/Users/ian/.virtualenvs/egather/lib/python2.6/site-packages/
django/db/models/manager.py", line 138, in create
return self.get_query_set().create(**kwargs)
  File "/Users/ian/.virtualenvs/testcode/lib/python2.6/site-packages/
django/db/models/fields/related.py", line 410, in get_query_set
return
superclass.get_query_set(self).using(db).filter(**(self.core_filters))
  File "/Users/ian/Code/Tests/related_test/test_app/models.py", line
17, in __getattr__
return getattr(self.get_query_set(), attr, *args)
  File "/Users/ian/.virtualenvs/testcode/lib/python2.6/site-packages/
django/db/models/fields/related.py", line 410, in get_query_set
return
superclass.get_query_set(self).using(db).filter(**(self.core_filters))
  File "/Users/ian/Code/Tests/related_test/test_app/models.py", line
17, in __getattr__
return getattr(self.get_query_set(), attr, *args)
  File "/Users/ian/.virtualenvs/testcode/lib/python2.6/site-packages/
django/db/models/fields/related.py", line 410, in get_query_set
return
superclass.get_query_set(self).using(db).filter(**(self.core_filters))
  File "/Users/ian/Code/Tests/related_test/test_app/models.py", line
17, in __getattr__
return getattr(self.get_query_set(), attr, *args)
  File "/Users/ian/.virtualenvs/testcode/lib/python2.6/site-packages/
django/db/models/fields/related.py", line 410, in get_query_set
return
superclass.get_query_set(self).using(db).filter(**(self.core_filters))
  File "/Users/ian/Code/Tests/related_test/test_app/models.py", line
17, in __getattr__
return getattr(self.get_query_set(), attr, *args)
...
Lots snipped
...
  File "/Users/ian/.virtualenvs/egather/lib/python2.6/site-packages/
django/db/models/fields/related.py", line 410, in get_query_set
return
superclass.get_query_set(self).using(db).filter(**(self.core_filters))
  File "/Users/ian/Code/Tests/related_test/test_app/models.py", line
14, in get_query_set
return self.model.QuerySet(self.model)
  File "/Users/ian/.virtualenvs/testcode/lib/python2.6/site-packages/
django/db/models/query.py", line 33, in __init__
self.query = query or sql.Query(self.model)
  File "/Users/ian/.virtualenvs/testcode/lib/python2.6/site-packages/
django/db/models/sql/query.py", line 138, in __init__
self.aggregates = SortedDict() # Maps alias -> SQL aggregate
function
  File "/Users/ian/.virtualenvs/testcode/lib/python2.6/site-packages/
django/utils/datastructures.py", line 97, in __init__
super(SortedDict, self).__init__(data)
RuntimeError: maximum recursion depth exceeded while calling a Python
object

[1] http://djangosnippets.org/snippets/734/

-- 
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: Building app on already existing set of DB tables

2010-12-22 Thread Ian
On Dec 22, 9:22 am, Vikram  wrote:
> Scenario:
> table v$session contains all the current sessions information and is
> under SYS user. My web application should connect as webinfo user that
> has read-only access on v$session table, query the data and present it
> in webpage.
>
> Do I write views that directly talk to these tables, pull data and
> render it online? Or is there a better way?

Yes, you should create synonyms (or views, if you want more fine-
grained control) that pull those tables into the Django user's
schema.  Inspectdb will not work for synonyms or views in Oracle, so
you will need to write the models by hand.

Cheers,
Ian

-- 
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: ORA-01425

2010-12-03 Thread Ian
On Dec 2, 3:17 pm, Tim Sawyer  wrote:
> I unpatched mine (changed LIKEC to LIKE) and then ran:
>
>  >>> from django.db import connection
>  >>> cursor = connection.cursor()
>  >>> result = cursor.execute(r"SELECT 1 FROM DUAL WHERE TRANSLATE('A'
> USING NCHAR_CS) LIKE TRANSLATE('A' USING NCHAR_CS) ESCAPE TRANSLATE('\'
> USING NCHAR_CS)")
>  >>> rows = cursor.fetchall()
>  >>> for row in rows:
>  > ...   print row[0]
>  > ...
>  > 1
>  >>> print rows
>  > ((1,),)

Nuts.  What if you remove the first TRANSLATE call, i.e.

cursor.execute(r"SELECT 1 FROM DUAL WHERE 'A' LIKE TRANSLATE('A' USING
NCHAR_CS) ESCAPE TRANSLATE('\' USING NCHAR_CS)")

If that also doesn't trigger the error, then maybe we need an actual
column in the mix.  Please try this also:

cursor.execute(r"SELECT 1 FROM DUAL WHERE DUMMY LIKE TRANSLATE('X'
USING NCHAR_CS) ESCAPE TRANSLATE('\' USING NCHAR_CS)")

Thanks,
Ian

-- 
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: Django 1.2.3, Oracle with Character Set WE8MSWIN1252 - 'utf8' codec can't decode bytes

2010-12-02 Thread Ian Kelly
On Thu, Dec 2, 2010 at 5:52 PM, Anurag Chourasia
 wrote:
> Hi Ian,
> Can't tell you how much this helps :-)
> Setting the variable using ctypes before the import of cx_Oracle does the
> trick for me.
> Appreciate the time you spent in helping resolve this.
> Is there any Cygwin specific doc where we could include this?
> Regards,
> Anurag

You're welcome!  I've checked a fix into trunk and the 1.2.X branch,
so future releases will not have this problem.  I don't really see a
need for documentation apart from this thread on top of that.

Cheers,
Ian

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



<    1   2   3   4   5   6   7   >