Re: Disk I/O Error

2011-11-02 Thread m1chael
I would also check the disk space

On Tue, Nov 1, 2011 at 7:23 AM, Jani Tiainen  wrote:
> On 1.11.2011 8:23, Nicole Button wrote:
>>
>> I'm getting a DatabaseError, looking like this:
>>
>> Django Version:         1.3
>> Exception Type:         DatabaseError
>> Exception Value:        disk I/O error
>> Exception Location:     /usr/local/lib/python2.6/dist-packages/django/db/
>> backends/sqlite3/base.py in execute, line 234
>>
>> whenever I try to read or write to any of the databases associated
>> with any of the websites on one of our servers. The fact that all
>> these websites work locally, but not in their live versions seems to
>> suggest to me that something has gone wrong on the server, rather than
>> with django, but I thought I'd better ask and see if any one has had
>> any similar issues. I'm running python 2.6.6, django 1.3 and they're
>> on a Linux server.
>>
>
> My wild guess is that you don't have permissions to write in db directory...
> SQLite (if you're using it) requires read and write rights to directory
> where actual database resides.
>
> --
>
> Jani Tiainen
>
> --
> 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: Relation not found error while dealing with foreign keys and forms

2011-11-02 Thread Tabitha Samuel
Thank you so much for your reply! So I got a "Staff object has no
attribute 'query'" error when I did it with the get. I got the sql
when I tried it with the filter instead (instance =
Staff.objects.using('gold').filter(username='tsamuel') >>
str(instance.query))this is what I'm getting:

'SELECT "n_test_staff"."username", "n_test_staff"."home_phone",
"n_test_staff"."cell_phone", "n_test_staff"."home_address",
"n_test_staff"."home_city", "n_test_staff"."home_state",
"n_test_staff"."home_zip", "n_test_staff"."emergency_name",
"n_test_staff"."emergency_phone", "n_test_staff"."nics_group",
"n_test_staff"."room_number", "n_test_staff"."title",
"n_test_staff"."supervisor", "n_test_staff"."url",
"n_test_staff"."im", "n_test_staff"."last_modification_time",
"n_test_staff"."start_date", "n_test_staff"."creation_time",
"n_test_staff"."termination_date", "n_test_staff"."bio",
"n_test_staff"."photopath", "n_test_staff"."office_phone",
"n_test_staff"."email", "n_test_staff"."preferred_name",
"n_test_staff"."deleted", "n_test_staff"."viewable" FROM
"n_test_staff" WHERE "n_test_staff"."username" = tsamuel '

Looks like from the query, is not looking into the n_nics_groups
table. Question is why?

Tabitha

On Nov 2, 6:00 pm, Furbee  wrote:
> Can you try this and tell us what you see:
>
> Run a shell using python manage.py shell
>
> >>> instance = Staff.objects.using('gold').get(username='tsamuel')
> >>> str(instance.query)
>
> This will tell us whether or not the database, reference, and such are
> correctly translating into a query. The error means Django is sending an
> erroneous query to your database layer.
>
> Furbeenator
>
> On Wed, Nov 2, 2011 at 1:54 PM, Tabitha Samuel 
> wrote:
>
>
>
>
>
>
>
> > Hi,
>
> > In brief here is my problem. I have two simple tables, one has a one
> > to many relation with the other. The problem I run into is that when I
> > try to create a form instance of the child, and try to print it or
> > render it in a template, I run into a "relation not found" error for
> > the parent. Simply querying the parent works without a problem.
>
> > This is what my models.py looks like:
> > from django.db import models
>
> > class NICSGroupType(models.Model):
> >     n_group_number = models.IntegerField(primary_key = True)
> >    n_group_name = models.CharField(max_length = 512)
> >    class Meta:
> >        db_table = "n_nics_groups"
>
> > class Staff(models.Model):
> >    username                    = models.CharField(primary_key = True,
> > max_length = 50)
> >    home_phone                  = models.CharField(max_length = 12,
> > null=True)
> >    cell_phone                  = models.CharField(max_length = 12,
> > null = True)
> >    home_address                = models.CharField(max_length = 1024,
> > null = True)
> >    home_city                   = models.CharField(max_length = 64,
> > null = True)
> >    home_state                  = models.CharField(max_length = 32,
> > null = True)
> >    home_zip                    = models.CharField(max_length = 10,
> > null = True)
> >    emergency_name              = models.CharField(max_length =64,
> > null = True)
> >    emergency_phone             = models.CharField(max_length = 12,
> > null = True)
> >    nics_group                  = models.ForeignKey(NICSGroupType,
> > to_field ='n_group_number', db_column="nics_group",
> > null=True,blank=True)
> >    room_number                 = models.CharField(max_length = 32,
> > null = True)
> >    title                       = models.CharField(max_length = 64)
> >    supervisor                  = models.CharField(max_length = 25,
> > null = True, blank = True)
> >    url                         = models.CharField(max_length =
> > 256,null = True, blank = True)
> >    im                          = models.CharField(max_length = 32,
> > null = True, blank=True)
> >    last_modification_time      = models.IntegerField()
> >    start_date                  = models.IntegerField()
> >    creation_time               = models.IntegerField()
> >    termination_date            = models.IntegerField(null = True,
> > blank = True)
> >    bio                         = models.TextField()
> >    photopath                   = models.CharField(max_length = 5048)
> >    office_phone                = models.CharField(max_length=12)
> >    email                       = models.CharField(max_length = 256)
> >    preferred_name              = models.CharField(max_length = 50,
> > null = True, blank = True)
> >    deleted                     = models.BooleanField(default = False)
> >    viewable                    = models.BooleanField(default = True)
>
> >    class Meta:
> >        db_table = "n_test_staff"
>
> > The tables that it corresponds to looks like this:
>
> >  \d n_test_staff
> >                 Table "public.n_test_staff"
> >         Column         |          Type          | Modifiers
> > ++---
> >  username         

Django with Codebase Database

2011-11-02 Thread Jonathan
Does anybody use Django/Python with Codebase? Can it be done? If so,
how hard is 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.



"drop table if exists" aborts

2011-11-02 Thread Brian Craft
mysql generates an informational warning when running "drop table if
exists " if the table doesn't exist. Django then throws an
error and aborts.

Is there a good way to avoid this?

b.c.

-- 
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: Formwizard - Many2Many field - instance needs to have a primary key value before a many-to-many relationship can be used

2011-11-02 Thread youpsla
Thanks Furbee,

UNDERSTOOD.

Thanks again for detailled and instructive answers.

Alain

On 2 nov, 21:36, Furbee  wrote:
> Hi Alain,
>
> Sort of. With this code:
>     if field == 'category':
>         instance.save()
> a Customer with 50 categories would write to the database 51 times (1
> INSERT, and 50 UPDATES).
>
> Including the "instance.id == None" like this:
>     if field == 'category' and instance.id == None:
>         instance.save()
> will make it write to the database one or two times maximum. If the
> Customer has 0 categories, it will write once (INSERT at bottom of
> program). If the Customer has n categories, it will only write once
> (INSERT) in the loops, and write once (UPDATE) at the bottom of the program.
>
> That is why it is much quicker running it this way.
>
> Cheers,
>
> Furbeenator
>
>
>
>
>
>
>
> On Wed, Nov 2, 2011 at 1:00 PM, youpsla  wrote:
> > Hi again
> > thanks for explanations.
>
> > I've understood difference between Null and None.
>
> > I've modify the code to add "instance.id == Non" and it seems to be
> > faster.
>
> > To be sure. You mean that if a customer has 1 category, there will be
> > 2 database access (one for all informations except category and one
> > for category).
>
> > If a customer has 50 categories, then it's 51 database access ? hu
>
> > Thanks again
>
> > Alain
>
> > On 2 nov, 20:11, Furbee  wrote:
> > > Hi Alain,
>
> > > Glad that it worked out! :-)
>
> > > To clarify, a blank is different from a Null, or "None" in
> > Python/Django. A
> > > blank character field is "" where a null character field is NULL. If a
> > > field does not specify null=True, and you try to save an instance of that
> > > object without specifying that field, it will raise a Database error. So,
> > > in your loop if you hit category first, before any other fields, it would
> > > try to save the instance of the Customer without specifying all of the
> > > fields needed. That is why category must come AFTER all other fields that
> > > are required (not null=True).
>
> > > You are correct. The instance = Customer() creates a new customer object,
> > > when you executed instance.save() the instance information is saved
> > > (INSERT) to the database, and it received a PK (id). Every subsequent
> > > instance.save() actually runs (UPDATE) on the database, updating all
> > fields
> > > in the instance. If you have a whole lot of fields in the Customer, one
> > > optimization would be to add logic to the loop that if the field is
> > > 'category' and the instance has not yet been saved, save it. This way it
> > is
> > > only saved once before adding category and once at the end of setting all
> > > attributes. This will probably be a better solution, and will hit the
> > > database only twice instead of +1 times:
>
> > > class InscriptionWizard(SessionWizardView):
> > >     def done(self, form_list, **kwargs):
> > >         instance = Customer()
> > >         for form in form_list:
> > >             for field, value in form.cleaned_data.iteritems():
> > >                 if field == 'category' and instance.id == None: # if
> > this
> > > is a category, and the instance has not yet been saved, save it so it has
> > > an id.
> > >                     instance.save()
> > >                 setattr(instance, field, value)
> > >         instance.save()
>
> > > Happy coding!
>
> > > Furbeenator
>
> > > On Wed, Nov 2, 2011 at 12:00 PM, youpsla  wrote:
> > > > Oupsss, another question in the step by step:
>
> > > > 1 class InscriptionWizard(SessionWizardView):
> > > > 2    def done(self, form_list, **kwargs):
> > > > 3        instance = Customer()
> > > > 4        for form in form_list:
> > > > 5            for field, value in form.cleaned_data.iteritems():
> > > > 6                if field == 'category':
> > > > 7                    instance.save()
> > > > 8                setattr(instance, field, value)
> > > > 9        instance.save()
>
> > > > Line 7 : Will save in the DB all fields that have been already
> > > > iterated. Then I suppose the instance.save() will not clear
> > > > informations affected by the setattr() otherwise the PK is lost ...
> > > > and the Line 9 doesn't know wich PK to use 
>
> > > > Then I suppose the Line 9 will save all informations of the form,
> > > > those which have been already saved by Line 7 and add category. Then I
> > > > suppose Django will perform an "UPDATE" rather than an "INSERT" SQL
> > > > statement ?
>
> > > > Is it right ?
>
> > > > Again, regards for the time spend to answer.
>
> > > > Alain
>
> > > > On 2 nov, 19:03, Furbee  wrote:
> > > > > In your Customer model there are fields which cannot be Null, so you
> > > > cannot
> > > > > instance.save() before setting those properties. So, you may have to
> > > > check
> > > > > for the category field in your loop and if it is category, save the
> > > > > instance first. Something 

Re: Suggestions on "Loading" for possible long load-times?

2011-11-02 Thread Matt Schinckel
Russ mentioned it in passing, but I'll point it out for clarity: Celery is 
a great framework for handling background tasks.

-- 
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/-/TwtPwcwjzvkJ.
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: Relation not found error while dealing with foreign keys and forms

2011-11-02 Thread Furbee
Can you try this and tell us what you see:

Run a shell using python manage.py shell
>>> instance = Staff.objects.using('gold').get(username='tsamuel')
>>> str(instance.query)

This will tell us whether or not the database, reference, and such are
correctly translating into a query. The error means Django is sending an
erroneous query to your database layer.

Furbeenator

On Wed, Nov 2, 2011 at 1:54 PM, Tabitha Samuel wrote:

