Re: Installed apps settings, necessary?

2007-02-10 Thread voltron

Thank you all for the clarification!

On Feb 10, 5:32 pm, "James Bennett" <[EMAIL PROTECTED]> wrote:
> On 2/9/07, voltron <[EMAIL PROTECTED]> wrote:
>
> > what are the advantages of adding the apps to the settings file?
>
> Several things:
>
> * If an app is never listed in INSTALLED_APPS, syncdb will never see
> it and so will never install DB tables for its models.
> * If an app is never listed in INSTALLED_APPS, Django will never pick
> up on any custom template tag libraries it includes.
> * If an app is never listed in INSTALLED_APPS, some internal loading
> tricks that the contrib apps rely on will never see its models.
>
> --
> "Bureaucrat Conrad, you are technically correct -- the best kind of correct."


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



Re: are the Installed apps settings necessary?

2007-02-10 Thread voltron

Aha! Thanks for the answers.


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



Re: Running django with stackless

2007-02-10 Thread krypton

Django
part of my code is in webpy
and a differnet proj in django

On Feb 10, 5:12 am, James Tauber <[EMAIL PROTECTED]> wrote:
> Is your mention of webpy everywhere instead of Django a cut-and-paste  
> error?
>
> Are you really asking about django or about webpy?
>
> On 10/02/2007, at 7:30 AM, krypton wrote:
>
>
>
> > Guys I m using threads to use concurrecy in my webapps and I find it
> > to be needlessly slow, because most of the stuff thatI try to do with
> > the thread are like, send messages, update a long running thread,
> > update rss feeds etcc., ie they do not need context and Hence i do not
> > need threads
>
> > Upon researching I found an implementation of python that doesnt  
> > use C-
> > Stacks and hence supports Co-routines. Here is my question. I want to
> > use webpy with stackless python.
>
> > The problem I m facing is there are parts of webpy that are hacked
> > with frame operations. Is there any one who has webpy running on
> > stackless. If so please share the patch
>
> > Thanks a lot Krypton


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



newforms Validation Static vs Dynamic

2007-02-10 Thread johnny

What is the different between newforms, forms.CharField(max_length =
30, min_length = 5, error_message ='Must be at least 5 char length')
and using clean method raise forms.ValidationError ('Display some
error message')

Is former for static error message and later for Dynamic Error Message?


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



Using NEWFORMS to select data from the MODEL

2007-02-10 Thread johnny

I have to include some fields from 3 different models. How do you
create a selection field, for selecting a category data, in category
model, using newforms?

Thank You in advance.


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



Re: how to set the choices of Select Widget by code in the newforms

2007-02-10 Thread gordyt

> I don't think there's any way of accessing the request.user from the
> Form class (is there?). If I could pass in the choices when I'm
> instantiating the form from views.py my problem would be solved. Is
> this possible?

Cathy this is absolutely possible.  Here is an example from one of my
projects...

First here is the form:

-- cut here --
class AddEditContactPhoneForm(forms.Form):
employee_id = forms.ChoiceField(label='Employee', required=False)
phone_number = PhoneNumberField(label='Phone Number')
extension = forms.CharField(max_length=8,required=False)
phone_type_id = forms.ChoiceField(label='Phone Type',
choices=[(c.id,c.description) for c in
PhoneNumberType.objects.all()] )
def __init__(self, data=None, auto_id='id_%s', prefix=None,
employee_list={}):
super( AddEditContactPhoneForm,
self ).__init__( data,auto_id,prefix )
self.fields['employee_id'] =
forms.ChoiceField(label='Employee', required=False,
choices = [('','Select')] + [(c.id,"%s, %s (%s)" %
(c.last_name,c.first_name,c.title)) for c in employee_list] )
-- cut here --

And here is a view that uses it:

-- cut here --
@login_required
def customer_phone_numbers_detail(request,customer_id,object_id):
"""
Editing form for a phone number
customer_id is the Customer.id
object_id is the ContactPhone.id of the phone number to edit or 0
for new phone number
"""
customer = Customer.objects.get(id=int(customer_id))
employees = Employee.objects.filter(customer=customer,active=True)
object_id = int(object_id)
error_message = None
if request.method == "POST":
edit_form =
AddEditContactPhoneForm(request.POST,employee_list=employees)
if edit_form.is_valid():
obj = ContactPhone(**edit_form.clean_data)
if object_id > 0 : obj.id = object_id
obj.customer = customer
obj.save()
object_id=obj.id
elif object_id > 0:
obj = ContactPhone.objects.get(id=object_id)
edit_form =
AddEditContactPhoneForm(obj.__dict__,employee_list=employees)
else:
edit_form = AddEditContactPhoneForm(employee_list=employees)
return render_to_response("kindledb/
customer_phone_numbers_detail.html",
{"edit_form": edit_form, 'object_id': object_id,
'error_message': error_message, 'customer' : customer})
-- cut here --

--gordy


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



Re: Subclassing models

2007-02-10 Thread Malcolm Tredinnick

On Sat, 2007-02-10 at 23:22 +, Zach Seifts wrote:
> I don't want to use a ForeignKey. I want to be able to set up a class
> in the model and not have a table created. Maybe the base model thing
> is the way to do it. I've read somewhere about mixins, could these be
> of interest?

As Collin mentioned, true model inheritance in Django (even with
abstract base classes as you are doing here) does not work yet. The
reason is that although it works on the Python level, you end up with
the wrong model manager and the multi-table queries are not constructed
correctly. A fix for this will land shortly (see [1]).

For what you are trying to do, you might be able to get away with not
making Foo a subclass of models.Model and then making Bar inherit from
both models.Model and Foo, although I'm not 100% sure that will work
correctly, either. But it should be fairly quick to test.

Sorry we cannot help you with a perfect solution. This is completely my
fault -- I have been dragging the chain on this one. It will be fixed
soon.

[1] http://code.djangoproject.com/wiki/VersionOneFeatures

Regards,
Malcolm


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



Re: Subclassing models

2007-02-10 Thread Zach Seifts

I don't want to use a ForeignKey. I want to be able to set up a class
in the model and not have a table created. Maybe the base model thing
is the way to do it. I've read somewhere about mixins, could these be
of interest?

On Feb 10, 4:37 pm, "Collin Grady" <[EMAIL PROTECTED]> wrote:
> Subclassing doesn't work right yet, you need to use a ForeignKey or
> similar to the base model in order to relate them - if you do it the
> way you're trying it will break things randomly.
>
> On Feb 10, 12:25 pm, "Zach Seifts" <[EMAIL PROTECTED]> wrote:
>
> > I have been working on a project where I need to create a few classes
> > in the model that are very similar. What I want to do is subclass a
> > model but have it not set up a database table. I know there are ways
> > of doing this I just haven't figured out yet.
>
> > Here's an example of what I am trying to do
>
> > class Foo(models.Model)
> > """ This class does not have a db table """
> > name = models.CharField(maxlength=100)
>
> > class Bar(Foo)
> > """ This class has a db table """
> > eyeColor = models.CharField(maxlength=100)
>
> > Thanks for you help.


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



Re: 404 Error - Can't link to my css or image files from a template.

2007-02-10 Thread Dan Lynch

Thanks for the link, it sorted the problem. It did my head in for a
while though I have to admit. I knew it would be something to do with
the URLConf but I couldn't seem to find the answer, maybe my brain was
just fried after a 5 hours staring at the screen, it seemed a lot
easier after a break :-)

Thanks again

Dan

On Feb 10, 9:35 pm, "Collin Grady" <[EMAIL PROTECTED]> wrote:
> You cannot put images in your templates directory. You need to make a
> media folder and map it properly as detailed here:
>
> http://www.djangoproject.com/documentation/static_files/


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