> Hi,
>
> In brief here is my problem. I have two simple tables, one has a one
> to many relation with the other. The problem I run into is that when I
> try to create a form instance of the child, and try to print it or
> render it in a template, I run into a "relation not found" error for
> the parent. Simply querying the parent works without a problem.
>
> This is what my models.py looks like:
> from django.db import models
>
> class NICSGroupType(models.Model):
> n_group_number = models.IntegerField(primary_key = True)
>n_group_name = models.CharField(max_length = 512)
>class Meta:
>db_table = "n_nics_groups"
>
> class Staff(models.Model):
>username= models.CharField(primary_key = True,
> max_length = 50)
>home_phone  = models.CharField(max_length = 12,
> null=True)
>cell_phone  = models.CharField(max_length = 12,
> null = True)
>home_address= models.CharField(max_length = 1024,
> null = True)
>home_city   = models.CharField(max_length = 64,
> null = True)
>home_state  = models.CharField(max_length = 32,
> null = True)
>home_zip= models.CharField(max_length = 10,
> null = True)
>emergency_name  = models.CharField(max_length =64,
> null = True)
>emergency_phone = models.CharField(max_length = 12,
> null = True)
>nics_group  = models.ForeignKey(NICSGroupType,
> to_field ='n_group_number', db_column="nics_group",
> null=True,blank=True)
>room_number = models.CharField(max_length = 32,
> null = True)
>title   = models.CharField(max_length = 64)
>supervisor  = models.CharField(max_length = 25,
> null = True, blank = True)
>url = models.CharField(max_length =
> 256,null = True, blank = True)
>im  = models.CharField(max_length = 32,
> null = True, blank=True)
>last_modification_time  = models.IntegerField()
>start_date  = models.IntegerField()
>creation_time   = models.IntegerField()
>termination_date= models.IntegerField(null = True,
> blank = True)
>bio = models.TextField()
>photopath   = models.CharField(max_length = 5048)
>office_phone= models.CharField(max_length=12)
>email   = models.CharField(max_length = 256)
>preferred_name  = models.CharField(max_length = 50,
> null = True, blank = True)
>deleted = models.BooleanField(default = False)
>viewable= models.BooleanField(default = True)
>
>class Meta:
>db_table = "n_test_staff"
>
> The tables that it corresponds to looks like this:
>
>  \d n_test_staff
> Table "public.n_test_staff"
> Column |  Type  | Modifiers
> ++---
>  username   | character varying(25)  |
>  home_phone | character varying(12)  |
>  cell_phone | character varying(12)  |
>  home_address   | character varying(256) |
>  home_city  | character varying(64)  |
>  home_state | character varying(32)  |
>  home_zip   | character varying(10)  |
>  emergency_name | character varying(64)  |
>  emergency_phone| character varying(12)  |
>  nics_group | integer|
>  room_number| character varying(32)  |
>  title  | character varying(64)  |
>  supervisor | character varying(25)  |
>  url| character varying(256) |
>  im | character varying(32)  |
>  last_modification_time | integer|
>  start_date | integer|
>  creation_time  | integer|
>  termination_date   | integer|
>  bio| text   |
>  photopath  | text   |
>  office_phone   | character varying(12)  |
>  email  | text   |
>  preferred_name | character varying(50)  |
>  deleted| boolean|
>  viewable   | boolean|
> Foreign-key constraints:
>"nics_group_fkey" FOREIGN KEY (nics_group) 

Relation not found error while dealing with foreign keys and forms

2011-11-02 Thread Tabitha Samuel
Hi,

In brief here is my problem. I have two simple tables, one has a one
to many relation with the other. The problem I run into is that when I
try to create a form instance of the child, and try to print it or
render it in a template, I run into a "relation not found" error for
the parent. Simply querying the parent works without a problem.

This is what my models.py looks like:
from django.db import models

class NICSGroupType(models.Model):
 n_group_number = models.IntegerField(primary_key = True)
n_group_name = models.CharField(max_length = 512)
class Meta:
db_table = "n_nics_groups"

class Staff(models.Model):
username= models.CharField(primary_key = True,
max_length = 50)
home_phone  = models.CharField(max_length = 12,
null=True)
cell_phone  = models.CharField(max_length = 12,
null = True)
home_address= models.CharField(max_length = 1024,
null = True)
home_city   = models.CharField(max_length = 64,
null = True)
home_state  = models.CharField(max_length = 32,
null = True)
home_zip= models.CharField(max_length = 10,
null = True)
emergency_name  = models.CharField(max_length =64,
null = True)
emergency_phone = models.CharField(max_length = 12,
null = True)
nics_group  = models.ForeignKey(NICSGroupType,
to_field ='n_group_number', db_column="nics_group",
null=True,blank=True)
room_number = models.CharField(max_length = 32,
null = True)
title   = models.CharField(max_length = 64)
supervisor  = models.CharField(max_length = 25,
null = True, blank = True)
url = models.CharField(max_length =
256,null = True, blank = True)
im  = models.CharField(max_length = 32,
null = True, blank=True)
last_modification_time  = models.IntegerField()
start_date  = models.IntegerField()
creation_time   = models.IntegerField()
termination_date= models.IntegerField(null = True,
blank = True)
bio = models.TextField()
photopath   = models.CharField(max_length = 5048)
office_phone= models.CharField(max_length=12)
email   = models.CharField(max_length = 256)
preferred_name  = models.CharField(max_length = 50,
null = True, blank = True)
deleted = models.BooleanField(default = False)
viewable= models.BooleanField(default = True)

class Meta:
db_table = "n_test_staff"

The tables that it corresponds to looks like this:

 \d n_test_staff
 Table "public.n_test_staff"
 Column |  Type  | Modifiers
++---
 username   | character varying(25)  |
 home_phone | character varying(12)  |
 cell_phone | character varying(12)  |
 home_address   | character varying(256) |
 home_city  | character varying(64)  |
 home_state | character varying(32)  |
 home_zip   | character varying(10)  |
 emergency_name | character varying(64)  |
 emergency_phone| character varying(12)  |
 nics_group | integer|
 room_number| character varying(32)  |
 title  | character varying(64)  |
 supervisor | character varying(25)  |
 url| character varying(256) |
 im | character varying(32)  |
 last_modification_time | integer|
 start_date | integer|
 creation_time  | integer|
 termination_date   | integer|
 bio| text   |
 photopath  | text   |
 office_phone   | character varying(12)  |
 email  | text   |
 preferred_name | character varying(50)  |
 deleted| boolean|
 viewable   | boolean|
Foreign-key constraints:
"nics_group_fkey" FOREIGN KEY (nics_group) REFERENCES
n_nics_groups(n_group_number) DEFERRABLE INITIALLY DEFERRED

n_nics_groups
Table "public.n_nics_groups"
 Column |  Type  | Modifiers
++---
 n_group_number | integer| not null
 n_group_name   | character varying(256) |
 n_group_lead   | character varying(25)  |
Indexes:
"n_nics_groups_pkey" PRIMARY KEY, btree (n_group_number)

So when I do a
 form = StaffForm(instance = Staff.objects.using('gold').get(username
='tsamuel'))
print form

the print form throws the error:
relation 

Abstract FormView

2011-11-02 Thread Kurtis
Hey,

I have a couple of FormViews that override quite a few methods. I want
to write an "Abstract View" that I can subclass for these. I'm
guessing what I actually need is a custom Mixin but I'm really not
sure.

Any suggestions on how to go about doing this?

Some methods I'm overriding:

get_form_kwargs
form_valid
form_invalid
get_context_data

Other than the form_class, the code in each is the same line for line
(except of course when referencing the Class name)

-- 
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: Formwizard - Many2Many field - instance needs to have a primary key value before a many-to-many relationship can be used

2011-11-02 Thread Furbee
Hi Alain,

Sort of. With this code:
if field == 'category':
instance.save()
a Customer with 50 categories would write to the database 51 times (1
INSERT, and 50 UPDATES).

Including the "instance.id == None" like this:
if field == 'category' and instance.id == None:
instance.save()
will make it write to the database one or two times maximum. If the
Customer has 0 categories, it will write once (INSERT at bottom of
program). If the Customer has n categories, it will only write once
(INSERT) in the loops, and write once (UPDATE) at the bottom of the program.

That is why it is much quicker running it this way.

Cheers,

Furbeenator

On Wed, Nov 2, 2011 at 1:00 PM, youpsla  wrote:

> Hi again
> thanks for explanations.
>
> I've understood difference between Null and None.
>
> I've modify the code to add "instance.id == Non" and it seems to be
> faster.
>
> To be sure. You mean that if a customer has 1 category, there will be
> 2 database access (one for all informations except category and one
> for category).
>
> If a customer has 50 categories, then it's 51 database access ? hu
>
>
> Thanks again
>
> Alain
>
>
>
> On 2 nov, 20:11, Furbee  wrote:
> > Hi Alain,
> >
> > Glad that it worked out! :-)
> >
> > To clarify, a blank is different from a Null, or "None" in
> Python/Django. A
> > blank character field is "" where a null character field is NULL. If a
> > field does not specify null=True, and you try to save an instance of that
> > object without specifying that field, it will raise a Database error. So,
> > in your loop if you hit category first, before any other fields, it would
> > try to save the instance of the Customer without specifying all of the
> > fields needed. That is why category must come AFTER all other fields that
> > are required (not null=True).
> >
> > You are correct. The instance = Customer() creates a new customer object,
> > when you executed instance.save() the instance information is saved
> > (INSERT) to the database, and it received a PK (id). Every subsequent
> > instance.save() actually runs (UPDATE) on the database, updating all
> fields
> > in the instance. If you have a whole lot of fields in the Customer, one
> > optimization would be to add logic to the loop that if the field is
> > 'category' and the instance has not yet been saved, save it. This way it
> is
> > only saved once before adding category and once at the end of setting all
> > attributes. This will probably be a better solution, and will hit the
> > database only twice instead of +1 times:
> >
> > class InscriptionWizard(SessionWizardView):
> > def done(self, form_list, **kwargs):
> > instance = Customer()
> > for form in form_list:
> > for field, value in form.cleaned_data.iteritems():
> > if field == 'category' and instance.id == None: # if
> this
> > is a category, and the instance has not yet been saved, save it so it has
> > an id.
> > instance.save()
> > setattr(instance, field, value)
> > instance.save()
> >
> > Happy coding!
> >
> > Furbeenator
> >
> >
> >
> >
> >
> >
> >
> > On Wed, Nov 2, 2011 at 12:00 PM, youpsla  wrote:
> > > Oupsss, another question in the step by step:
> >
> > > 1 class InscriptionWizard(SessionWizardView):
> > > 2def done(self, form_list, **kwargs):
> > > 3instance = Customer()
> > > 4for form in form_list:
> > > 5for field, value in form.cleaned_data.iteritems():
> > > 6if field == 'category':
> > > 7instance.save()
> > > 8setattr(instance, field, value)
> > > 9instance.save()
> >
> > > Line 7 : Will save in the DB all fields that have been already
> > > iterated. Then I suppose the instance.save() will not clear
> > > informations affected by the setattr() otherwise the PK is lost ...
> > > and the Line 9 doesn't know wich PK to use 
> >
> > > Then I suppose the Line 9 will save all informations of the form,
> > > those which have been already saved by Line 7 and add category. Then I
> > > suppose Django will perform an "UPDATE" rather than an "INSERT" SQL
> > > statement ?
> >
> > > Is it right ?
> >
> > > Again, regards for the time spend to answer.
> >
> > > Alain
> >
> > > On 2 nov, 19:03, Furbee  wrote:
> > > > In your Customer model there are fields which cannot be Null, so you
> > > cannot
> > > > instance.save() before setting those properties. So, you may have to
> > > check
> > > > for the category field in your loop and if it is category, save the
> > > > instance first. Something like the following:
> >
> > > > views.py (in clients application)
> > > > -
> > > > class InscriptionWizard(SessionWizardView):
> > > >def done(self, form_list, **kwargs):
> > > >instance = Customer()
> > > >for form in 

Re: Formwizard - Many2Many field - instance needs to have a primary key value before a many-to-many relationship can be used

2011-11-02 Thread youpsla
Hi again
thanks for explanations.

I've understood difference between Null and None.

I've modify the code to add "instance.id == Non" and it seems to be
faster.

To be sure. You mean that if a customer has 1 category, there will be
2 database access (one for all informations except category and one
for category).

If a customer has 50 categories, then it's 51 database access ? hu


Thanks again

Alain