Re: ForeignKey, null, and schema evolution

2007-02-10 Thread Ramiro Morales

On 2/10/07, David Abrahams <[EMAIL PROTECTED]> wrote:
>
> Whatever django bugs may be lurking asid, I need to move forward with
> my project ASAP so I'd really appreciate it if someone could give me a
> few hints about how to evolve my existing DB (which was created
> without the primary_key=True and (I think) also without null=True) so
> I can still use the data.

Disclamer: I know almost nothing about databases.

Oh, this is a (new) hint. You are not sure if you created your data when
the Session -> Track ForeignKey had null=True? If it hadn' t and you are
now trying to modify it it to use that option without also modifying the DB,
it's not that strange you are getting errors.

You could confirm that by examining the table stucture. Use:

$ ./manage.py sql program

twice, once without null=True and once with null=True, to see the difference
and eventually create the ALTER TABLE SQL sentence to modify to reflect
the change you' ve made to your model without losing your valuable data.

This is using sqlite3:

--- nonull.txt  2007-02-10 19:29:23.0 -0300
+++ nulltrue.txt2007-02-10 19:28:48.0 -0300
@@ -13,13 +13,13 @@
 CREATE TABLE "program_session" (
 "id" integer NOT NULL PRIMARY KEY,
 "title" varchar(200) NOT NULL,
 "short_title" varchar(50) NOT NULL,
 "description" text NOT NULL,
 "start_id" integer NOT NULL REFERENCES "program_timedivision" ("id"),
-"track_id" integer NOT NULL REFERENCES "program_track" ("id"),
+"track_id" integer NULL REFERENCES "program_track" ("id"),
 "duration" time NOT NULL,
 UNIQUE ("start_id", "track_id"),
 UNIQUE ("title")
 );
 CREATE TABLE "program_speaker" (
 "id" integer NOT NULL PRIMARY KEY,

Regards,

-- 
 Ramiro Morales

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



Re: Doing "in" subqueries on the server-side

2007-02-10 Thread Malcolm Tredinnick

On Sat, 2007-02-10 at 09:41 -0600, Tim Chase wrote:
> For an app I've been assembling, I need to filter a particular
> data-set based on multiple many-to-many criteria where the
> criteria span multiple records in the far participant of the M2M.
>  The basics are the recordset (Items) and each Item has a M2M
> relationship with Properties (a key/value pair)
> 
> class Property(model):
>   name = CharField(...)
>   value = CharField(...)
> 
> class Item(model:
>   properties = ManyToMany(Property)
> 
> I want to filter my list of items for items that have two
> different properties.   In SQL, it would look something like
> 
> SELECT *
> FROM x_item
> WHERE
>  x_id IN (
>   SELECT ip.item_id
>   FROM
>   x_item_property ip
>   INNER JOIN x_property p
>   ON ip.property_id = p.id
>   WHERE
>   p.name = 'foo'
>   and p.value = 'bar'
>   )
> AND
>  x_id IN (
>   SELECT ip.item_id
>   FROM
>   x_item_property ip
>   INNER JOIN x_property p
>   ON ip.property_id = p.id
>   WHERE
>   p.name = 'baz'
>   and p.value = 'bip'
>   )
> 
> 
> This query returns all the items that have both "foo=bar" and
> "baz=bip" from their associated property lists.  This is
> different than just filtering the M2M relationship based on the
> select_related() because once you've filtered for those items
> that have "foo=bar", you've eliminated all rows in which
> "baz=bip" and thus filtering by that again would return an empty
> dataset.
> 
> However, I'm having trouble getting Django to do all the work on
> the server side.  I've got a workaround in place where I do
> 
> items = models.Items.objects
> properties = models.Items.objects.select_related(
>   ).filter(properties__name='foo'
>   ).filter(properties__value='bar')
> item_ids = [item.id for item in items] # XXX
> items = items.filter(id__in = item_ids)
> properties = models.Items.objects.select_related(
>   ).filter(properties__name='baz'
>   ).filter(properties__value='bip')
> item_ids = [item.id for item in items] # XXX
> items = items.filter(id__in = item_ids)
> # do something with items
> 
> While this works (this is some pseudo-code in the email, but
> should give you the idea of what's going on, even if there are a
> couple syntax errors), it pulls back the data-sets for the
> properties (in the XXX lines), building potentially huge lists on
> the Django side (rather than the DB side) and then shipping those
> huge lists back to the server as the clause to an IN query.  I've
> already experienced some problems with sluggish behavior and this
> is a only a medium-sized record-set (about 800 IDs coming back
> per sub-query).  Live data will actually have some that bring
> back thousands upon thousands.
> 
> Ideally, I'd have some way of doing something like
> 
> items = models.Items.objects
> properties = models.Items.objects.select_related(
>   ).filter(properties__name='foo'
>   ).filter(properties__value='bar')
> items = items.filter(id__in = properties)
> properties = models.Items.objects.select_related(
>   ).filter(properties__name='baz'
>   ).filter(properties__value='bip')
> items = items.filter(id__in = properties)
> # do something with items
> 
> This would allow for lazy evaluation of a single query, doing all
> the filtering on the DB side rather than shipping huge quantities
> of data over the connection 3x.
> 
> However, when I tried the above, the "= properties" clause
> expanded as a string (perhaps as a repr() of bits of the data),
> not as the full SELECT query, and produced bogus SQL which the
> server promptly complained about.
> 
> Any hints on how to go about this and make the server do all the
> work?  Push come to shove, I can monkey with an .extra() call and
> put the SQL in the WHERE clause by hand, but it would be
> nice/legible/understandable to use pure Django.

You cannot really construct nested clauses like this with Django DB API
-- it's designed in favour of simpler cases. The normal solution that is
recommended in cases like this is to construct the SQL statement
yourself (maybe as part of a custom model manager method) and just pass
it to the database directly. See [1] for an example.

[1] http://www.pointy-stick.com/blog/2006/06/14/custom-sql-django/

In the future (probably before 1.0), the query construction inside a
QuerySet is going to be moved into a more self-contained construct, so
that, instead of constructing queries by pushing a bunch of string
fragments together as we do now, you can access the independent parts of
the query prior to it being turned into a string. This will make it
easier for people to poke at the query to tweak things like this (it
won't be trivial, but it will be easier if you want to get a mix between
custom SQL and Django-generated queries). You could even subclass that
query generation portion to do the heavy 

Re: Subclassing models

2007-02-10 Thread Collin Grady

Subclassing doesn't work right yet, you need to use a ForeignKey or
similar to the base model in order to relate them - if you do it the
way you're trying it will break things randomly.

On Feb 10, 12:25 pm, "Zach Seifts" <[EMAIL PROTECTED]> wrote:
> I have been working on a project where I need to create a few classes
> in the model that are very similar. What I want to do is subclass a
> model but have it not set up a database table. I know there are ways
> of doing this I just haven't figured out yet.
>
> Here's an example of what I am trying to do
>
> class Foo(models.Model)
> """ This class does not have a db table """
> name = models.CharField(maxlength=100)
>
> class Bar(Foo)
> """ This class has a db table """
> eyeColor = models.CharField(maxlength=100)
>
> Thanks for you help.


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



Re: 404 Error - Can't link to my css or image files from a template.

2007-02-10 Thread Collin Grady

You cannot put images in your templates directory. You need to make a
media folder and map it properly as detailed here:

http://www.djangoproject.com/documentation/static_files/

On Feb 10, 1:05 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Hi folks,
>
> I am a bit of a newbie when it comes to Django so I apologize in
> advance. I know this is something simple I'm doing wrong but after
> hours of reading articles on the Django site and searching for answers
> I've had enough. I decided to bite the bullet and just ask :-)
>
> My problem is I went through the tutorial on the site, all worked
> first time great. Then I decided to try putting a more interesting
> template HTML page into the polls app, just for an experiment really.
> I took an XHTML/CSS design I had done for a site previously and copied
> the files into the folder where I keep the templates for the the Polls
> tutorial. Thinking all I needed to do was tell point HTTPResonse of
> the main view to the new file and it would all work. I was wrong.
>
> It loads the new HTML file fine but none of the links to images or the
> stylesheet coded in the file work. I have looked around trying to find
> what I need to do to get this working, I've moved the files around
> trying to find the right location for them, read the full Template
> guide on the Django site and even tried to see how it's done in the
> Admin HTML templates that come with Django. Nothing has worked.
>
> My site is structured like so:
> mysite - folder created by Django_Admin.py
> ---> Polls - folder contains all the .py files for the Polls app
> ---> Templates - folder containing all the HTML templates for the
> site
> ->Polls - folder for all the templates for Polls app
> >Images folder - contains all the images used in
> the template
> >index.html
> >screen.css
>
> The stylesheet is linked with the following syntax in the HTML
> template:
>
> 
>
> The links work fine when you load the HTML file in a browser so I
> assume it's something to do with the Django template settings in
> settings.py I tried experimenting with the media folder settings at
> well but I'm getting nowhere. The Django development server gives 404
> error for the stylesheet and images when I run it, just appears with
> plain HTML text.
>
> Can anyone help? It would be greatly appreciated. No doubt it will be
> something simple in the settings.
>
> Thanks in advance.
>
> Dan


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



404 Error - Can't link to my css or image files from a template.

2007-02-10 Thread [EMAIL PROTECTED]

Hi folks,

I am a bit of a newbie when it comes to Django so I apologize in
advance. I know this is something simple I'm doing wrong but after
hours of reading articles on the Django site and searching for answers
I've had enough. I decided to bite the bullet and just ask :-)

My problem is I went through the tutorial on the site, all worked
first time great. Then I decided to try putting a more interesting
template HTML page into the polls app, just for an experiment really.
I took an XHTML/CSS design I had done for a site previously and copied
the files into the folder where I keep the templates for the the Polls
tutorial. Thinking all I needed to do was tell point HTTPResonse of
the main view to the new file and it would all work. I was wrong.

It loads the new HTML file fine but none of the links to images or the
stylesheet coded in the file work. I have looked around trying to find
what I need to do to get this working, I've moved the files around
trying to find the right location for them, read the full Template
guide on the Django site and even tried to see how it's done in the
Admin HTML templates that come with Django. Nothing has worked.

My site is structured like so:
mysite - folder created by Django_Admin.py
---> Polls - folder contains all the .py files for the Polls app
---> Templates - folder containing all the HTML templates for the
site
->Polls - folder for all the templates for Polls app
>Images folder - contains all the images used in
the template
>index.html
>screen.css

The stylesheet is linked with the following syntax in the HTML
template:



The links work fine when you load the HTML file in a browser so I
assume it's something to do with the Django template settings in
settings.py I tried experimenting with the media folder settings at
well but I'm getting nowhere. The Django development server gives 404
error for the stylesheet and images when I run it, just appears with
plain HTML text.

Can anyone help? It would be greatly appreciated. No doubt it will be
something simple in the settings.

Thanks in advance.

Dan


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



Re: ForeignKey, null, and schema evolution

2007-02-10 Thread David Abrahams

"yary" <[EMAIL PROTECTED]> writes:

> IIRC, Django's admin can't handle a field with null=True and
> blank=False (which is a bit of a shame...) Try adding blank=True to
> your model's field?

Read my latest post and you'll see that I have tried that.  It works,
but only if I explicitly specify the ForeignKey's primary key.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com


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



Re: ForeignKey, null, and schema evolution

2007-02-10 Thread yary

IIRC, Django's admin can't handle a field with null=True and
blank=False (which is a bit of a shame...) Try adding blank=True to
your model's field?


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



Subclassing models

2007-02-10 Thread Zach Seifts

I have been working on a project where I need to create a few classes
in the model that are very similar. What I want to do is subclass a
model but have it not set up a database table. I know there are ways
of doing this I just haven't figured out yet.

Here's an example of what I am trying to do

class Foo(models.Model)
""" This class does not have a db table """
name = models.CharField(maxlength=100)

class Bar(Foo)
""" This class has a db table """
eyeColor = models.CharField(maxlength=100)

Thanks for you help.


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



NEW MONEY NETWORK AGLOCO

2007-02-10 Thread efendy

Hi ...

I recently joined AGLOCO because of a friend recommended it to me. I
am now promoting it to you because I like the idea and I want you to
share in what I think will be an exciting new Internet concept.

Sign in : http://www.agloco.com/r/BBBV9253

AGLOCO's story is simple:


Do you realize how valuable you are? Advertisers, search providers and
online retailers are paying billions to reach you while you surf.  How
much of that money are you making? NONE!


AGLOCO thinks you deserve a piece of the action.


AGLOCO collects money from those companies on behalf of its members.
(For example, Google currently pays AOL 10 cents for every Google
search by an AOL user. And Google still has enough profit to pay $1.6
billion dollars for YouTube, an 18-month old site full of content that
YouTube's users did not get paid for!


AGLOCO will work to get its Members their share of this and more.


AGLOCO is building a new form of online community that they call an
Economic Network. They are not only paying Members their fair share,
but they're building a community that will generate the kind of
fortune that YouTube made. But instead of that wealth making only a
few people rich, the entire community will get its share.


What's the catch? No catch - no spyware, no pop-ups and no spam -
membership and software are free and AGLOCO is 100% member owned.
Privacy is a core value and AGLOCO never sells or rents member
information.


So do both of us a favor: Sign up for AGLOCO right now! If you use
this link to sign up, I automatically get credit for referring you and
helping to build AGLOCO.

Sign in : http://www.agloco.com/r/BBBV9253


Thanks


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



Re: how to set the choices of Select Widget by code in the newforms

2007-02-10 Thread Cathy Young

On Feb 10, 5:33 pm, "canen" <[EMAIL PROTECTED]> wrote:
> If I understand what you are asking, choices can be set to a function,
> as long as it returns the correct format. If you return a generator I
> think there is a  bug that will only call it the first time the form
> is rendered (e.g. if there is an error in the form the choices won't
> show up when it renders again). To get around this wrap the function
> call in  a list so it is forced to be evaluated, i.e choices =
> list(my_function())..

I have the same problem as the OP. In my example, choices needs to be
a list of things associated with the current user, so I need to have
the request.user so that I can retrieve an appropriate queryset of
objects.

I don't think there's any way of accessing the request.user from the
Form class (is there?). If I could pass in the choices when I'm
instantiating the form from views.py my problem would be solved. Is
this possible?

--
Cathy
http://www.bentbacktulips.co.uk/


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



Re: DB API - dict of emails

2007-02-10 Thread Dirk Eschler

On Samstag, 10. Februar 2007, Ned Batchelder wrote:
> But is is simple to convert what you have into what you want:
>
> l =
> User.objects.filter(username__in=['foo','bar']).values('username', 'email')
> emails = dict([(d['username'], d['email']) for d in l])
>
> It would be a little simpler like this:
>
> emails = dict([(r.username, r.email) for r in
> User.objects.filter(username__in=['foo','bar'])])
>
> The dict() built-in accepts a number of forms of arguments.  One is a
> list of pairs, each of which becomes a key and value in the resulting
> dictionary.

Nice! Thanks alot for posting posting this solution.

Best Regards,
Dirk Eschler

-- 
Dirk Eschler 
http://www.krusader.org

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



Re: ForeignKey, null, and schema evolution

2007-02-10 Thread David Abrahams
David Abrahams <[EMAIL PROTECTED]> writes:

> My models.py is enclosed.  It doesn't have any special dependencies.
> Would you mind trying to reproduce the problem?
>
>> Try creating a smaller project with a trimmed
>> down model -- doing the standard "remove stuff until it starts working
>> or you are only left with the ForeignKey" process.
>
> I'll see if I can do that.

FYI, I can reproduce two problems in a smaller complete project
(enclosed), although I haven't had success creating a minimal case.

Steps to reproduce the main problem:

  0. create a database 
  1. syncdb
  2. run the dev server
  3. go to http://localhost:8000/admin/ and login
  4. create a new Session object
  5. fill in all required fields, creating a Speaker and
 TimeDivision as needed.  leave Track as '--'
  6. Save

How to make it work:

  7. Set primary_key=True on the 'name' field of the Track object
  8. AND add blank=True to the 'track' field of the Session object
  9. delete the database
  10. repeat

Note that without blank=True, the Session with no track won't
validate.

Whatever django bugs may be lurking asid, I need to move forward with
my project ASAP so I'd really appreciate it if someone could give me a
few hints about how to evolve my existing DB (which was created
without the primary_key=True and (I think) also without null=True) so
I can still use the data.

Thanks,


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



djtest.tar.bz2
Description: Binary data

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com


Re: Use of post_save on newly created objects

2007-02-10 Thread daev

I've write in my project:

def create_profile_for_user(sender, instance, signal, *args,
**kwargs):
try:
User.objects.get(id=instance._get_pk_val())
except (User.DoesNotExist, AssertionError):
profile = Profile( user = instance )
profile.save()

dispatcher.connect(create_profile_for_user, signal=signals.post_save,
sender=User)

it creates a profile for new user. works

On Feb 10, 6:09 am, "Benjamin Slavin" <[EMAIL PROTECTED]>
wrote:
> Howdy all,
>
> I was investigating post_save to perform some associated setup for an
> object after it's created.  My only concern is that I can't seem to
> find any way to check if the object was created on this call to
> save()... I only want to perform the setup the first time the object
> is saved.
>
> So... Is it possible to perform a function (via post_save or some
> other mechanism) when a given object is saved for the first time?
>
> Perhaps the addition of a post_create signal could be a solution, but
> I didn't want to bring that up on django-developers until I asked
> here.
>
> Thanks,
>   -Ben


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



Re: are the Installed apps settings necessary?

2007-02-10 Thread daev

On Feb 10, 8:41 pm, "canen" <[EMAIL PROTECTED]> wrote:
> You don't need INSTALLED_APPS for views, it's more for models if I am
> not mistaken, for example, syncdb won't work if your app is not in
> INSTALLED_APPS.
Yes. Its true


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



Re: Using __str__ with DateField

2007-02-10 Thread Andrew Diederich

On 2/10/07, Adrian Holovaty <[EMAIL PROTECTED]> wrote:
>
> On 2/10/07, Andrew Diederich <[EMAIL PROTECTED]> wrote:
> > Is there an easy way to munge the return self.end_date into a string?
>
> This is a Python requirement -- __str__() methods must return a
> string. To fix the problem, wrap self.end_date in str(), like so:
>
> return str(self.end_date)

Perfect. I thought it would be intensely easy.  Thanks for the help.

-- 
Andrew Diederich

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



Authenticate during middleware call

2007-02-10 Thread Mike H


Hi all,

I am putting together a system where logging in and out is triggered by
calls from a seperate application.

The other application posts a username and a session id to my
application, and sets a cookie so that when the user visits my site, my
app sees the cookie, looks up which username is associated with that
session id and logs them in. So far, this works fine and my application
can see the cookie and look up the related user with no problems.

I have a middleware class that detects for the cookie and tries to
authenticate the user, and it looks like this :



from django.contrib.auth import authenticate
from combie.sso.models import SsoSession

class SsoAuthenticatedMiddleware(object):
def process_request(self, request):
if 'COMBIE_SESSION_ID' in request.COOKIES:
identifier = request.COOKIES['COMBIE_SESSION_ID']
session =
SsoSession.objects.get(session_identifier=identifier)
user = authenticate(username=session.user.username,
password='combiepass')
login(request, user)
return None

I've tried many different ways but either it fails to authenticate
silently or complains about no "backend" attribute.

Has anyone got a better solution to this?

Many thanks.

Mike

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



Re: Using __str__ with DateField

2007-02-10 Thread Adrian Holovaty

On 2/10/07, Andrew Diederich <[EMAIL PROTECTED]> wrote:
> Is there an easy way to munge the return self.end_date into a string?

This is a Python requirement -- __str__() methods must return a
string. To fix the problem, wrap self.end_date in str(), like so:

return str(self.end_date)

Adrian

-- 
Adrian Holovaty
holovaty.com | djangoproject.com

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



Using __str__ with DateField

2007-02-10 Thread Andrew Diederich

I'm setting up a simple timecard app as a django proof-of-concept.
One of my models is "Period" that specifies the end-date of the time
period (usually a Friday).

I'm not getting __repr__ right.

Trying to add a period in the admin side:

TypeError at /admin/timekeeper/period/add/
__str__ returned non-string (type datetime.date)Request Method: POST
Request URL:http://localhost:8000/admin/timekeeper/period/add/
Exception Type: TypeError
Exception Value:__str__ returned non-string (type datetime.date)
Exception Location: 
c:\python25\lib\site-packages\django\contrib\admin\views\main.py
in add_stage, line 256

The model:
class Period(models.Model):
end_date = models.DateField('end date')
insert_date = models.DateTimeField('date inserted', auto_now_add=True)

def __str__(self):
return self.end_date

class Admin:
pass

Is there an easy way to munge the return self.end_date into a string?

Thanks for the help.

-- 
Andrew Diederich

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



Re: are the Installed apps settings necessary?

2007-02-10 Thread canen

You don't need INSTALLED_APPS for views, it's more for models if I am
not mistaken, for example, syncdb won't work if your app is not in
INSTALLED_APPS.

voltron wrote:
> I posted this yesterday, but It did not show up, strange.
>
> According to the manual, one has to add apps to the INSTALLED_APPS
> setting tuple to make the usable in a project. I have created several
> test apps with views wired to urls in the projects url conf file, I
> was able to call up all urls without any problems.
>
> What is the main advantage of listing the apps in the INSTALLED_APPS
> variable? Not that I`m complaining, Im just curious, in fact if its
> not a necessity, It makes my apps more portable, I just copy the apps
> I need to another Project folder, wire up the urls  and they work, one
> step less to take.


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



Re: ForeignKey, null, and schema evolution

2007-02-10 Thread David Abrahams
Malcolm Tredinnick <[EMAIL PROTECTED]> writes:

> On Sat, 2007-02-10 at 03:34 -0500, David Abrahams wrote:
>> 
>> In my attempt to use 
>> 
>>ForeignKey(Track, null=True) 
>> 
>> When I actually tried to use a null Track value, I got:
> [...traceback snipped...]
>> 
>> ProgrammingError at /admin/program/session/15/
>> ERROR: invalid input syntax for integer: "" SELECT 
>> "program_session"."id","program_session"."title","program_session"."short_title","program_session"."description","program_session"."start_id","program_session"."track_id","program_session"."duration"
>>  FROM "program_session" INNER JOIN "program_timedivision" AS 
>> "program_session__start" ON "program_session"."start_id" = 
>> "program_session__start"."id" WHERE ("program_session__start"."id" ILIKE 
>> '40' AND "program_session"."track_id" = '')
>> 
>> My wild guess here is that this happens because track_id is the primary key
>> and thus expects an integer value; had I made the track name its
>> primary key it might've worked (?).  Anyway, if I want to make that
>> change at this point, I don't know how to do so without losing my
>> valuable data.  Any help you can offer me would be very much
>> appreciated.
>
> Can you give a little more information about how you triggered this
> error? It looks like you are doing something in the admin, 

I am.  I'm saving an existing Session object after setting its Track
to the "--" entry in the pop-up used for track selection.  I get
a similar effect when creating a new Session without setting the
Track.

> but I am using null=True foreign keys through the admin successfully
> without doing anything special, so it's not totally impossible. It
> shows up fine in the admin system and the database stores the
> reference as a NULL (in my case). And I'm using PostgreSQL, too, so
> it's not a db-specific thing that I can see (although I'm using
> psycopg1, not psycopg2).
>
> If you triggered the problem just by trying to add a record in the admin
> and leaving the "track" reference field empty, it's going to be a little
> hard to debug remotely. 

My models.py is enclosed.  It doesn't have any special dependencies.
Would you mind trying to reproduce the problem?

> Try creating a smaller project with a trimmed
> down model -- doing the standard "remove stuff until it starts working
> or you are only left with the ForeignKey" process.

I'll see if I can do that.

> I can't place what portion of the admin is generating the query you are
> seeing, so any information you can provide would be useful.

The endlosed models.py ought to be sufficient.


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

from django.db import models

class Speaker(models.Model):
last_name = models.CharField(maxlength=100)
first_name = models.CharField(maxlength=100)
email = models.EmailField()
bio = models.TextField()

class Meta:
ordering = ('last_name','first_name','email')

class Admin:
pass
# list_display = ('first_name', 'last_name')

def __str__(self):
return self.first_name + ' ' + self.last_name

class Track(models.Model):
name = models.CharField(maxlength=100, primary_key=True)
description = models.TextField()

class Admin:
list_display = ('name', 'description')

def __str__(self):
return self.name


class TimeDivision(models.Model):
when = models.DateTimeField()
starts_break = models.BooleanField()
name = models.CharField(maxlength=100)

class Admin:
pass
# list_display = ('name', 'when', 'starts_break')

class Meta:
ordering = ('when',)

def __str__(self):
return self.when.strftime('%A') + ' ' + self.name

class Session(models.Model):
title = models.CharField(maxlength=200)
speakers = models.ManyToManyField(Speaker, filter_interface =
  models.HORIZONTAL, related_name='Sessions')
short_title = models.CharField(maxlength=50,blank=True)
description = models.TextField()
start = models.ForeignKey(TimeDivision)
track = models.ForeignKey(Track,blank=True,null=True)
duration = models.TimeField()

def __str__(self):
return ', '.join([s.last_name for s in self.speakers.all()]) \
   + ': ' + (self.short_title or self.title)


class Admin:
pass

class Meta:
# These constraints are imperfect but should catch many common errors
unique_together = (
('start','track'),  # only one session may start in a given

Re: how to set the choices of Select Widget by code in the newforms

2007-02-10 Thread daev

On Feb 10, 8:07 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> how?
In my project i have that code:

#in some view
form_class = AddPostForm #form adds post to the blog
form_class.base_fields[ 'category' ].choices =
getCategoriesTuple( request.blog ) #sets choices to ChoiceField


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



Re: how to set the choices of Select Widget by code in the newforms

2007-02-10 Thread canen

If I understand what you are asking, choices can be set to a function,
as long as it returns the correct format. If you return a generator I
think there is a  bug that will only call it the first time the form
is rendered (e.g. if there is an error in the form the choices won't
show up when it renders again). To get around this wrap the function
call in  a list so it is forced to be evaluated, i.e choices =
list(my_function())..

Hope that helps.

[EMAIL PROTECTED] wrote:
> how?


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



how to set the choices of Select Widget by code in the newforms

2007-02-10 Thread [EMAIL PROTECTED]

how?


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



Re: Installed apps settings, necessary?

2007-02-10 Thread James Bennett

On 2/9/07, voltron <[EMAIL PROTECTED]> wrote:
> what are the advantages of adding the apps to the settings file?

Several things:

* If an app is never listed in INSTALLED_APPS, syncdb will never see
it and so will never install DB tables for its models.
* If an app is never listed in INSTALLED_APPS, Django will never pick
up on any custom template tag libraries it includes.
* If an app is never listed in INSTALLED_APPS, some internal loading
tricks that the contrib apps rely on will never see its models.

-- 
"Bureaucrat Conrad, you are technically correct -- the best kind of correct."

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



Re: Filtering foreign items in admin

2007-02-10 Thread Rob Hudson

Take a look at "limit_choices_to" in the model api docs and see if
that will do what you need.

On Feb 9, 4:27 am, "Rob Slotboom" <[EMAIL PROTECTED]> wrote:
> For a several models I use a FK to photos. The drop down in admin to
> choose from lists all photos.
> Can this list be filtered so I can restrict the available photos for
> some models?


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



Re: custom validator or other way to avoid double bed bookings

2007-02-10 Thread Nebojša Đorđević

On Feb 9, 2007, at 09:32 , Benedict Verheyen wrote:

> my app is used to manage patients of a ward in a hospital.
> This ward has a number of beds available.
> A patient has a room id referring to the room/bed where he's laying.
>
> Now i would want to avoid being able to select a bed that is  
> already in use.

Have you tried `limit_choices_to` (http://www.djangoproject.com/ 
documentation/model_api/#many-to-one-relationships) to filter out all  
of the used beds from the select list.

Do you use Django admin interface or the custom form?

-- 
Nebojša Đorđević - nesh, ICQ#43799892
Studio Quattro - Niš - Serbia
http://studioquattro.biz/ | http://trac.studioquattro.biz/djangoutils/
Registered Linux User 282159 [http://counter.li.org]



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



Doing "in" subqueries on the server-side

2007-02-10 Thread Tim Chase

For an app I've been assembling, I need to filter a particular
data-set based on multiple many-to-many criteria where the
criteria span multiple records in the far participant of the M2M.
 The basics are the recordset (Items) and each Item has a M2M
relationship with Properties (a key/value pair)

class Property(model):
name = CharField(...)
value = CharField(...)

class Item(model:
properties = ManyToMany(Property)

I want to filter my list of items for items that have two
different properties.   In SQL, it would look something like

SELECT *
FROM x_item
WHERE
 x_id IN (
SELECT ip.item_id
FROM
x_item_property ip
INNER JOIN x_property p
ON ip.property_id = p.id
WHERE
p.name = 'foo'
and p.value = 'bar'
)
AND
 x_id IN (
SELECT ip.item_id
FROM
x_item_property ip
INNER JOIN x_property p
ON ip.property_id = p.id
WHERE
p.name = 'baz'
and p.value = 'bip'
)


This query returns all the items that have both "foo=bar" and
"baz=bip" from their associated property lists.  This is
different than just filtering the M2M relationship based on the
select_related() because once you've filtered for those items
that have "foo=bar", you've eliminated all rows in which
"baz=bip" and thus filtering by that again would return an empty
dataset.

However, I'm having trouble getting Django to do all the work on
the server side.  I've got a workaround in place where I do

items = models.Items.objects
properties = models.Items.objects.select_related(
).filter(properties__name='foo'
).filter(properties__value='bar')
item_ids = [item.id for item in items] # XXX
items = items.filter(id__in = item_ids)
properties = models.Items.objects.select_related(
).filter(properties__name='baz'
).filter(properties__value='bip')
item_ids = [item.id for item in items] # XXX
items = items.filter(id__in = item_ids)
# do something with items

While this works (this is some pseudo-code in the email, but
should give you the idea of what's going on, even if there are a
couple syntax errors), it pulls back the data-sets for the
properties (in the XXX lines), building potentially huge lists on
the Django side (rather than the DB side) and then shipping those
huge lists back to the server as the clause to an IN query.  I've
already experienced some problems with sluggish behavior and this
is a only a medium-sized record-set (about 800 IDs coming back
per sub-query).  Live data will actually have some that bring
back thousands upon thousands.

Ideally, I'd have some way of doing something like

items = models.Items.objects
properties = models.Items.objects.select_related(
).filter(properties__name='foo'
).filter(properties__value='bar')
items = items.filter(id__in = properties)
properties = models.Items.objects.select_related(
).filter(properties__name='baz'
).filter(properties__value='bip')
items = items.filter(id__in = properties)
# do something with items

This would allow for lazy evaluation of a single query, doing all
the filtering on the DB side rather than shipping huge quantities
of data over the connection 3x.

However, when I tried the above, the "= properties" clause
expanded as a string (perhaps as a repr() of bits of the data),
not as the full SELECT query, and produced bogus SQL which the
server promptly complained about.

Any hints on how to go about this and make the server do all the
work?  Push come to shove, I can monkey with an .extra() call and
put the SQL in the WHERE clause by hand, but it would be
nice/legible/understandable to use pure Django.

Thanks,

-tkc





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



Re: new forms - problem populating with data from a table

2007-02-10 Thread Honza Král
On 2/10/07, Lawrence Oluyede <[EMAIL PROTECTED]> wrote:
>
> > I now want to take an existing user record and create an edit account
> > form, where the data entered by the user in the registration form is
> > represented and available to edit. Seemed simple when I set out to do
> > it, but I can't seem to populate the form.
>
> It's pretty easy. You provide a page with the edit link and you create
> a user_edit view or whatever.
>
> Now in that view you simply check if the user is authenticated and
> then get his id.
>
> > Should I define which data goes into the form fields using the
> > 'initial' data in the Form definition? If so, how would I do this,
> > because I don't know the user_id and can't place a -
> > userid=request.user.id request in this definition.
>
> I don't really understand why you can't but you don't need the ID
> because the authenticated user is already in request.user attribute
>
> Anyway the pattern is:
>
> def profile_edit(request):
> if not request.user.is_authenticated():
> # blah blah
>
> if request.method == "POST":
> new_data = request.POST.copy()

is there any reason why you copy the data? the form doesn't need the
data to be mutable, so there is no need for this.

>
> form = UserEditForm(new_data)
> if form.is_valid():
> clean_data = form.clean_data
> # blah blah
> return HttpResponseRedirect("/whatever/")
> else:
> data = _get_user_data(request)
> form = UserEditForm(initial=data)
>
> context = Context({'form': form})
> return render_to_response('blahblah/account.html', context)
>
> In this way when the page is accesed with a GET you call
> _get_user_data() to retrieve the data to put in the form otherwise you
> check for errors and validate.
>
> In _get_user_data() you actually populate the dictionary with
> something like this:
>
> def _get_customer_profile_data(request):
> first_name = request.user.first_name
> last_name = request.user.last_name
> # go on with the other fields
>
> # if you have a profile associated
> user_profile = request.user.get_profile()
> whatever = user_profile.whatever
> del user_profile
> return locals()

I prefer constructing a dict manually than to mess around with python
internals, but that is really just a matter of personal preference.

>
> HTH
>
> --
> Lawrence, oluyede.org - neropercaso.it
> "It is difficult to get a man to understand
> something when his salary depends on not
> understanding it" - Upton Sinclair
>
> >
>


-- 
Honza Kr�l
E-Mail: [EMAIL PROTECTED]
ICQ#:   107471613
Phone:  +420 606 678585

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



Re: new forms - problem populating with data from a table

2007-02-10 Thread Honza Král
On 2/10/07, daev <[EMAIL PROTECTED]> wrote:
>
> On Feb 9, 10:12 pm, "Tipan" <[EMAIL PROTECTED]> wrote:
>
> > else:
> > form=UserAccountForm()
> > return render_to_response('account.html',{'form':form})
> somthing like this:
> form = UserAccountForm( user.__dict__ )

you would probably want to pass it as `initial` kwarg, when you pass
it like this, it will get validated, which is not always what you
want... for example if the form has more requirements than your model,
the form would render itself with errors even when displayed for the
first time.

>
>
> >
>


-- 
Honza Kr�l
E-Mail: [EMAIL PROTECTED]
ICQ#:   107471613
Phone:  +420 606 678585

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



Re: new forms - problem populating with data from a table

2007-02-10 Thread daev

On Feb 9, 10:12 pm, "Tipan" <[EMAIL PROTECTED]> wrote:

> else:
> form=UserAccountForm()
> return render_to_response('account.html',{'form':form})
somthing like this:
form = UserAccountForm( user.__dict__ )


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



Re: Use of post_save on newly created objects

2007-02-10 Thread Benjamin Slavin

On 2/9/07, Malcolm Tredinnick <[EMAIL PROTECTED]> wrote:
>
> Using the signal system might be overkill here. Can you achieve whatever
> you want with your own save() method (remember that you can then call
> the model's default save() method after doing your own stuff)?
>

Malcom,

Thanks for the quick reply.  This was my original thought... yes, I
can do what I want in my own save() method, but it feels inelegant
(and, in my case, would violate DRY).

It seems like post-object-creation logic could be a common design
pattern in more complex applications, so a signal might be worth
consideration.  Also, a signal would solve this problem in the case of
a self-assigned pk value... though it's not an issue for me.

For those following along at home, Malcom's suggestion could be
implemented as something like the following
===
class MyModelName(models.Model):
   def save(self):
  pre_save_id = self.id
  super(MyModelName, self).save()
  if not pre_save_id:
 ... my code ...
===

Thanks,
  - Ben

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



Re: DB API - dict of emails

2007-02-10 Thread Ned Batchelder
But is is simple to convert what you have into what you want:

l = 
User.objects.filter(username__in=['foo','bar']).values('username', 'email')
emails = dict([(d['username'], d['email']) for d in l])

It would be a little simpler like this:

emails = dict([(r.username, r.email) for r in 
User.objects.filter(username__in=['foo','bar'])])

The dict() built-in accepts a number of forms of arguments.  One is a 
list of pairs, each of which becomes a key and value in the resulting 
dictionary.

--Ned.

Malcolm Tredinnick wrote:
> Hi Dirk,
>
> On Sat, 2007-02-10 at 12:02 +0100, Dirk Eschler wrote:
>   
>> Hello,
>>
>> i'm trying to get a dict of emails with usernames as keys.
>>
>> User.objects.filter(username__in=['foo', 'bar']).values('username', 'email')
>>
>> The above returns a list of dicts:
>> [{'username': 'foo', 'email': '[EMAIL PROTECTED]'}, 
>> {'username': 'bar', 'email': '[EMAIL PROTECTED]'}]
>>
>> Is it possible to get a dict like this with Django's db api?:
>> {'foo':'[EMAIL PROTECTED]', 'bar':'[EMAIL PROTECTED]'}
>> 
>
> No, it is not possible to get that sort of dictionary back directly from
> Django.
>
> Regards,
> Malcolm
>
>
>
> >
>
>
>
>   

-- 
Ned Batchelder, http://nedbatchelder.com


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



Re: image response from Httpresponse

2007-02-10 Thread Ned Batchelder

You want something like this:

image = Image.open('/home/www-data/html/picture_lib/0002/0002.jpg')
response = HttpResponse(mimetype='image/jpeg')
image.save(response, "JPEG")
return response()

The response object is file-like, you can write your content data to it, 
and the image.save() method takes a file-like object and writes the 
image data to it.

--Ned.

Lasse Borchard wrote:
> Hi all,
>
> one simple quest, but i dont find anything at google...
> Ive an image gallery and i dont want to store the images
> in my "static" (handler none) directory, because to view 
> the image it is necesaary to be logged in.
> Therefore django must serve the images. But i'm sadly still
> a newbie. 
>
> I tried like this:
>
> from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
> import os, glob, re
> # from project_knauf.login import login
> from PIL import Image, ImageOps
>
> def foobar(request):
>   image = Image.open('/home/www-data/html/picture_lib/0002/0002.jpg')
>   response = HttpResponse(content='image',mimetype='image/jpeg')
>   return response()
>
> Is it completely wrong? Please help... 
>
> Thanks, Lasse
>
> >
>
>
>
>   

-- 
Ned Batchelder, http://nedbatchelder.com

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



Re: Running django with stackless

2007-02-10 Thread James Tauber

Is your mention of webpy everywhere instead of Django a cut-and-paste  
error?

Are you really asking about django or about webpy?

On 10/02/2007, at 7:30 AM, krypton wrote:

>
> Guys I m using threads to use concurrecy in my webapps and I find it
> to be needlessly slow, because most of the stuff thatI try to do with
> the thread are like, send messages, update a long running thread,
> update rss feeds etcc., ie they do not need context and Hence i do not
> need threads
>
> Upon researching I found an implementation of python that doesnt  
> use C-
> Stacks and hence supports Co-routines. Here is my question. I want to
> use webpy with stackless python.
>
> The problem I m facing is there are parts of webpy that are hacked
> with frame operations. Is there any one who has webpy running on
> stackless. If so please share the patch
>
> Thanks a lot Krypton


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



Re: Installed apps settings, necessary?

2007-02-10 Thread James Tauber

They need to be in INSTALLED_APPS for syncdb to pick up the models  
and make any necessary additions to the database.

There may be other uses as well (contrib.admin might use it too, for  
example) but I'm not sure.

James

On 09/02/2007, at 11:23 AM, voltron wrote:

>
> Hi all, going bto install apps, one must add them to ty the book, the
> INSTALLED_APPS tuple setting, I noticed however that one that one can
> wire up views and in app directories and they work fine even if not
> added to the tuple in the settings file.
>
> My question:
>
> what are the advantages of adding the apps to the settings file?


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



image response from Httpresponse

2007-02-10 Thread Lasse Borchard

Hi all,

one simple quest, but i dont find anything at google...
Ive an image gallery and i dont want to store the images
in my "static" (handler none) directory, because to view 
the image it is necesaary to be logged in.
Therefore django must serve the images. But i'm sadly still
a newbie. 

I tried like this:

from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
import os, glob, re
# from project_knauf.login import login
from PIL import Image, ImageOps

def foobar(request):
image = Image.open('/home/www-data/html/picture_lib/0002/0002.jpg')
response = HttpResponse(content='image',mimetype='image/jpeg')
return response()

Is it completely wrong? Please help... 

Thanks, Lasse

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



Re: DB API - dict of emails

2007-02-10 Thread Dirk Eschler

On Samstag, 10. Februar 2007, Malcolm Tredinnick wrote:
> Hi Dirk,
>
> On Sat, 2007-02-10 at 12:02 +0100, Dirk Eschler wrote:
> > Hello,
> >
> > i'm trying to get a dict of emails with usernames as keys.
> >
> > User.objects.filter(username__in=['foo', 'bar']).values('username',
> > 'email')
> >
> > The above returns a list of dicts:
> > [{'username': 'foo', 'email': '[EMAIL PROTECTED]'},
> > {'username': 'bar', 'email': '[EMAIL PROTECTED]'}]
> >
> > Is it possible to get a dict like this with Django's db api?:
> > {'foo':'[EMAIL PROTECTED]', 'bar':'[EMAIL PROTECTED]'}
>
> No, it is not possible to get that sort of dictionary back directly from
> Django.
>
> Regards,
> Malcolm

I see, thanks anyway!

Best Regards
Dirk Eschler

-- 
Dirk Eschler 
http://www.krusader.org

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



Re: DB API - dict of emails

2007-02-10 Thread Malcolm Tredinnick

Hi Dirk,

On Sat, 2007-02-10 at 12:02 +0100, Dirk Eschler wrote:
> Hello,
> 
> i'm trying to get a dict of emails with usernames as keys.
> 
> User.objects.filter(username__in=['foo', 'bar']).values('username', 'email')
> 
> The above returns a list of dicts:
> [{'username': 'foo', 'email': '[EMAIL PROTECTED]'}, 
> {'username': 'bar', 'email': '[EMAIL PROTECTED]'}]
> 
> Is it possible to get a dict like this with Django's db api?:
> {'foo':'[EMAIL PROTECTED]', 'bar':'[EMAIL PROTECTED]'}

No, it is not possible to get that sort of dictionary back directly from
Django.

Regards,
Malcolm



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



DB API - dict of emails

2007-02-10 Thread Dirk Eschler

Hello,

i'm trying to get a dict of emails with usernames as keys.

User.objects.filter(username__in=['foo', 'bar']).values('username', 'email')

The above returns a list of dicts:
[{'username': 'foo', 'email': '[EMAIL PROTECTED]'}, 
{'username': 'bar', 'email': '[EMAIL PROTECTED]'}]

Is it possible to get a dict like this with Django's db api?:
{'foo':'[EMAIL PROTECTED]', 'bar':'[EMAIL PROTECTED]'}

Best Regards,
Dirk Eschler

-- 
Dirk Eschler 
http://www.krusader.org

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



Re: new forms - problem populating with data from a table

2007-02-10 Thread Lawrence Oluyede

> I now want to take an existing user record and create an edit account
> form, where the data entered by the user in the registration form is
> represented and available to edit. Seemed simple when I set out to do
> it, but I can't seem to populate the form.

It's pretty easy. You provide a page with the edit link and you create
a user_edit view or whatever.

Now in that view you simply check if the user is authenticated and
then get his id.

> Should I define which data goes into the form fields using the
> 'initial' data in the Form definition? If so, how would I do this,
> because I don't know the user_id and can't place a -
> userid=request.user.id request in this definition.

I don't really understand why you can't but you don't need the ID
because the authenticated user is already in request.user attribute

Anyway the pattern is:

def profile_edit(request):
if not request.user.is_authenticated():
# blah blah

if request.method == "POST":
new_data = request.POST.copy()

form = UserEditForm(new_data)
if form.is_valid():
clean_data = form.clean_data
# blah blah
return HttpResponseRedirect("/whatever/")
else:
data = _get_user_data(request)
form = UserEditForm(initial=data)

context = Context({'form': form})
return render_to_response('blahblah/account.html', context)

In this way when the page is accesed with a GET you call
_get_user_data() to retrieve the data to put in the form otherwise you
check for errors and validate.

In _get_user_data() you actually populate the dictionary with
something like this:

def _get_customer_profile_data(request):
first_name = request.user.first_name
last_name = request.user.last_name
# go on with the other fields

# if you have a profile associated
user_profile = request.user.get_profile()
whatever = user_profile.whatever
del user_profile
return locals()

HTH

-- 
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand
something when his salary depends on not
understanding it" - Upton Sinclair

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



Re: ForeignKey, null, and schema evolution

2007-02-10 Thread Malcolm Tredinnick

On Sat, 2007-02-10 at 03:34 -0500, David Abrahams wrote:
> 
> In my attempt to use 
> 
>ForeignKey(Track, null=True) 
> 
> When I actually tried to use a null Track value, I got:
[...traceback snipped...]
> 
> ProgrammingError at /admin/program/session/15/
> ERROR: invalid input syntax for integer: "" SELECT 
> "program_session"."id","program_session"."title","program_session"."short_title","program_session"."description","program_session"."start_id","program_session"."track_id","program_session"."duration"
>  FROM "program_session" INNER JOIN "program_timedivision" AS 
> "program_session__start" ON "program_session"."start_id" = 
> "program_session__start"."id" WHERE ("program_session__start"."id" ILIKE '40' 
> AND "program_session"."track_id" = '')
> 
> My wild guess here is that this happens because track_id is the primary key
> and thus expects an integer value; had I made the track name its
> primary key it might've worked (?).  Anyway, if I want to make that
> change at this point, I don't know how to do so without losing my
> valuable data.  Any help you can offer me would be very much
> appreciated.

Can you give a little more information about how you triggered this
error? It looks like you are doing something in the admin, but I am
using null=True foreign keys through the admin successfully without
doing anything special, so it's not totally impossible. It shows up fine
in the admin system and the database stores the reference as a NULL (in
my case). And I'm using PostgreSQL, too, so it's not a db-specific thing
that I can see (although I'm using psycopg1, not psycopg2).

If you triggered the problem just by trying to add a record in the admin
and leaving the "track" reference field empty, it's going to be a little
hard to debug remotely. Try creating a smaller project with a trimmed
down model -- doing the standard "remove stuff until it starts working
or you are only left with the ForeignKey" process.

I can't place what portion of the admin is generating the query you are
seeing, so any information you can provide would be useful.

Regards,
Malcolm


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



ForeignKey, null, and schema evolution

2007-02-10 Thread David Abrahams


In my attempt to use 

   ForeignKey(Track, null=True) 

When I actually tried to use a null Track value, I got:

  Traceback (most recent call last):
  File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py" in 
get_response
77. response = callback(request, *callback_args, **callback_kwargs)
  File 
"/usr/lib/python2.4/site-packages/django/contrib/admin/views/decorators.py" in 
_checklogin
55. return view_func(request, *args, **kwargs)
  File "/usr/lib/python2.4/site-packages/django/views/decorators/cache.py" in 
_wrapped_view_func
39. response = view_func(request, *args, **kwargs)
  File "/usr/lib/python2.4/site-packages/django/contrib/admin/views/main.py" in 
change_stage
325. errors = manipulator.get_validation_errors(new_data)
  File "/usr/lib/python2.4/site-packages/django/oldforms/__init__.py" in 
get_validation_errors
59. errors.update(field.get_validation_errors(new_data))
  File "/usr/lib/python2.4/site-packages/django/oldforms/__init__.py" in 
get_validation_errors
357. self.run_validator(new_data, validator)
  File "/usr/lib/python2.4/site-packages/django/oldforms/__init__.py" in 
run_validator
347. validator(new_data.get(self.field_name, ''), new_data)
  File "/usr/lib/python2.4/site-packages/django/db/models/manipulators.py" in 
manipulator_validator_unique_together
299. old_obj = self.manager.get(**kwargs)
  File "/usr/lib/python2.4/site-packages/django/db/models/manager.py" in get
67. return self.get_query_set().get(*args, **kwargs)
  File "/usr/lib/python2.4/site-packages/django/db/models/query.py" in get
211. obj_list = list(clone)
  File "/usr/lib/python2.4/site-packages/django/db/models/query.py" in __iter__
103. return iter(self._get_data())
  File "/usr/lib/python2.4/site-packages/django/db/models/query.py" in _get_data
430. self._result_cache = list(self.iterator())
  File "/usr/lib/python2.4/site-packages/django/db/models/query.py" in iterator
172. cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + 
",".join(select) + sql, params)
  File "/usr/lib/python2.4/site-packages/django/db/backends/util.py" in execute
12. return self.cursor.execute(sql, params)
  File "/usr/lib/python2.4/site-packages/django/db/backends/postgresql/base.py" 
in execute
43. return self.cursor.execute(sql, [smart_basestring(p, self.charset) for 
p in params])

ProgrammingError at /admin/program/session/15/
ERROR: invalid input syntax for integer: "" SELECT 
"program_session"."id","program_session"."title","program_session"."short_title","program_session"."description","program_session"."start_id","program_session"."track_id","program_session"."duration"
 FROM "program_session" INNER JOIN "program_timedivision" AS 
"program_session__start" ON "program_session"."start_id" = 
"program_session__start"."id" WHERE ("program_session__start"."id" ILIKE '40' 
AND "program_session"."track_id" = '')

My wild guess here is that this happens because track_id is the primary key
and thus expects an integer value; had I made the track name its
primary key it might've worked (?).  Anyway, if I want to make that
change at this point, I don't know how to do so without losing my
valuable data.  Any help you can offer me would be very much
appreciated.

Thanks,

P.S. I've seen hints elsewhere that you also need blank=True, but that had
no effect for me.
-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com


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



Re: how to make a list of allowable arguments for filter()

2007-02-10 Thread Malcolm Tredinnick

On Fri, 2007-02-09 at 23:22 -0800, abe wrote:
> >
> > I really tried hard to understand your problem, but then my brain
> > started to leak out of my ears and I had to stop. :-(
> >
> > Could you post an example of how all these models are related? You seem
> > to have Relmodl2, model2 and model1 and I'm not sure what all the
> > linkages are.
> >
> > I think what you are asking is why does the reverse end of a ForeignKey
> > show up in get_all_related_objects(), but the forward direction does
> > not. If that is the question, the forward direction (the ForeignKey
> > field itself), is just an object of class ForeignKey in the _meta.fields
> > attribute on the model it is defined on. So you need to inspect the
> > class types in _meta.fields to see which are the forwards relations.
> >
> > If that isn't your question, I apologise and ask only for a simple
> > example to illustrate the problem.
> >
> > Regards,
> > Malcolm
> 
> 
> 
> sorry, shouldn't post so late I guess...
> 
> I would like to make a list of allowable arguments for filter
> to supply that as a selection list on a search page.
> 
> so I have to get a list of 'model__field' like strings
> derived from  models (models.get_all_models())
> 
> 
> class Poll(models.Model):
> question = models.CharField(maxlength=200)
> pub_date = models.DateTimeField('date published')
> 
> 
> class Choice(models.Model):
> poll = models.ForeignKey(Poll)
> choice = models.CharField(maxlength=200)
> votes = models.IntegerField()

OK, that's what I suspected, but thanks for the clear example.

[...]
> Now you seem to say that the answer is in here,
> 
> 
> In [18]: [f for f in Choice._meta.fields]
> Out[18]:
> [,
>  ,
>  ,
>  ]
> 
> which I can see. but how do a make an expression to test for
> foreignkey
> (except for  'fields.related' in `f` which seems a bit clumsy)

One way would be:

   [f for f in Choice._meta.fields if f.rel]

That will catch ManyToMany and OneToOne fields as well. For non-relation
fields, the "rel" attribute is None. For relation fields, it points to
the class that does all the heavy lifting for the relation, but that
isn't important here. Just the fact that f.rel will only be non-None for
relation fields.

> and then of course I would like to find the 2nd (or higher) order
> cases too
> 
> 'model1__model2__field_of_model2'
> 
> any simple ways to find those?

You could operate iteratively: start with a list of all your models that
are related to the current one. Do the same process to those and store
any *new* model names that appear. Repeat until no new names appear.

The reason you need to track new names (versus all names) is to avoid
infinite loops (the simple case being a model that has a ForeignKey to
itself). How to represent loops in your result page is something you'll
need to think about.

Regards,
Malcolm



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