On 2 nov, 20:11, Furbee  wrote:
> Hi Alain,
>
> Glad that it worked out! :-)
>
> To clarify, a blank is different from a Null, or "None" in Python/Django. A
> blank character field is "" where a null character field is NULL. If a
> field does not specify null=True, and you try to save an instance of that
> object without specifying that field, it will raise a Database error. So,
> in your loop if you hit category first, before any other fields, it would
> try to save the instance of the Customer without specifying all of the
> fields needed. That is why category must come AFTER all other fields that
> are required (not null=True).
>
> You are correct. The instance = Customer() creates a new customer object,
> when you executed instance.save() the instance information is saved
> (INSERT) to the database, and it received a PK (id). Every subsequent
> instance.save() actually runs (UPDATE) on the database, updating all fields
> in the instance. If you have a whole lot of fields in the Customer, one
> optimization would be to add logic to the loop that if the field is
> 'category' and the instance has not yet been saved, save it. This way it is
> only saved once before adding category and once at the end of setting all
> attributes. This will probably be a better solution, and will hit the
> database only twice instead of +1 times:
>
> class InscriptionWizard(SessionWizardView):
>     def done(self, form_list, **kwargs):
>         instance = Customer()
>         for form in form_list:
>             for field, value in form.cleaned_data.iteritems():
>                 if field == 'category' and instance.id == None: # if this
> is a category, and the instance has not yet been saved, save it so it has
> an id.
>                     instance.save()
>                 setattr(instance, field, value)
>         instance.save()
>
> Happy coding!
>
> Furbeenator
>
>
>
>
>
>
>
> On Wed, Nov 2, 2011 at 12:00 PM, youpsla  wrote:
> > Oupsss, another question in the step by step:
>
> > 1 class InscriptionWizard(SessionWizardView):
> > 2    def done(self, form_list, **kwargs):
> > 3        instance = Customer()
> > 4        for form in form_list:
> > 5            for field, value in form.cleaned_data.iteritems():
> > 6                if field == 'category':
> > 7                    instance.save()
> > 8                setattr(instance, field, value)
> > 9        instance.save()
>
> > Line 7 : Will save in the DB all fields that have been already
> > iterated. Then I suppose the instance.save() will not clear
> > informations affected by the setattr() otherwise the PK is lost ...
> > and the Line 9 doesn't know wich PK to use 
>
> > Then I suppose the Line 9 will save all informations of the form,
> > those which have been already saved by Line 7 and add category. Then I
> > suppose Django will perform an "UPDATE" rather than an "INSERT" SQL
> > statement ?
>
> > Is it right ?
>
> > Again, regards for the time spend to answer.
>
> > Alain
>
> > On 2 nov, 19:03, Furbee  wrote:
> > > In your Customer model there are fields which cannot be Null, so you
> > cannot
> > > instance.save() before setting those properties. So, you may have to
> > check
> > > for the category field in your loop and if it is category, save the
> > > instance first. Something like the following:
>
> > > views.py (in clients application)
> > > -
> > > class InscriptionWizard(SessionWizardView):
> > >    def done(self, form_list, **kwargs):
> > >        instance = Customer()
> > >        for form in form_list:
> > >            for field, value in form.cleaned_data.iteritems():
> > >                if field == 'category':
> > >                    instance.save()
> > >                setattr(instance, field, value)
> > >        instance.save()
> > > -
>
> > > This would of course depend on your ordering of the fields. In other
> > words,
> > > category would have to be the first Allow Null field in your model,
> > because
> > > you cannot save() until all Not Null fields have a value. If you cannot
> > > order these fields so the category is last, you may have to do something
> > > like:
>
> > > views.py (in clients application)
> > > -
> > > class InscriptionWizard(SessionWizardView):
> > >    def done(self, form_list, **kwargs):
> > >        instance = Customer()
> > >        for form in form_list:
> > >            for field, value in 

Re: Problems with jquery and accessing django template system

2011-11-02 Thread Kevin Miller
Thanks Tom, but I have already tried that and it didn't work.



On Wed, Nov 2, 2011 at 12:25 PM, Tom Evans  wrote:
> n Wed, Nov 2, 2011 at 5:13 PM, Kevin Miller  wrote:
>> I have a url that I need to attach to link that is in a jquery
>> section. It seem like the django template system is not getting the
>> variable. For example:
>>
>> $.each(event,function(index,value){
>>                        var url = "{% url fiesta.views.detail "+
>> event[index].pk +"  %}"
>
> It gets the variable alright - the variable is the raw string "+
> event[index].pk + ". Template rendering happens before the javascript
> runs.
>
> An option is to hardcode an id into the generated URL, and then replace it:
>
> var url = "{% url fiesta.views.detail 999 %}";
> url = url.replace('999', event[index].pk);
>
>
> Cheers
>
> Tom
>
> --
> 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: Formwizard - Many2Many field - instance needs to have a primary key value before a many-to-many relationship can be used

2011-11-02 Thread Furbee
Hi Alain,

Glad that it worked out! :-)

To clarify, a blank is different from a Null, or "None" in Python/Django. A
blank character field is "" where a null character field is NULL. If a
field does not specify null=True, and you try to save an instance of that
object without specifying that field, it will raise a Database error. So,
in your loop if you hit category first, before any other fields, it would
try to save the instance of the Customer without specifying all of the
fields needed. That is why category must come AFTER all other fields that
are required (not null=True).

You are correct. The instance = Customer() creates a new customer object,
when you executed instance.save() the instance information is saved
(INSERT) to the database, and it received a PK (id). Every subsequent
instance.save() actually runs (UPDATE) on the database, updating all fields
in the instance. If you have a whole lot of fields in the Customer, one
optimization would be to add logic to the loop that if the field is
'category' and the instance has not yet been saved, save it. This way it is
only saved once before adding category and once at the end of setting all
attributes. This will probably be a better solution, and will hit the
database only twice instead of +1 times:

class InscriptionWizard(SessionWizardView):
def done(self, form_list, **kwargs):
instance = Customer()
for form in form_list:
for field, value in form.cleaned_data.iteritems():
if field == 'category' and instance.id == None: # if this
is a category, and the instance has not yet been saved, save it so it has
an id.
instance.save()
setattr(instance, field, value)
instance.save()

Happy coding!

Furbeenator


On Wed, Nov 2, 2011 at 12:00 PM, youpsla  wrote:

> Oupsss, another question in the step by step:
>
> 1 class InscriptionWizard(SessionWizardView):
> 2def done(self, form_list, **kwargs):
> 3instance = Customer()
> 4for form in form_list:
> 5for field, value in form.cleaned_data.iteritems():
> 6if field == 'category':
> 7instance.save()
> 8setattr(instance, field, value)
> 9instance.save()
>
> Line 7 : Will save in the DB all fields that have been already
> iterated. Then I suppose the instance.save() will not clear
> informations affected by the setattr() otherwise the PK is lost ...
> and the Line 9 doesn't know wich PK to use 
>
> Then I suppose the Line 9 will save all informations of the form,
> those which have been already saved by Line 7 and add category. Then I
> suppose Django will perform an "UPDATE" rather than an "INSERT" SQL
> statement ?
>
> Is it right ?
>
>
> Again, regards for the time spend to answer.
>
> Alain
>
> On 2 nov, 19:03, Furbee  wrote:
> > In your Customer model there are fields which cannot be Null, so you
> cannot
> > instance.save() before setting those properties. So, you may have to
> check
> > for the category field in your loop and if it is category, save the
> > instance first. Something like the following:
> >
> > views.py (in clients application)
> > -
> > class InscriptionWizard(SessionWizardView):
> >def done(self, form_list, **kwargs):
> >instance = Customer()
> >for form in form_list:
> >for field, value in form.cleaned_data.iteritems():
> >if field == 'category':
> >instance.save()
> >setattr(instance, field, value)
> >instance.save()
> > -
> >
> > This would of course depend on your ordering of the fields. In other
> words,
> > category would have to be the first Allow Null field in your model,
> because
> > you cannot save() until all Not Null fields have a value. If you cannot
> > order these fields so the category is last, you may have to do something
> > like:
> >
> > views.py (in clients application)
> > -
> > class InscriptionWizard(SessionWizardView):
> >def done(self, form_list, **kwargs):
> >instance = Customer()
> >for form in form_list:
> >for field, value in form.cleaned_data.iteritems():
> >if field != 'category':
> >setattr(instance, field, value)
> >instance.save()
> >for form in form_list:
> >for field, value in form.cleaned_data.iteritems():
> >if field == 'category':
> >setattr(instance, field, value)
> > -
> >
> > I'm sure there is a MUCH more elegant way of getting just the categories
> > from the forms and field/value pairs, this is brute force (not very
> > scalable for large number of fields), but should work. Anybody else
> please,
> > show code that could get the 

Re: Formwizard - Many2Many field - instance needs to have a primary key value before a many-to-many relationship can be used

2011-11-02 Thread youpsla
Oupsss, another question in the step by step:

1 class InscriptionWizard(SessionWizardView):
2    def done(self, form_list, **kwargs):
3        instance = Customer()
4        for form in form_list:
5            for field, value in form.cleaned_data.iteritems():
6                if field == 'category':
7                    instance.save()
8                setattr(instance, field, value)
9        instance.save()

Line 7 : Will save in the DB all fields that have been already
iterated. Then I suppose the instance.save() will not clear
informations affected by the setattr() otherwise the PK is lost ...
and the Line 9 doesn't know wich PK to use 

Then I suppose the Line 9 will save all informations of the form,
those which have been already saved by Line 7 and add category. Then I
suppose Django will perform an "UPDATE" rather than an "INSERT" SQL
statement ?

Is it right ?


Again, regards for the time spend to answer.

Alain

On 2 nov, 19:03, Furbee  wrote:
> In your Customer model there are fields which cannot be Null, so you cannot
> instance.save() before setting those properties. So, you may have to check
> for the category field in your loop and if it is category, save the
> instance first. Something like the following:
>
> views.py (in clients application)
> -
> class InscriptionWizard(SessionWizardView):
>    def done(self, form_list, **kwargs):
>        instance = Customer()
>        for form in form_list:
>            for field, value in form.cleaned_data.iteritems():
>                if field == 'category':
>                    instance.save()
>                setattr(instance, field, value)
>        instance.save()
> -
>
> This would of course depend on your ordering of the fields. In other words,
> category would have to be the first Allow Null field in your model, because
> you cannot save() until all Not Null fields have a value. If you cannot
> order these fields so the category is last, you may have to do something
> like:
>
> views.py (in clients application)
> -
> class InscriptionWizard(SessionWizardView):
>    def done(self, form_list, **kwargs):
>        instance = Customer()
>        for form in form_list:
>            for field, value in form.cleaned_data.iteritems():
>                if field != 'category':
>                    setattr(instance, field, value)
>        instance.save()
>        for form in form_list:
>            for field, value in form.cleaned_data.iteritems():
>                if field == 'category':
>                    setattr(instance, field, value)
> -
>
> I'm sure there is a MUCH more elegant way of getting just the categories
> from the forms and field/value pairs, this is brute force (not very
> scalable for large number of fields), but should work. Anybody else please,
> show code that could get the specific forms and field/values for categories.
>
> Furbeenator
>
>
>
>
>
>
>
> On Wed, Nov 2, 2011 at 10:28 AM, youpsla  wrote:
> > Hello,
> > i'm currently doning a website where user can register (without
> > password, without auth module of Django). They put some informations
> > and at the end (Step5Form) do multiple choices by clicking on
> > checkboxes. When I click on validate on the last step I've "instance
> > needs to have a primary key value before a many-to-many relationship
> > can be used" error. I've search the web to find a solution but . :-
> > (
>
> > Here is my code:
>
> > models.py for Customer (in clients application)
> > -
> > class Customer (models.Model):
>
> >    email_adresse = models.EmailField(max_length=255, unique=True)
> >    some fields . for Step2 to Step4 of the form
> >    category = models.ManyToManyField(Categories)
> > -
>
> > models.py for categories (in categories application)
> > -
> > class Categories (models.Model):
> >    category = models.CharField(max_length=200)
>
> >    def __unicode__(self):
> >        return unicode(self.category)
> > -
>
> > The ManyToMany field has created(syncdb) a table
> > clients_customer_category with the following columns:
> >        1       id                      int(11)
> > AUTO_INCREMENT
> >        2       customer_id     int(11)
> >        3       categories_id   int(11)
>
> > urls.py
> > -
> > urlpatterns = patterns('',
> >    (r'^clients/$', InscriptionWizard.as_view([Step1Form, Step2Form,
> > Step3Form, Step4Form, Step5Form])),
> > )
> > -
>
> > forms.py (in clients application)
> > -
> > from django import forms
> > from clients.models import Customer

Re: Formwizard - Many2Many field - instance needs to have a primary key value before a many-to-many relationship can be used

2011-11-02 Thread youpsla
Hi Furbeenator,
thanks a lots, it works !!! :-)))

I've use your first solution. You say that "category would have to be
the first Allow Null field in your model" wich is not the case here. A
"phone" field is the first step (Step0) can be empty :
telephone = models.CharField(max_length=14, blank=True)

Maybe I do a confusion between "Allow Null" and "blank=True) ?


To be sure to understand your solution, I go bellow step by step:

1 class InscriptionWizard(SessionWizardView):
2    def done(self, form_list, **kwargs):
3        instance = Customer()
4        for form in form_list:
5            for field, value in form.cleaned_data.iteritems():
6                if field == 'category':
7                    instance.save()
8                setattr(instance, field, value)
9        instance.save()

Line 5 : Iterate over field and values
Line 6 : If field name is category, then save the instance BEFORE
setting attribute (setattr) for the category field. Then a PK is
available in the DB for saving the m2m field category, wich is done
Line 9.

Is it the way it works and has to works ?


Again, thanks a lots for help  Yahoo !!!

Regards

Alain







On 2 nov, 19:03, Furbee  wrote:
> In your Customer model there are fields which cannot be Null, so you cannot
> instance.save() before setting those properties. So, you may have to check
> for the category field in your loop and if it is category, save the
> instance first. Something like the following:
>
> views.py (in clients application)
> -
> class InscriptionWizard(SessionWizardView):
>    def done(self, form_list, **kwargs):
>        instance = Customer()
>        for form in form_list:
>            for field, value in form.cleaned_data.iteritems():
>                if field == 'category':
>                    instance.save()
>                setattr(instance, field, value)
>        instance.save()
> -
>
> This would of course depend on your ordering of the fields. In other words,
> category would have to be the first Allow Null field in your model, because
> you cannot save() until all Not Null fields have a value. If you cannot
> order these fields so the category is last, you may have to do something
> like:
>
> views.py (in clients application)
> -
> class InscriptionWizard(SessionWizardView):
>    def done(self, form_list, **kwargs):
>        instance = Customer()
>        for form in form_list:
>            for field, value in form.cleaned_data.iteritems():
>                if field != 'category':
>                    setattr(instance, field, value)
>        instance.save()
>        for form in form_list:
>            for field, value in form.cleaned_data.iteritems():
>                if field == 'category':
>                    setattr(instance, field, value)
> -
>
> I'm sure there is a MUCH more elegant way of getting just the categories
> from the forms and field/value pairs, this is brute force (not very
> scalable for large number of fields), but should work. Anybody else please,
> show code that could get the specific forms and field/values for categories.
>
> Furbeenator
>
>
>
>
>
>
>
> On Wed, Nov 2, 2011 at 10:28 AM, youpsla  wrote:
> > Hello,
> > i'm currently doning a website where user can register (without
> > password, without auth module of Django). They put some informations
> > and at the end (Step5Form) do multiple choices by clicking on
> > checkboxes. When I click on validate on the last step I've "instance
> > needs to have a primary key value before a many-to-many relationship
> > can be used" error. I've search the web to find a solution but . :-
> > (
>
> > Here is my code:
>
> > models.py for Customer (in clients application)
> > -
> > class Customer (models.Model):
>
> >    email_adresse = models.EmailField(max_length=255, unique=True)
> >    some fields . for Step2 to Step4 of the form
> >    category = models.ManyToManyField(Categories)
> > -
>
> > models.py for categories (in categories application)
> > -
> > class Categories (models.Model):
> >    category = models.CharField(max_length=200)
>
> >    def __unicode__(self):
> >        return unicode(self.category)
> > -
>
> > The ManyToMany field has created(syncdb) a table
> > clients_customer_category with the following columns:
> >        1       id                      int(11)
> > AUTO_INCREMENT
> >        2       customer_id     int(11)
> >        3       categories_id   int(11)
>
> > urls.py
> > -
> > urlpatterns = patterns('',
> >    (r'^clients/$', InscriptionWizard.as_view([Step1Form, Step2Form,
> > Step3Form, Step4Form, 

Re: QuerySet: "if obj in queryset" can be very slow

2011-11-02 Thread Ian Clelland
On Wed, Nov 2, 2011 at 10:46 AM, Tom Evans  wrote:

> OK, take this example. I have a django model table with 70 million
> rows in it. Doing any kind of query on this table is slow, and
> typically the query is date restrained - which mysql will use as the
> optimum key, meaning any further filtering is a table scan on the
> filtered rows.
>
> Pulling a large query (say, all logins in a month, ~1 million rows)
> takes only a few seconds longer than counting the number of rows the
> query would find - after all, the database still has to do precisely
> the same amount of work, it just doesn't have to deliver the data.
>
> Say I have a n entries I want to test are in that resultset, and I
> also want to iterate through the list, calculating some data and
> printing out the row, I can do the existence tests either in python or
> in the database. If I do it in the database, I have n+1 expensive
> queries to perform. If I do it in python, I have 1 expensive query to
> perform, and (worst case) n+1 full scans of the data retrieved (and I
> avoid locking the table for n+1 expensive queries).
>
> Depending on the size of the data set, as the developer I have the
> choice of which will be more appropriate for my needs. Sometimes I
> need "if qs.filter(pk=obj.pk).exists()", sometimes I need "if obj in
> qs".
>
>
Just looking at the source to QuerySet (finally), and it looks like the
__contains__ method actually does something different than this: It
evaluates the whole QuerySet in bulk at the database level, and starts
creating model instances based on that, but only until it finds a matching
one. So, after running "if obj in qs", you might end up with one object
created, or you might end up with 70M objects, or anywhere in between.

Again: odd, undocumented, and potentially surprising behaviour, and I'd
recommend explicit over implicit, especially in this case.



-- 
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: QuerySet: "if obj in queryset" can be very slow

2011-11-02 Thread Ian Clelland
On Wed, Nov 2, 2011 at 10:46 AM, Tom Evans  wrote:

> On Wed, Nov 2, 2011 at 5:30 PM, Ian Clelland  wrote:
> > On Wed, Nov 2, 2011 at 8:25 AM, Thomas Guettler  wrote:
> >>
> >> # This is my current solution
> >> if get_special_objects().filter(pk=obj.pk).count():
> >># yes, it is special
> >>
> >
> > I can't speak to the "why" of this situation; it seems to me that this
> could
> > always be converted into a more efficient database query without any
> > unexpected side-effects (and if I really wanted the side effects, I would
> > just write "if obj in list(qs)" instead). In this case, though, I would
> > usually write something like this:
> > if get_special_objects().filter(pk=obj.pk).exists():
> ># yes, it is special
> > I believe that in some cases, the exists() query can be optimized to
> return
> > faster than a count() aggregation, and I think that the intent of the
> code
> > appears more clearly.
> > Ian
>
> OK, take this example. I have a django model table with 70 million
> rows in it. Doing any kind of query on this table is slow, and
> typically the query is date restrained - which mysql will use as the
> optimum key, meaning any further filtering is a table scan on the
> filtered rows.
>
> Pulling a large query (say, all logins in a month, ~1 million rows)
> takes only a few seconds longer than counting the number of rows the
> query would find - after all, the database still has to do precisely
> the same amount of work, it just doesn't have to deliver the data.
>
> Say I have a n entries I want to test are in that resultset, and I
> also want to iterate through the list, calculating some data and
> printing out the row, I can do the existence tests either in python or
> in the database. If I do it in the database, I have n+1 expensive
> queries to perform. If I do it in python, I have 1 expensive query to
> perform, and (worst case) n+1 full scans of the data retrieved (and I
> avoid locking the table for n+1 expensive queries).
>
> Depending on the size of the data set, as the developer I have the
> choice of which will be more appropriate for my needs. Sometimes I
> need "if qs.filter(pk=obj.pk).exists()", sometimes I need "if obj in
> qs".
>

I agree that there are situations where you want, or need, to pull the data
in to Python for processing, to avoid a lot of database overhead. That's
why we have select_related, as well: sometimes you really do need to just
grab as much as possible all at once.

The trouble is that querysets are *supposed* to be lazy; just evaluating as
much as necessary, as late as possible, to do the job. I think that this
behaviour violates the principle of least surprise, by instantiating a
(potentially very large) queryset as a side-effect of a simple inclusion
test.

Any other time that you want a queryset instantiated, the idiomatic way to
do it is to construct a Python list based on it:

# Get all objects at once from database
objs = list(qs)
# Now use that list multiple times in a method

or

for obj in list(qs):
  # qs is evaluated once, list members may be manipulated as needed in
Python

or, by extension,

if obj in list(qs):
  # stuff

I wouldn't rely on the behaviour of the in operator to evaluate the
queryset for me; it doesn't look right to me, it's not obvious to anyone
else looking at the code, and I don't think it's documented behaviour.

I would prefer that in did an exists query, but since there are explicit
ways to force either behavior, in practise I use one of those explicit
ways, rather than leave the code looking ambiguous.

-- 
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: QuerySet: "if obj in queryset" can be very slow

2011-11-02 Thread Furbee
Thanks Tom, that's a great explanation!

Furbeenator

On Wed, Nov 2, 2011 at 10:46 AM, Tom Evans  wrote:

> On Wed, Nov 2, 2011 at 5:30 PM, Ian Clelland  wrote:
> > On Wed, Nov 2, 2011 at 8:25 AM, Thomas Guettler  wrote:
> >>
> >> # This is my current solution
> >> if get_special_objects().filter(pk=obj.pk).count():
> >># yes, it is special
> >>
> >
> > I can't speak to the "why" of this situation; it seems to me that this
> could
> > always be converted into a more efficient database query without any
> > unexpected side-effects (and if I really wanted the side effects, I would
> > just write "if obj in list(qs)" instead). In this case, though, I would
> > usually write something like this:
> > if get_special_objects().filter(pk=obj.pk).exists():
> ># yes, it is special
> > I believe that in some cases, the exists() query can be optimized to
> return
> > faster than a count() aggregation, and I think that the intent of the
> code
> > appears more clearly.
> > Ian
>
> OK, take this example. I have a django model table with 70 million
> rows in it. Doing any kind of query on this table is slow, and
> typically the query is date restrained - which mysql will use as the
> optimum key, meaning any further filtering is a table scan on the
> filtered rows.
>
> Pulling a large query (say, all logins in a month, ~1 million rows)
> takes only a few seconds longer than counting the number of rows the
> query would find - after all, the database still has to do precisely
> the same amount of work, it just doesn't have to deliver the data.
>
> Say I have a n entries I want to test are in that resultset, and I
> also want to iterate through the list, calculating some data and
> printing out the row, I can do the existence tests either in python or
> in the database. If I do it in the database, I have n+1 expensive
> queries to perform. If I do it in python, I have 1 expensive query to
> perform, and (worst case) n+1 full scans of the data retrieved (and I
> avoid locking the table for n+1 expensive queries).
>
> Depending on the size of the data set, as the developer I have the
> choice of which will be more appropriate for my needs. Sometimes I
> need "if qs.filter(pk=obj.pk).exists()", sometimes I need "if obj in
> qs".
>
> Cheers
>
> Tom
>
> --
> 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: Formwizard - Many2Many field - instance needs to have a primary key value before a many-to-many relationship can be used

2011-11-02 Thread Furbee
In your Customer model there are fields which cannot be Null, so you cannot
instance.save() before setting those properties. So, you may have to check
for the category field in your loop and if it is category, save the
instance first. Something like the following:

views.py (in clients application)
-
class InscriptionWizard(SessionWizardView):
   def done(self, form_list, **kwargs):
   instance = Customer()
   for form in form_list:
   for field, value in form.cleaned_data.iteritems():
   if field == 'category':
   instance.save()
   setattr(instance, field, value)
   instance.save()
-

This would of course depend on your ordering of the fields. In other words,
category would have to be the first Allow Null field in your model, because
you cannot save() until all Not Null fields have a value. If you cannot
order these fields so the category is last, you may have to do something
like:

views.py (in clients application)
-
class InscriptionWizard(SessionWizardView):
   def done(self, form_list, **kwargs):
   instance = Customer()
   for form in form_list:
   for field, value in form.cleaned_data.iteritems():
   if field != 'category':
   setattr(instance, field, value)
   instance.save()
   for form in form_list:
   for field, value in form.cleaned_data.iteritems():
   if field == 'category':
   setattr(instance, field, value)
-

I'm sure there is a MUCH more elegant way of getting just the categories
from the forms and field/value pairs, this is brute force (not very
scalable for large number of fields), but should work. Anybody else please,
show code that could get the specific forms and field/values for categories.

Furbeenator


On Wed, Nov 2, 2011 at 10:28 AM, youpsla  wrote:

> Hello,
> i'm currently doning a website where user can register (without
> password, without auth module of Django). They put some informations
> and at the end (Step5Form) do multiple choices by clicking on
> checkboxes. When I click on validate on the last step I've "instance
> needs to have a primary key value before a many-to-many relationship
> can be used" error. I've search the web to find a solution but . :-
> (
>
> Here is my code:
>
> models.py for Customer (in clients application)
> -
> class Customer (models.Model):
>
>email_adresse = models.EmailField(max_length=255, unique=True)
>some fields . for Step2 to Step4 of the form
>category = models.ManyToManyField(Categories)
> -
>
> models.py for categories (in categories application)
> -
> class Categories (models.Model):
>category = models.CharField(max_length=200)
>
>def __unicode__(self):
>return unicode(self.category)
> -
>
> The ManyToMany field has created(syncdb) a table
> clients_customer_category with the following columns:
>1   id  int(11)
> AUTO_INCREMENT
>2   customer_id int(11)
>3   categories_id   int(11)
>
>
> urls.py
> -
> urlpatterns = patterns('',
>(r'^clients/$', InscriptionWizard.as_view([Step1Form, Step2Form,
> Step3Form, Step4Form, Step5Form])),
> )
> -
>
>
> forms.py (in clients application)
> -
> from django import forms
> from clients.models import Customer
> from categories.models import Categories
>
> class Step1Form(forms.Form):
>email_adresse = forms.EmailField(max_length=255)
>
> class Step5Form(forms.Form):
>category =
> forms.ModelMultipleChoiceField(queryset=Categories.objects.all(),
> widget=forms.CheckboxSelectMultiple, required=True)
>
>
> views.py (in clients application)
> -
> class InscriptionWizard(SessionWizardView):
>def done(self, form_list, **kwargs):
>instance = Customer()
>for form in form_list:
>for field, value in form.cleaned_data.iteritems():
>setattr(instance, field, value)
>instance.save()
> -
>
> I got the following error:
> -
> Request Method: POST
> Request URL:http://127.0.0.1:8010/clients/
> Django Version: 1.3.1
> Exception Type: ValueError
> Exception Value:
> 'Customer' instance needs to have a primary key value before a many-to-
> many relationship can be used.
> ...
> ...
> ▶ Local vars
> C:\dev\Flash\clients\views.py in done
>

Re: QuerySet: "if obj in queryset" can be very slow

2011-11-02 Thread Tom Evans
On Wed, Nov 2, 2011 at 5:30 PM, Ian Clelland  wrote:
> On Wed, Nov 2, 2011 at 8:25 AM, Thomas Guettler  wrote:
>>
>> # This is my current solution
>> if get_special_objects().filter(pk=obj.pk).count():
>>    # yes, it is special
>>
>
> I can't speak to the "why" of this situation; it seems to me that this could
> always be converted into a more efficient database query without any
> unexpected side-effects (and if I really wanted the side effects, I would
> just write "if obj in list(qs)" instead). In this case, though, I would
> usually write something like this:
> if get_special_objects().filter(pk=obj.pk).exists():
>    # yes, it is special
> I believe that in some cases, the exists() query can be optimized to return
> faster than a count() aggregation, and I think that the intent of the code
> appears more clearly.
> Ian

OK, take this example. I have a django model table with 70 million
rows in it. Doing any kind of query on this table is slow, and
typically the query is date restrained - which mysql will use as the
optimum key, meaning any further filtering is a table scan on the
filtered rows.

Pulling a large query (say, all logins in a month, ~1 million rows)
takes only a few seconds longer than counting the number of rows the
query would find - after all, the database still has to do precisely
the same amount of work, it just doesn't have to deliver the data.

Say I have a n entries I want to test are in that resultset, and I
also want to iterate through the list, calculating some data and
printing out the row, I can do the existence tests either in python or
in the database. If I do it in the database, I have n+1 expensive
queries to perform. If I do it in python, I have 1 expensive query to
perform, and (worst case) n+1 full scans of the data retrieved (and I
avoid locking the table for n+1 expensive queries).

Depending on the size of the data set, as the developer I have the
choice of which will be more appropriate for my needs. Sometimes I
need "if qs.filter(pk=obj.pk).exists()", sometimes I need "if obj in
qs".

Cheers

Tom

-- 
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: QuerySet: "if obj in queryset" can be very slow

2011-11-02 Thread Ian Clelland
On Wed, Nov 2, 2011 at 8:25 AM, Thomas Guettler  wrote:

> # This is my current solution
> if get_special_objects().filter(pk=obj.pk).count():
># yes, it is special
>
>
I can't speak to the "why" of this situation; it seems to me that this
could always be converted into a more efficient database query without any
unexpected side-effects (and if I really wanted the side effects, I would
just write "if obj in list(qs)" instead). In this case, though, I would
usually write something like this:

if get_special_objects().filter(pk=obj.pk).*exists*():
   # yes, it is special

I believe that in some cases, the exists() query can be optimized to return
faster than a count() aggregation, and I think that the intent of the code
appears more clearly.

Ian

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



Formwizard - Many2Many field - instance needs to have a primary key value before a many-to-many relationship can be used

2011-11-02 Thread youpsla
Hello,
i'm currently doning a website where user can register (without
password, without auth module of Django). They put some informations
and at the end (Step5Form) do multiple choices by clicking on
checkboxes. When I click on validate on the last step I've "instance
needs to have a primary key value before a many-to-many relationship
can be used" error. I've search the web to find a solution but . :-
(

Here is my code:

models.py for Customer (in clients application)
-
class Customer (models.Model):

email_adresse = models.EmailField(max_length=255, unique=True)
some fields . for Step2 to Step4 of the form
category = models.ManyToManyField(Categories)
-

models.py for categories (in categories application)
-
class Categories (models.Model):
category = models.CharField(max_length=200)

def __unicode__(self):
return unicode(self.category)
-

The ManyToMany field has created(syncdb) a table
clients_customer_category with the following columns:
1   id  int(11) 
AUTO_INCREMENT
2   customer_id int(11)
3   categories_id   int(11)


urls.py
-
urlpatterns = patterns('',
(r'^clients/$', InscriptionWizard.as_view([Step1Form, Step2Form,
Step3Form, Step4Form, Step5Form])),
)
-


forms.py (in clients application)
-
from django import forms
from clients.models import Customer
from categories.models import Categories

class Step1Form(forms.Form):
email_adresse = forms.EmailField(max_length=255)

class Step5Form(forms.Form):
category =
forms.ModelMultipleChoiceField(queryset=Categories.objects.all(),
widget=forms.CheckboxSelectMultiple, required=True)


views.py (in clients application)
-
class InscriptionWizard(SessionWizardView):
def done(self, form_list, **kwargs):
instance = Customer()
for form in form_list:
for field, value in form.cleaned_data.iteritems():
setattr(instance, field, value)
instance.save()
-

I got the following error:
-
Request Method: POST
Request URL:http://127.0.0.1:8010/clients/
Django Version: 1.3.1
Exception Type: ValueError
Exception Value:
'Customer' instance needs to have a primary key value before a many-to-
many relationship can be used.
...
...
▶ Local vars
C:\dev\Flash\clients\views.py in done
setattr(instance, field, value) ...
-


What I've tried:
1)I've search the web and didn't find any way to solve this. I've read
on save_m2m() wich doesn't apply here as far I understand because no
"commit=False" and this form is not a ModelForm.


2)I've trie to save in 2 steps with the hope an id has been set in the
DB:
-First step : for form in form_list[0:3]: .. instance.save()
-Second step :
for form in form_list[4]:
for field, value in form.cleaned_data.iteritems():
instance.category.add(value)

I've the following error : 'BoundField' object has no attribute
'cleaned_data' for the line "for field, value in
form.cleaned_data.iteritems():" in Second step.


Then I can maybe split my form in 2 forms, one from Step0 to Step3 and
another one for Step4 and passing the id_customer in teh session but
maybe there is a solution to solve this issue in one form.


Help will be really appreciated.

I apologize if my explanations are not enough clear (and for my
english) and feel free to ask informations.

Regards

Alain




-- 
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: Problems with jquery and accessing django template system

2011-11-02 Thread Tom Evans
n Wed, Nov 2, 2011 at 5:13 PM, Kevin Miller  wrote:
> I have a url that I need to attach to link that is in a jquery
> section. It seem like the django template system is not getting the
> variable. For example:
>
> $.each(event,function(index,value){
>                        var url = "{% url fiesta.views.detail "+
> event[index].pk +"  %}"

It gets the variable alright - the variable is the raw string "+
event[index].pk + ". Template rendering happens before the javascript
runs.

An option is to hardcode an id into the generated URL, and then replace it:

var url = "{% url fiesta.views.detail 999 %}";
url = url.replace('999', event[index].pk);


Cheers

Tom

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



Problems with jquery and accessing django template system

2011-11-02 Thread Kevin Miller
I have a url that I need to attach to link that is in a jquery
section. It seem like the django template system is not getting the
variable. For example:

$.each(event,function(index,value){
var url = "{% url fiesta.views.detail "+
event[index].pk +"  %}"

$('#event_results').append(
'' + event[index].fields.title +
'' + event[index].fields.description + ''
)

});

},


"json"
);

--PROBLEM
I need this url to be formatted like: {% url fiesta.view.detail 1 %}
Where the number 1 would replace the event[index].pk
However, it keeps printing the text: "event[index].pk" instead of the
value. I have checked that the variable is returning values and it is
returning values outside of django template blocks.

I don't know, but it seems that the django template is reading the
data before it is evaluated by jquery/javascript.

 How can I format the django template so that i can evaluate jquery variables.



Thanks.

regard,
Kevin

-- 
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: Onchange event on Choicefield in django formset

2011-11-02 Thread Kurtis Mullins
Whoops, sorry -- I didn't realize you weren't using CBVs. :)

On Wed, Nov 2, 2011 at 12:43 PM, Furbee  wrote:

> I think your 'answer' is going to exist in POST in either case. Perhaps
> change the construct of your logic to:
>
> if 'evaluation' in request.POST:
> return render_to_response('results.html')
> elif 'form-0-answer' in request.POST:
>
> answer = request.POST.get('answer','')
> values.append(answer)
> return render_to_response('success.html')
>
> Furbeenator
>
>
> On Wed, Nov 2, 2011 at 9:21 AM, Kurtis Mullins 
> wrote:
>
>> Try changing your success_url to this same page.
>>
>>
>> On Wed, Nov 2, 2011 at 11:00 AM, asif.jama...@rezayat.net <
>> asif.jama...@rezayat.net> wrote:
>>
>>> How can i access the form fields in django views.
>>>
>>> Suppose i have modelform called
>>>
>>>
>>> class QuestionForm(forms.ModelForm):
>>>
>>>
>>>  answer = forms.ChoiceField(choices=HAY_EVALUATION_CHOICES,
>>>
>>> widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
>>>
>>>
>>> In views.py
>>>
>>>
>>>  if 'form-0-answer' in request.POST:
>>>
>>>
>>>answer = request.POST.get('answer','')
>>>
>>>
>>>values.append(answer)
>>>
>>>
>>>return render_to_response('success.html')
>>>
>>>
>>> if 'evaluation' in request.POST:
>>>
>>> return render_to_response('results.html')
>>>
>>> The form consist of one submit button called 'evaluation' and second
>>> is having onchange event on selection
>>>
>>> Here i'm trying to perform some operation on selection, then by using
>>> second button that is 'evaluation' i will save the form.
>>>
>>> Here the problem is the form is always redirecting to success.html
>>> even when i click 'evaluation' button
>>>
>>>
>>>
>>> --
>>> 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.
>>
>
>  --
> 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: Calling Python from JavaScript

2011-11-02 Thread Furbee
You could call the Dajaxice method that gets the result (the one that fires
when the drop down changes) with window.onload, or you could pass the
initial values to the template via the view. For consistency and code
reuse, I would personally use the first method, calling the Dajaxice
function responsible for calculating the result with window.onload. If the
method is currently accepting the drop-down's value as an argument, you
would have to change it to actively find the selected values of the
drop-downs manually from the javascript function.

Furbeenator

On Wed, Nov 2, 2011 at 2:31 AM, asif  wrote:

> I will explain what i'm trying to achieve, I'm using Dajaxice with
> Django.
>
> I created modelformset which consist of multiple forms. Each form has
> dropdown field on which I'm calling dajaxice function, that function
> will takes the value of the dropdown field and calls another python
> function which calculates the total sum of all the values of dropdown
> fields. Here my formset has initial values. So I want to call that
> python function (which calculates result ) in javascript code (This
> javascript function is for dajaxice )
>
>
> Regards
>
> Asif
>
> --
> 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: Field available via Django shell but not via web application (crossposted from StackOverFlow)

2011-11-02 Thread Furbee
You said you are using django.contrib.auth.models.User as your User model,
but that doesn't have a "foos" property. Can you share the models that you
are using? Are you creating a subclass User that extends
django.contrib.auth.models.User and adds foos and a ForeignKey? Is foos a
ManyToManyField, OneToOneField, or just a ForeignKey to a Foos model which
has a name property?

Thanks,

Furbeenator

On Wed, Nov 2, 2011 at 8:27 AM, Jordan  wrote:

> Yes, it does work in runserver, as might be expected since runserver
> uses exact same environment as the shell.
>
> So that established, how can I fix it?
>
> On Nov 1, 9:04 pm, Andy McKay  wrote:
> > Is this using the Django built in runserver or some other way of serving
> > pages? If not try using runserver.
>
> --
> 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: Onchange event on Choicefield in django formset

2011-11-02 Thread Furbee
I think your 'answer' is going to exist in POST in either case. Perhaps
change the construct of your logic to:

if 'evaluation' in request.POST:
return render_to_response('results.html')
elif 'form-0-answer' in request.POST:
answer = request.POST.get('answer','')
values.append(answer)
return render_to_response('success.html')

Furbeenator


On Wed, Nov 2, 2011 at 9:21 AM, Kurtis Mullins wrote:

> Try changing your success_url to this same page.
>
>
> On Wed, Nov 2, 2011 at 11:00 AM, asif.jama...@rezayat.net <
> asif.jama...@rezayat.net> wrote:
>
>> How can i access the form fields in django views.
>>
>> Suppose i have modelform called
>>
>>
>> class QuestionForm(forms.ModelForm):
>>
>>
>>  answer = forms.ChoiceField(choices=HAY_EVALUATION_CHOICES,
>>
>> widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
>>
>>
>> In views.py
>>
>>
>>  if 'form-0-answer' in request.POST:
>>
>>
>>answer = request.POST.get('answer','')
>>
>>
>>values.append(answer)
>>
>>
>>return render_to_response('success.html')
>>
>>
>> if 'evaluation' in request.POST:
>>
>> return render_to_response('results.html')
>>
>> The form consist of one submit button called 'evaluation' and second
>> is having onchange event on selection
>>
>> Here i'm trying to perform some operation on selection, then by using
>> second button that is 'evaluation' i will save the form.
>>
>> Here the problem is the form is always redirecting to success.html
>> even when i click 'evaluation' button
>>
>>
>>
>> --
>> 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.
>

-- 
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 + Ajax/Javascript

2011-11-02 Thread Furbee
You could pass the values from the view to the template and use javascript
(I would suggest using jQuery) if there are only a few options. I would
suggest using Dajax (dajaxproject.com) for your AJAX commands. It is really
easy to plug into Django, and you should get familiar with it and the
jQuery javascript framework. They work very well for making the UI fun and
easy. There is also jQuery-UI which builds on the jQuery library with tons
more user interface options, like calendar pickers, sliders, etc. Good
stuff! :-)

Furbeenator

On Wed, Nov 2, 2011 at 5:42 AM, Felix Wagner wrote:

> Hi,
>
> I have the following model layout:
>
> class A(models.model):
>options = models.ManyToManyField(OptionSet, blank=True, null=True)
>values = models.ManyToManyField(Value, blank=True, null=True)
>
> class OptionSet(models.model):
>name = models.TextField(unique=True)
>values = models.ManyToManyField(Value)
>
>def __unicode__(self):
>return '%s' % self.name
>
> class Value(models.Model):
>name = models.TextField()
>key = models.ForeignKey(Key, related_name='values')
>
> class Key(models.Model):
>name = models.TextField(unique=True)
>
> And my forms.py looks like this:
>
> class A_Form(ModelForm):
>values =
> forms.ModelMultipleChoiceField(queryset=Value.objects.all(),
> widget=CheckboxSelectMultiple, label="Einzelne Werte", required=False)
>options =
> forms.ModelMultipleChoiceField(queryset=OptionSet.objects.all(),
> widget=CheckboxSelectMultiple, label="Optionen Sets", required=False)
>
> Template:
>
> {% csrf_token %}
>{{ form.as_table }}
>
> 
>
> I use that form with a generic update view! I'm new to javascript/ajax
> to be honest never did something in javascript/ajax. What I want to do
> is on mouseover on the options name it should show all the values for
> that option set. How would one accomplish this (either with or without
> ajax)?
>
> --
> 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: Onchange event on Choicefield in django formset

2011-11-02 Thread Kurtis Mullins
Try changing your success_url to this same page.

On Wed, Nov 2, 2011 at 11:00 AM, asif.jama...@rezayat.net <
asif.jama...@rezayat.net> wrote:

> How can i access the form fields in django views.
>
> Suppose i have modelform called
>
>
> class QuestionForm(forms.ModelForm):
>
>
>  answer = forms.ChoiceField(choices=HAY_EVALUATION_CHOICES,
>
> widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
>
>
> In views.py
>
>
>  if 'form-0-answer' in request.POST:
>
>
>answer = request.POST.get('answer','')
>
>
>values.append(answer)
>
>
>return render_to_response('success.html')
>
>
> if 'evaluation' in request.POST:
>
> return render_to_response('results.html')
>
> The form consist of one submit button called 'evaluation' and second
> is having onchange event on selection
>
> Here i'm trying to perform some operation on selection, then by using
> second button that is 'evaluation' i will save the form.
>
> Here the problem is the form is always redirecting to success.html
> even when i click 'evaluation' button
>
>
>
> --
> 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: Set of choices of which several can be chosen without using a ManyToManyField

2011-11-02 Thread Tom Evans
On Wed, Nov 2, 2011 at 12:15 PM, Jaroslav Dobrek
 wrote:
> I now use ManyToManyFields and hide certain data from administrators
> by simply not importing them into admin.py. What I don't like about
> this solution is that this data still is in the database and not in my
> source code. In my view, it should be part of the source code, because
> it is part of the program logic: Any instance of my program is
> supposed to use these data, independently of any other set of data it
> might use. Much as any instance of a program that uses the notion of
> gender should have the genders "male" and "female". Administrators
> should not have to or be able to manipulate gender objects.
>

As you've alluded to, you can control this by not giving them
interfaces to adjust those items.

With respect to the data being constant and unchanging, this makes it
ideally suited to become part of a initial_data fixture, that will
automatically be loaded into the database when an app is synched to
the database. This fixture then becomes a part of your source code.

https://docs.djangoproject.com/en/1.3/howto/initial-data/#providing-initial-data-with-fixtures

Cheers

Tom

-- 
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: QuerySet: "if obj in queryset" can be very slow

2011-11-02 Thread Tom Evans
On Wed, Nov 2, 2011 at 3:25 PM, Thomas Guettler  wrote:
> Here is a better example:
>
> def get_special_objects():
>    # Some are special. But the result can still be huge!
>    return MyModel.objects.filter()
>
> obj=MyModel.objects.get()
>
> # is this object "special?"
> if obj in get_special_objects(): # This is very slow if there are many rows 
> in the result.
>    # yes, it is special
>
> # This is my current solution
> if get_special_objects().filter(pk=obj.pk).count():
>    # yes, it is special
>
>
> Up to now I sometimes used "if obj in queryset" but never realized, that
> this evaluates the whole queryset. Up to now I thought this is lazy.
>
> I have no big problem with this, since I found a solution.
>
> Is there a reason why "if obj in queryset" is executed in python code, and not
> in the DB?
>
>  Thomas
>
>

Choice and consistency.

You've picked an edge case where it does make more sense to query the
database, however I could contrive any number of examples where it
would be wrong to filter in the database, for example if I had a long
list of objects I wanted to test are in the queryset AND I wanted the
items in the queryset constructed anyway, I'd use the 'in' operator.
This is the choice.

For consistency, querying the database is performed by methods on a
model's manager class or related queryset, where as python functions
operating on a queryset do not perform database queries. Eg, len(qs)
evaluates the queryset and counts the number of instances in the
queryset using python, where as qs.count() performs a DB query to
obtain the result. Neither is wrong, they are appropriate in different
cases.

Cheers

Tom

-- 
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: Field available via Django shell but not via web application (crossposted from StackOverFlow)

2011-11-02 Thread Jordan
Yes, it does work in runserver, as might be expected since runserver
uses exact same environment as the shell.

So that established, how can I fix it?

On Nov 1, 9:04 pm, Andy McKay  wrote:
> Is this using the Django built in runserver or some other way of serving
> pages? If not try using runserver.

-- 
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: QuerySet: "if obj in queryset" can be very slow

2011-11-02 Thread Thomas Guettler
Here is a better example:

def get_special_objects():
# Some are special. But the result can still be huge!
return MyModel.objects.filter()

obj=MyModel.objects.get()

# is this object "special?"
if obj in get_special_objects(): # This is very slow if there are many rows in 
the result.
# yes, it is special

# This is my current solution
if get_special_objects().filter(pk=obj.pk).count():
# yes, it is special


Up to now I sometimes used "if obj in queryset" but never realized, that
this evaluates the whole queryset. Up to now I thought this is lazy.

I have no big problem with this, since I found a solution.

Is there a reason why "if obj in queryset" is executed in python code, and not
in the DB?

  Thomas



Am 02.11.2011 12:42, schrieb Thomas Guettler:
> Hi,
> 
> I just discovered, that "if obj in queryset" can be very slow:
> 
> queryset=MyModel.objects.all()
> obj=MyModel.objects.get(id=319526)
> 
> #if obj in queryset: # This is very slow, if queryset is big: All lines from 
> queryset get created to Python objects
> #print 'in'
> 
> if queryset.filter(id=obj.id): # Fast: Check is done inside DB.
> print 'in'
> 
> What is the best way to do "if obj in queryset"?
> 
>   Thomas
> 

-- 
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de

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



Onchange event on Choicefield in django formset

2011-11-02 Thread asif.jama...@rezayat.net
How can i access the form fields in django views.

Suppose i have modelform called


class QuestionForm(forms.ModelForm):


 answer = forms.ChoiceField(choices=HAY_EVALUATION_CHOICES,
 
widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))


In views.py


  if 'form-0-answer' in request.POST:


answer = request.POST.get('answer','')


values.append(answer)


return render_to_response('success.html')


 if 'evaluation' in request.POST:

 return render_to_response('results.html')

The form consist of one submit button called 'evaluation' and second
is having onchange event on selection

Here i'm trying to perform some operation on selection, then by using
second button that is 'evaluation' i will save the form.

Here the problem is the form is always redirecting to success.html
even when i click 'evaluation' button



-- 
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: "python manage.py runserver" creates not tables (tutorial)

2011-11-02 Thread Martin Chiteri
What about if you do a

python manage.py sqlall

>From the settings file, I do not see any of your apps added in the
list of installed apps, like

INSTALLED_APPS = (
   'django.contrib.auth',
   'mysite.news',
.,
)

Martin.

-- 
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 aggregation does excessive GROUP BY clauses

2011-11-02 Thread christian.oudard
Opened a bug:

https://code.djangoproject.com/ticket/17144

I think I might take a crack at fixing this one.

On Nov 1, 9:06 pm, Karen Tracey  wrote:
> On Tue, Nov 1, 2011 at 6:19 PM, christian.oudard 
>
>
>
>
>
>
>
>
> > wrote:
> > I am doing a very simple aggregation using the Django ORM, and it is
> > producing a GROUP BY clause that includes the data field, which is
> > very large, and is slowing down the query by over 100-fold.
>
> > Here is a simplified version of the model:
>
> > class Document(models.Model):
> >    data = models.TextField()
>
> > class Attachment(models.Model):
> >    document = models.ForeignKey(Document)
>
> > And the query I am running:
>
> > Document.objects.annotate(num_attachments=Count('attachment'))
>
> The SQL generated by the ORM for this query changed between Django version
> 1.2 and 1.3. The 1.2 SQL did a group by only on the id field. With 1.3
> we're getting id twice and then all other fields in the model. Bisection
> shows the change was made with r14715:
>
> https://code.djangoproject.com/changeset/14715
>
> It certainly looks to me like the old SQL was correct and preferable for
> this particular case. In a brief search I did not find a ticket reporting
> this issue -- could you open one?
>
> Karen
> --http://tracey.org/kmt/

-- 
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: QuerySet: "if obj in queryset" can be very slow

2011-11-02 Thread Jirka Vejrazka
> queryset=MyModel.objects.all()
> obj=MyModel.objects.get(id=319526)

Thomas,

  if the second line works for you (i.e. does not raise
MyModel.DoesNotExist exception), then obj is in queryset by
definition.

  What are you trying to achieve?

   Jirka

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



Onchange attribute for mdelformset

2011-11-02 Thread asif
How can i access the form in django views.

Suppose

Modelform

class QuestionForm(forms.ModelForm):

 answer = forms.ChoiceField(choices=HAY_EVALUATION_CHOICES,
widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))


In views.py

  if 'form-0-answer' in request.POST:

answer = request.POST.get('answer','')

values.append(answer)

return render_to_response('success.html')

 if 'evaluation' in request.POST:

 return render_to_response('results.html')



Here 'evaluation' name of Submit button

Here the problem is the form is always redirecting to success.html
even i click submit button






-- 
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 + Ajax/Javascript

2011-11-02 Thread Felix Wagner
Hi,

I have the following model layout:

class A(models.model):
options = models.ManyToManyField(OptionSet, blank=True, null=True)
values = models.ManyToManyField(Value, blank=True, null=True)

class OptionSet(models.model):
name = models.TextField(unique=True)
values = models.ManyToManyField(Value)

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

class Value(models.Model):
name = models.TextField()
key = models.ForeignKey(Key, related_name='values')

class Key(models.Model):
name = models.TextField(unique=True)

And my forms.py looks like this:

class A_Form(ModelForm):
values =
forms.ModelMultipleChoiceField(queryset=Value.objects.all(),
widget=CheckboxSelectMultiple, label="Einzelne Werte", required=False)
options =
forms.ModelMultipleChoiceField(queryset=OptionSet.objects.all(),
widget=CheckboxSelectMultiple, label="Optionen Sets", required=False)

Template:

{% csrf_token %}
{{ form.as_table }}



I use that form with a generic update view! I'm new to javascript/ajax
to be honest never did something in javascript/ajax. What I want to do
is on mouseover on the options name it should show all the values for
that option set. How would one accomplish this (either with or without
ajax)?

-- 
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: "python manage.py syncdb" creates no tables (tutorial)

2011-11-02 Thread angelika
Well, here I am, confessing my stupidity to the internet. Like I said,
I'm new to both Python and Django. I've been trying to run the
commands in the same terminal window where I ran the 'python manage.py
runserver'. When I run it in a separate window, it all works as
expected. The tables are created.

Sorry for taking up your time.
Until next time,
/Angelika

On Nov 2, 1:12 pm, Flavia Missi  wrote:
> You do not need to run syncdb before creating your first app, syncdb search
> for the apps in INSTALLED_APPS and sync their models with the database, so
> you can run it anytime. Note that if you just change an existing model
> syncdb won't sync anything, you'll need migrations for that.
>
> []'s
>
>
>
>
>
>
>
>
>
> On Wed, Nov 2, 2011 at 9:59 AM, angelika  wrote:
> > I'm following the tutorial on this page:
> >https://docs.djangoproject.com/en/1.3/intro/tutorial01/
>
> > In it, the 'python manage.py syncdb' command is supposed to be run to
> > create tables for the apps in the INSTALLED_APPS setting, right? And
> > this bit seems to come before you start creating an app. Or have I
> > misunderstood it?
>
> > /Angelika
>
> > On Nov 2, 12:46 pm, kenneth gonsalves  wrote:
> > > On Wed, 2011-11-02 at 04:37 -0700, angelika wrote:
> > > > I'm new to both Python and Django. I'm doing the tutorial and I named
> > > > the site mysite, to keep it simple. Does that mean mysite is the name
> > > > of the app? And the command should be:
>
> > > you must have created an app under mysite - probably named 'polls' under
> > > which you have your models.py and views.py etc
>
> > > > from mysite import *
>
> > > go to the mysite directory and type
> > > python manage.py shell
>
> > > the python shell will appear. Then type:
>
> > > from polls import *
>
> > > (this assumes that you have an app named polls, and that you have
> > > populated your models.py)
>
> > > --
> > > regards
> > > Kenneth Gonsalves
>
> > --
> > 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.
>
> --
> Flávia Missi
> @flaviamissi 
> flaviamissi.com.brhttps://github.com/flaviamissi

-- 
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: Set of choices of which several can be chosen without using a ManyToManyField

2011-11-02 Thread Jaroslav Dobrek


On 1 Nov., 18:54, Mark Furbee  wrote:
> As alluded to previously, the most "straightforward way to use a set of
> choices of which several can be chosen" IS to use a ManyToManyField. The
> syntax is slightly different, but ManyToManyFields are really easy to use
> with Django. Do not reinvent the wheel in this case.

I am not against ManyToManyFields. Yet, in certain cases (which are
actually more complicated than the (invented) Candidate/language
example), I would like to not create certain data as objects that can
be seen, modified, created and deleted by administrators.
Administrators should only see those data which they are supposed to
manipulate. That is why I wanted to have the possibility to "hardwire"
certain data in my source code in the same way as data is hardwired in
the source code with the "choices=" solution that can be used with
CharField.

I now use ManyToManyFields and hide certain data from administrators
by simply not importing them into admin.py. What I don't like about
this solution is that this data still is in the database and not in my
source code. In my view, it should be part of the source code, because
it is part of the program logic: Any instance of my program is
supposed to use these data, independently of any other set of data it
might use. Much as any instance of a program that uses the notion of
gender should have the genders "male" and "female". Administrators
should not have to or be able to manipulate gender objects.

Thanks to all who participated in this thread.

-- 
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: "python manage.py syncdb" creates no tables (tutorial)

2011-11-02 Thread Flavia Missi
You do not need to run syncdb before creating your first app, syncdb search
for the apps in INSTALLED_APPS and sync their models with the database, so
you can run it anytime. Note that if you just change an existing model
syncdb won't sync anything, you'll need migrations for that.

[]'s

On Wed, Nov 2, 2011 at 9:59 AM, angelika  wrote:

> I'm following the tutorial on this page:
> https://docs.djangoproject.com/en/1.3/intro/tutorial01/
>
> In it, the 'python manage.py syncdb' command is supposed to be run to
> create tables for the apps in the INSTALLED_APPS setting, right? And
> this bit seems to come before you start creating an app. Or have I
> misunderstood it?
>
> /Angelika
>
> On Nov 2, 12:46 pm, kenneth gonsalves  wrote:
> > On Wed, 2011-11-02 at 04:37 -0700, angelika wrote:
> > > I'm new to both Python and Django. I'm doing the tutorial and I named
> > > the site mysite, to keep it simple. Does that mean mysite is the name
> > > of the app? And the command should be:
> >
> > you must have created an app under mysite - probably named 'polls' under
> > which you have your models.py and views.py etc
> >
> >
> >
> > > from mysite import *
> >
> > go to the mysite directory and type
> > python manage.py shell
> >
> > the python shell will appear. Then type:
> >
> > from polls import *
> >
> > (this assumes that you have an app named polls, and that you have
> > populated your models.py)
> >
> > --
> > regards
> > Kenneth Gonsalves
>
> --
> 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.
>
>


-- 
Flávia Missi
@flaviamissi 
flaviamissi.com.br
https://github.com/flaviamissi

-- 
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: "python manage.py syncdb" creates no tables (tutorial)

2011-11-02 Thread kenneth gonsalves
On Wed, 2011-11-02 at 04:59 -0700, angelika wrote:
> I'm following the tutorial on this page:
> https://docs.djangoproject.com/en/1.3/intro/tutorial01/
> 
> In it, the 'python manage.py syncdb' command is supposed to be run to
> create tables for the apps in the INSTALLED_APPS setting, right? And
> this bit seems to come before you start creating an app. Or have I
> misunderstood it? 

*after* creating the app and adding at least *one* model.
-- 
regards
Kenneth Gonsalves

-- 
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: "python manage.py syncdb" creates no tables (tutorial)

2011-11-02 Thread angelika
I'm following the tutorial on this page:
https://docs.djangoproject.com/en/1.3/intro/tutorial01/

In it, the 'python manage.py syncdb' command is supposed to be run to
create tables for the apps in the INSTALLED_APPS setting, right? And
this bit seems to come before you start creating an app. Or have I
misunderstood it?

/Angelika

On Nov 2, 12:46 pm, kenneth gonsalves  wrote:
> On Wed, 2011-11-02 at 04:37 -0700, angelika wrote:
> > I'm new to both Python and Django. I'm doing the tutorial and I named
> > the site mysite, to keep it simple. Does that mean mysite is the name
> > of the app? And the command should be:
>
> you must have created an app under mysite - probably named 'polls' under
> which you have your models.py and views.py etc
>
>
>
> > from mysite import *
>
> go to the mysite directory and type
> python manage.py shell
>
> the python shell will appear. Then type:
>
> from polls import *
>
> (this assumes that you have an app named polls, and that you have
> populated your models.py)
>
> --
> regards
> Kenneth Gonsalves

-- 
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: QuerySet: "if obj in queryset" can be very slow

2011-11-02 Thread Flavia Missi
That's because your queryset is being evaluated when you compare, maybe if
you explain your problem, we can give you a better solution than the use of
`in`.

Take a look at the docs about when querysets are evaluated:

https://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated

[]'s

On Wed, Nov 2, 2011 at 9:42 AM, Thomas Guettler  wrote:

> Hi,
>
> I just discovered, that "if obj in queryset" can be very slow:
>
> queryset=MyModel.objects.all()
> obj=MyModel.objects.get(id=319526)
>
> #if obj in queryset: # This is very slow, if queryset is big: All lines
> from queryset get created to Python objects
> #print 'in'
>
> if queryset.filter(id=obj.id): # Fast: Check is done inside DB.
>print 'in'
>
> What is the best way to do "if obj in queryset"?
>
>  Thomas
>
> --
> Thomas Guettler, http://www.thomas-guettler.de/
> E-Mail: guettli (*) thomas-guettler + de
>
> --
> 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.
>
>


-- 
Flávia Missi
@flaviamissi 
flaviamissi.com.br
https://github.com/flaviamissi

-- 
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: "python manage.py syncdb" creates no tables (tutorial)

2011-11-02 Thread kenneth gonsalves
On Wed, 2011-11-02 at 04:37 -0700, angelika wrote:
> I'm new to both Python and Django. I'm doing the tutorial and I named
> the site mysite, to keep it simple. Does that mean mysite is the name
> of the app? And the command should be:

you must have created an app under mysite - probably named 'polls' under
which you have your models.py and views.py etc
> 
> from mysite import *

go to the mysite directory and type 
python manage.py shell

the python shell will appear. Then type:

from polls import *

(this assumes that you have an app named polls, and that you have
populated your models.py)
> 
> 
-- 
regards
Kenneth Gonsalves

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



QuerySet: "if obj in queryset" can be very slow

2011-11-02 Thread Thomas Guettler
Hi,

I just discovered, that "if obj in queryset" can be very slow:

queryset=MyModel.objects.all()
obj=MyModel.objects.get(id=319526)

#if obj in queryset: # This is very slow, if queryset is big: All lines from 
queryset get created to Python objects
#print 'in'

if queryset.filter(id=obj.id): # Fast: Check is done inside DB.
print 'in'

What is the best way to do "if obj in queryset"?

  Thomas

-- 
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de

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



Calling Python from JavaScript

2011-11-02 Thread asif
I will explain what i'm trying to achieve, I'm using Dajaxice with
Django.

I created modelformset which consist of multiple forms. Each form has
dropdown field on which I'm calling dajaxice function, that function
will takes the value of the dropdown field and calls another python
function which calculates the total sum of all the values of dropdown
fields. Here my formset has initial values. So I want to call that
python function (which calculates result ) in javascript code (This
javascript function is for dajaxice )


Regards

Asif

-- 
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: Set of choices of which several can be chosen without using a ManyToManyField

2011-11-02 Thread Mark Furbee
As alluded to previously, the most "straightforward way to use a set of
choices of which several can be chosen" IS to use a ManyToManyField. The
syntax is slightly different, but ManyToManyFields are really easy to use
with Django. Do not reinvent the wheel in this case.

Thanks,

Mark Furbee


On Tue, Nov 1, 2011 at 7:49 AM, J. Cliff Dyer  wrote:

> On 11/01/2011 09:05 AM, Jaroslav Dobrek wrote:
>
>> You are confusing model fields with form fields. MultipleChoiceField
>>> is a form field, not a model field.
>>>
>> I wasn't aware of the existence of MultipleChoiceFields. The idea of
>> the above code was to express that I wanted to use this code
>>
>> class Candidate(models.Model):
>>
>> programming_languages = models.CharField(max_length=**50, choices=(
>>
>> (u'Python)', u'Python'),
>> (u'C++', u'C++'),
>> (u'Java', u'Java'),
>> # ...
>> ), blank=True)
>>
>> with the only exception that, in the admin interface, several choices
>> are possible when one creates a new candidate object. I.e. I want
>> admins to be able to create a candidate that knows, say Python *and* C+
>> + by choosing both of these languages during the creation of the
>> object. I used the string "MultipleChoiceField" as a dummy for
>> whatever should be used instead.
>>
>> Jaroslav
>>
>>
>>
>>
>>
>>
>>  If you want a field that will be represented by a MultipleChoiceField
>>> in model, you simply need to define 'choices' on a field class.
>>>
>>> https://docs.djangoproject.**com/en/1.3/ref/models/fields/#**choices
>>>
>>> Cheers
>>>
>>> Tom
>>>
>> Still, you want to control the input at the form level, not the model
> level.  Create a ModelForm for your Candidate, but override the language
> field to take a MultipleChoiceField, and then override the __init__() and
> save() methods to handle them properly.  "Properly," of course, is
> determined by your application, and how you want to store the information
> in the database.  You could choose to store it in a CharField as a comma
> separated list of language names, or in an IntegerField as a bit field (0x1
> = 'Python', 0x2 = 'Perl', 0x4 = PHP, so 0x5 means the user knows Python and
> PHP, but not Perl).  The latter is a more efficient way to store the data,
> but the former is arguably more human-friendly.
>
> Ultimately, though, it seems that you are adding complexity rather than
> removing it.  This is exactly what many to many relationships are designed
> to handle.  If you want to use another method, you have to figure out the
> details for yourself.
>
> Cheers,
> Cliff
>
>
> --
> 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+unsubscribe@**
> 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: "python manage.py runserver" creates not tables (tutorial)

2011-11-02 Thread angelika
Thanks, Kenneth.

I'm new to both Python and Django. I'm doing the tutorial and I named
the site mysite, to keep it simple. Does that mean mysite is the name
of the app? And the command should be:

from mysite import *

I did that, but nothing happened. Same as with 'python manage.py
runserver'. No messages, no errors, nothing.

/Angelika

On Nov 2, 11:43 am, kenneth gonsalves  wrote:
> On Wed, 2011-11-02 at 02:47 -0700, angelika wrote:
> > Christ, I totally messed up this post. I did not mean "python
> > manage.py runserver" but "python manage.py syncdb". That is the
> > command that does not create any tables. Sorry.
>
> https://code.djangoproject.com/ticket/11494- it may be due to this. To
> check it out go to the shell and try:
>
> from yourapp import * - if it fails, fix the import error and try syncdb
> again.
>
> --
> regards
> Kenneth Gonsalves

-- 
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: tutorial error

2011-11-02 Thread rihad


On Nov 2, 1:29 pm, Daniel Roseman  wrote:
> On Wednesday, 2 November 2011 07:24:39 UTC, rihad wrote:
>
> > render_to_response('polls/detail.html', {'poll': p})


Oops, of course this has no relation to URLs, it's just a filepath :)

-- 
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: tutorial error

2011-11-02 Thread rihad


On Nov 2, 1:29 pm, Daniel Roseman  wrote:
> On Wednesday, 2 November 2011 07:24:39 UTC, rihad wrote:
>
> > It says at the end of part 3 of the Django tutorial:
>
> > "The idea behind include() and URLconf decoupling is to make it easy
> > to plug-and-play URLs. Now that polls are in their own URLconf, they
> > can be placed under "/polls/", or under "/fun_polls/", or under "/
> > content/polls/", or any other path root, and the app will still work."
>
> > It's actually not that simple. Simply changing the project-wide
> > URLconf prefix from '^polls/' to '^fun_polls/' will not work, because
> > the code referencing templates still has polls in its path:
> > render_to_response('polls/detail.html', {'poll': p})
> > or in URLs:
> > {{ poll.question }}
>
> Your first point is simply not true. Changing the urlconf prefix does not
> in any way affect how you reference the template path. You could prefix the
> polls URLs with 'foobar', but the template path would still be 'polls'.
>
> The second point is made irrelevant by something that's not covered in the
> tutorial, but is mentioned in the actual documentation for URLs: you should
> never hard-code URLs, you should use the `{% url %}` tag in templates or
> the `reverse()` function in views - for precisely this reason.
> --

Thanks, now I see.

p.s.: don't know where you saw two points. All I meant was that simply
changing /polls/ to /fun_polls/ will not work with the code examples
given up to that point in the tutorial, as implied by it, precisely
because URLs in the app are coupled to urlpatterns. The second part
seems to be the answer, though.

-- 
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: "python manage.py runserver" creates not tables (tutorial)

2011-11-02 Thread kenneth gonsalves
On Wed, 2011-11-02 at 02:47 -0700, angelika wrote:
> Christ, I totally messed up this post. I did not mean "python
> manage.py runserver" but "python manage.py syncdb". That is the
> command that does not create any tables. Sorry.
> 
> 
https://code.djangoproject.com/ticket/11494 - it may be due to this. To
check it out go to the shell and try:

from yourapp import * - if it fails, fix the import error and try syncdb
again.

-- 
regards
Kenneth Gonsalves

-- 
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: No module named django after upgrade to os x Lion

2011-11-02 Thread angelika
Thanks a million, Kurtis! I followed your advice and I no longer get
any errors when I run "python manage.py runserver". Hurray :) !

I'll probably give PostgreSQL a try once I've got the hang of python
and django a bit more, since you were all so positive about that.

My next problem is that the command python manage.py synchdb does not
create any tables, but I've started a new thread for that :)
http://groups.google.com/group/django-users/browse_thread/thread/eca94f905a6bea10

Thanks for all your help!
/Angelika

On Oct 28, 7:56 pm, Kurtis  wrote:
> Okay, I think I've got the exact steps down needed to get this running
> right. If these are actually it, I'm not sure if I had any other
> prerequisites I can't think of at the moment, then it's a matter of
> copying and pasting 3 lines into your terminal. (Less than 5-10
> minutes total)
>
> 1. Install "Brew" (http://mxcl.github.com/homebrew/)
> 2. Use Brew to Install mysql-connector-c
> 3. Install MySQL-python
>
> Open up your terminal and follow these steps. If you are unsure of
> anything during the process, then feel free to read more information
> on what these are. Google is your friend here :)
>
> /usr/bin/ruby -e "$(curl -fsSLhttps://raw.github.com/gist/323731)"
> brew install mysql-connector-c
> sudo easy_install mysql-python
>
> Hopefully that works for you! Good luck.
>
> On Oct 28, 12:19 pm, creecode  wrote:
>
>
>
>
>
>
>
> > Hello Angelika,
>
> > On Friday, October 28, 2011 2:13:20 AM UTC-7, angelika wrote:
>
> > creecode, I tried the commands you suggested first. No matter which
>
> > > version I switched to, it still said No module named django, which
> > > seems weird but there it is.
>
> > If your curious about where the old Django install may have gotten to you
> > could try on the command line...
>
> > sudo find -x / -name django -print
>
> > So I ran sudo easy_install django, just
>
> > > to see if it could be that easy. When the install was done, it seemed
> > > to work at first. I could run import django, no problem. I started the
> > > tutorial on djangoproject.com and got as far as setting up a db and
> > > running python manage.py runserver, before the dreaded
> > > "django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb
> > > module: No module named MySQLdb" started showing up. God damn it.
>
> > If you are just doing local development for learning I think you can bypass
> > the database install, at least that is what the Django Quick Install docs
> > indicate.
>
> > At this point I thinking maybe I should just switch to using
>
> > > PostgreSQL instead, if that would solve the problem. What do you guys
> > > think?
>
> > You could give it a go but if you're just wanting to get through the
> > tutorial is does seem like overkill.  I've just tried installing Postgres
> > on Mac OS X for the first time and it wasn't smooth sailing by any means.  
> > Part of the issues were related to installing the Postgres server on an
> > older OS version and hardware.  I did install psycopg2 on recent hardware
> > with current Lion and a fair amount of hair pulling.  psycopg2 is a
> > connector so that Django, through Python, will be able to talk to a
> > Postgres server.  It does the same job that MySQLdb does for MySQL.
>
> > Toodle-loo.
> > creecode

-- 
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: "python manage.py runserver" creates not tables (tutorial)

2011-11-02 Thread angelika
Christ, I totally messed up this post. I did not mean "python
manage.py runserver" but "python manage.py syncdb". That is the
command that does not create any tables. Sorry.

On Nov 2, 10:44 am, nisa balakrishnan 
wrote:
> did  u do a syncdb ?
> On 02-Nov-2011, at 3:12 PM, angelika wrote:
>
>
>
>
>
>
>
> > I've started the Django tutorial and I get as far as running python
> > manage.py runserver, but when I do, nothing happens. I get no messages
> > and the database connected to the project is still empty. The database
> > exists and I've made no modifications to any of the files created,
> > accept for the info to connect to the database. My settings.py has
> > this snippet in it:
>
> > INSTALLED_APPS = (
> >    'django.contrib.auth',
> >    'django.contrib.contenttypes',
> >    'django.contrib.sessions',
> >    'django.contrib.sites',
> >    'django.contrib.messages',
> >    'django.contrib.staticfiles',
> >    # Uncomment the next line to enable the admin:
> >    # 'django.contrib.admin',
> >    # Uncomment the next line to enable admin documentation:
> >    # 'django.contrib.admindocs',
> > )
>
> > If django is not able to find or connect to the database, I would
> > expect there to be at least an error message, right? Is there a
> > command I can run make sure? Any other ideas?
>
> > /Angelika
>
> > --
> > 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 
> > athttp://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: "python manage.py runserver" creates not tables (tutorial)

2011-11-02 Thread nisa balakrishnan
did  u do a syncdb ?
On 02-Nov-2011, at 3:12 PM, angelika wrote:

> I've started the Django tutorial and I get as far as running python
> manage.py runserver, but when I do, nothing happens. I get no messages
> and the database connected to the project is still empty. The database
> exists and I've made no modifications to any of the files created,
> accept for the info to connect to the database. My settings.py has
> this snippet in it:
> 
> INSTALLED_APPS = (
>'django.contrib.auth',
>'django.contrib.contenttypes',
>'django.contrib.sessions',
>'django.contrib.sites',
>'django.contrib.messages',
>'django.contrib.staticfiles',
># Uncomment the next line to enable the admin:
># 'django.contrib.admin',
># Uncomment the next line to enable admin documentation:
># 'django.contrib.admindocs',
> )
> 
> If django is not able to find or connect to the database, I would
> expect there to be at least an error message, right? Is there a
> command I can run make sure? Any other ideas?
> 
> /Angelika
> 
> -- 
> 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: "python manage.py runserver" creates not tables (tutorial)

2011-11-02 Thread angelika
Sorry, title is supposed to be "python manage.py runserver" creates no
tables (tutorial)

On Nov 2, 10:42 am, angelika  wrote:
> I've started the Django tutorial and I get as far as running python
> manage.py runserver, but when I do, nothing happens. I get no messages
> and the database connected to the project is still empty. The database
> exists and I've made no modifications to any of the files created,
> accept for the info to connect to the database. My settings.py has
> this snippet in it:
>
> INSTALLED_APPS = (
>     'django.contrib.auth',
>     'django.contrib.contenttypes',
>     'django.contrib.sessions',
>     'django.contrib.sites',
>     'django.contrib.messages',
>     'django.contrib.staticfiles',
>     # Uncomment the next line to enable the admin:
>     # 'django.contrib.admin',
>     # Uncomment the next line to enable admin documentation:
>     # 'django.contrib.admindocs',
> )
>
> If django is not able to find or connect to the database, I would
> expect there to be at least an error message, right? Is there a
> command I can run make sure? Any other ideas?
>
> /Angelika

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



"python manage.py runserver" creates not tables (tutorial)

2011-11-02 Thread angelika
I've started the Django tutorial and I get as far as running python
manage.py runserver, but when I do, nothing happens. I get no messages
and the database connected to the project is still empty. The database
exists and I've made no modifications to any of the files created,
accept for the info to connect to the database. My settings.py has
this snippet in it:

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)

If django is not able to find or connect to the database, I would
expect there to be at least an error message, right? Is there a
command I can run make sure? Any other ideas?

/Angelika

-- 
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: tutorial error

2011-11-02 Thread Daniel Roseman
On Wednesday, 2 November 2011 07:24:39 UTC, rihad wrote:
>
> It says at the end of part 3 of the Django tutorial: 
>
> "The idea behind include() and URLconf decoupling is to make it easy 
> to plug-and-play URLs. Now that polls are in their own URLconf, they 
> can be placed under "/polls/", or under "/fun_polls/", or under "/ 
> content/polls/", or any other path root, and the app will still work." 
>
> It's actually not that simple. Simply changing the project-wide 
> URLconf prefix from '^polls/' to '^fun_polls/' will not work, because 
> the code referencing templates still has polls in its path: 
> render_to_response('polls/detail.html', {'poll': p}) 
> or in URLs: 
> {{ poll.question }}


Your first point is simply not true. Changing the urlconf prefix does not 
in any way affect how you reference the template path. You could prefix the 
polls URLs with 'foobar', but the template path would still be 'polls'.

The second point is made irrelevant by something that's not covered in the 
tutorial, but is mentioned in the actual documentation for URLs: you should 
never hard-code URLs, you should use the `{% url %}` tag in templates or 
the `reverse()` function in views - for precisely this reason.
--
DR.

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



tutorial error

2011-11-02 Thread rihad
It says at the end of part 3 of the Django tutorial:

"The idea behind include() and URLconf decoupling is to make it easy
to plug-and-play URLs. Now that polls are in their own URLconf, they
can be placed under "/polls/", or under "/fun_polls/", or under "/
content/polls/", or any other path root, and the app will still work."

It's actually not that simple. Simply changing the project-wide
URLconf prefix from '^polls/' to '^fun_polls/' will not work, because
the code referencing templates still has polls in its path:
render_to_response('polls/detail.html', {'poll': p})
or in URLs:
{{ poll.question }}

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