problem with milliseconds and mysql database

2009-07-24 Thread Asinox

Hi, guy, i have a problem trying to save "datetime" in mysql.

the problem is that mysql dont need milliseconds in the datatime
field...

how ill send datatime in format "2009-12-12  1:25:30" without that
python and Django say: Enter a valid date/time in -MM-DD HH:MM[:ss
[.uu]] format  ??

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



Re: A confusing traceback.

2009-07-24 Thread cornjuliox

Thanks.

On Jul 24, 11:04 pm, Daniel Roseman  wrote:
> On Jul 24, 3:13 pm, cornjuliox  wrote:
> 
>
> > File "C:\Blog2\..\Blog2\Engine2\models.py" in save
> >   48.         super(Entry).save()
>
> > Exception Type: AttributeError at /admin_add/
> > Exception Value: 'super' object has no attribute 'save'
>
> > Am I not supposed to be using 'super' here?
>
> The signature for super() is super(MyClass, self). Your save method
> should read:
>
>     def save(self, force_insert=False, force_update=False):
>         # Since I'm using a custom form, I've got to slugify by hand
>         # before the model is saved.
>         unique_slugify(self, "title")
>         super(Entry, self).save(force_insert, force_update)
>
> --
> DR.
--~--~-~--~~~---~--~~
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: ImageFile bug? (Re: ImageField questions)

2009-07-24 Thread Rusty Greer

On Fri, Jul 24, 2009 at 9:49 AM, Jacob Kaplan-Moss wrote:
>
> On Fri, Jul 24, 2009 at 8:23 AM, Rusty Greer wrote:
>> from what i can tell, get_image_dimensions in
>> django/core/files/images.py seems to open the files but never closes
>> them.  is this a bug?
>
> Yes, it was #8817 (http://code.djangoproject.com/ticket/8817) which
> was fixed a few months ago
> (http://code.djangoproject.com/changeset/10708).
>
> So the fix is in the 1.1 release candidate released earlier this week,
> and will be in the 1.1 final and also in the next release of the 1.0.X
> series.
>
> Jacob
>

that bug actually doesn't fix my case.  if i alter the patch to just
do a file.close() in all cases, it works.  is there another patch to
close the file opened outside of this class?

--~--~-~--~~~---~--~~
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: Signals API

2009-07-24 Thread Russell Keith-Magee

On Sat, Jul 25, 2009 at 8:42 AM, Glenn Maynard wrote:
>
> Is the Signals API public?  There's
> http://docs.djangoproject.com/en/dev/topics/signals/, which explains
> connecting to signals (so Signal.connect is public), but the rest of
> Signal, eg. Signal.disconnect, doesn't seem to be in there anywhere.
> Google can't find the Signal.disconnect docstring
> (site:http://docs.djangoproject.com/en/ "The registered receiver to
> disconnect." - did not match any documents).
>
> It seems intended to be public, but I can only find disconnect
> mentioned in 1.0-porting-guide (site:http://docs.djangoproject.com/en/
> signal disconnect).

This is oversight, not intention. Yes, the signals API is public, and
all the obvious apis (connect, disconnect, etc) should be fully
documented. If they're not, you've found something that needs to be
corrected.

Yours,
Russ Magee %-)
> --
> Glenn Maynard
>
> >
>

--~--~-~--~~~---~--~~
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: Database connection closed after each request?

2009-07-24 Thread Andy

On Jul 24, 8:54 pm, Alex Gaynor  wrote:
> "Seen under this light, the additional 150ms latency resulting from non-
> persistent DB connection is huge - it implies almost 30% fewer
> customer orders. And it has nothing to do with traffic."
>
> I'd just like to take a moment to point out that that simply *cannot*
> be, else the only logical conclusion would be that .5s of latency
> results in 0 sales, which plainly makes no sense.

Actually it doesn't mean that at all.

First of all, the 10% decrease in order for each additional 50ms
increase in latency is *multiplicative*, NOT additive. For the 150ms
increase in latency that non-persistent connection costs you, the
decrease in order is 1 - 0.9^3 = 27.1%, hence I wrote "almost 30%"

Hence for a 0.5s increase in latency, *if the relationship still holds
over a range that big*, the corresponding drop in order would be 1-
0.9^10 = 65%. Which isn't exactly impossible. But my guess is for
increase in latency that large, the original "50ms results in 10%
drop" relationship will no longer holds.

Regardless, the point is that latency is a big deal whether your site
is large or small. Even a small latency increase can have a big impact
on user behavior. Telling every mom & pop site owner out there "Go set
up pgpool or hack the Django signal handler if you don't want high
latency" is not very user friendly. Especially when the solution
(providing optional persistent DB connection) is relatively simple.

--~--~-~--~~~---~--~~
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: Database connection closed after each request?

2009-07-24 Thread James Bennett

On Fri, Jul 24, 2009 at 7:55 PM, Glenn Maynard wrote:
> There are lots of requests for ways to build specific types of
> queries, too.  You can't really commit a QuerySet method for one thing
> and then...

So, let's walk through this logically.

Suppose we start with a patch which does the sort of thing you
apparently want: hold on to the connection, and reset it after each
request/response cycle. That patch would never get committed, because
it would have even worse side effects (see: "spinning up a server
process ties up a DB handle for as long as the process lives?") and
could quite realistically cause resource starvation.

How do we avoid that? Well, we'd need some way to say "I'm done with
this connection for now but I'll be needing a connection again soon,
so hang on to it to avoid the overhead of re-establishing it". Which
is pretty much the definition of connection pooling.

So we see that this isn't a pointless slippery-slope argument:
connection pooling is an inevitable outcome of your approach, just one
you've yet to accept.

But it gets worse: you'd want this mechanism to be independent of the
web server processes/threads in which the connections are used,
because you don't want to have to have one connection pool per server
process (since that just reintroduces the problem of latency every
time you spin one up and increases overhead and code complexity) and
you don't want the connection pool to be killed if the process which
hosted it gets recycled by the server. Which points to... an external
connection-pooling utility.

Such utilities already exist and are usable right now. They don't
belong in Django (for many reasons, "don't reinvent the wheel" being
only one of them).


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



Re: Database connection closed after each request?

2009-07-24 Thread Glenn Maynard
On Fri, Jul 24, 2009 at 8:36 PM, Andy wrote:
> Seen under this light, the additional 150ms latency resulting from non-
> persistent DB connection is huge - it implies almost 30% fewer
> customer orders. And it has nothing to do with traffic.

By the way, I switched my connections from TCP to a Unix socket with
local authentication and it dropped to 5-10ms.  (I suspect it was
setting up SSL to localhost--seems like Postgres should know better,
but I havn't investigated.)  I still consider 5-10ms significant (all
delays are cumulative and the framework should have a small baseline
"latency footprint"), but I havn't done enough benchmarking and timing
yet, and obviously that's an order of magnitude lower.

Also, you may be connecting to a database on another server, or local
authentication may not be available; not reconnecting for each request
seems just like sensible behavior unless you really are using a pooler
and explicitly don't want it to.  It's easy to be stuck with a set
configuration on a shared server, and if you're stuck with a 150ms
configuration, that's a perceptible delay that's easily avoided.

I've attached the change as I'm running it now.  I could isolate it
outside of a patch (disconnect the signal, as James suggested, and
connect my own), but it does need to know a little about the backend
internals (on Postgres, to set the isolation level; and resetting the
connection will be different with other databases).

(Obviously, this isn't anything like a submittable patch; I'm just
making it available since he asked.)

> I'd just like to take a moment to point out that that simply *cannot*
> be, else the only logical conclusion would be that .5s of latency
> results in 0 sales, which plainly makes no sense.

I suspect the actual formula is something like pow(0.9,
(seconds_latency / 0.050)); in other words, 500ms latency would imply
34.8% as many sales.  That's pretty believable.

-- 
Glenn Maynard

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

Index: db/__init__.py
===
--- db/__init__.py	(revision 11286)
+++ db/__init__.py	(working copy)
@@ -63,6 +63,10 @@
 # when a Django request is finished.
 def close_connection(**kwargs):
 connection.close()
+#signals.request_finished.connect(reset_connection)
+
+def reset_connection(**kwargs):
+connection._reset()
 signals.request_finished.connect(close_connection)
 
 # Register an event that resets connection.queries
Index: db/backends/postgresql_psycopg2/base.py
===
--- db/backends/postgresql_psycopg2/base.py	(revision 11286)
+++ db/backends/postgresql_psycopg2/base.py	(working copy)
@@ -73,6 +73,19 @@
 self.introspection = DatabaseIntrospection(self)
 self.validation = BaseDatabaseValidation()
 
+def _reset(self):
+if self.connection is None:
+return
+cursor = self._cursor()
+cursor.execute("ABORT; RESET ALL; SET SESSION AUTHORIZATION DEFAULT;")
+
+autocommit = self.settings_dict["DATABASE_OPTIONS"].get('autocommit', False)
+
+# Work around a psycopg2 bug: it doesn't know we just reset autocommit, so it swallows
+# the _set_isolation_level call.
+self._set_isolation_level(int(autocommit))
+self._set_isolation_level(int(not autocommit))
+
 def _cursor(self):
 set_tz = False
 settings_dict = self.settings_dict


Re: Database connection closed after each request?

2009-07-24 Thread Glenn Maynard

On Fri, Jul 24, 2009 at 8:17 PM, James Bennett wrote:
> While the specific thing you personally are asking for might not be
> that much, we can't really commit it to Django and then say "Hey, we
> only did this for Glenn and nobody else gets to ask for features
> building on it". And since there have already been multiple requests
> for Django to grow full-blown connection-pooling utilities, I feel
> pretty confident that's where it would end up.

There are lots of requests for ways to build specific types of
queries, too.  You can't really commit a QuerySet method for one thing
and then...

Anyway, even if I was to put together a patch for this, it wouldn't be
for quite a while--not until after I've tested and used it in
production for quite a while, done more extensive benchmarking, and in
any case I wouldn't submit anything but bug reports right now with the
tracker so (understandably) backlogged from the release freeze.  So
relax, I'm not jumping head-first into this.

-- 
Glenn Maynard

--~--~-~--~~~---~--~~
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: Database connection closed after each request?

2009-07-24 Thread Alex Gaynor

On Fri, Jul 24, 2009 at 8:36 PM, Andy wrote:
>
> On Jul 24, 4:39 pm, James Bennett  wrote:
>> Except this is what it turns into. So suppose a patch is added which
>> does nothing except keep the database connection open; well, that's
>> problematic because it means a server process/thread that's not
>> handling a request at the moment is still tying up a handle to a DB
>> connection. So somebody will say it'd be much better if Django
>> maintained a pool of connections independent of request/response
>> cycles, and just doled them out as needed.
>
> I think you're mixing 2 different things together: persistent
> connection & connection pooling.
>
> There's no reason that you can't have persistent connection without
> connection pooling.
>
> For connection pooling you can make an argument whether it belongs in
> an ORM or not (although SQLAlchemy supports connection pooling just
> fine)
>
> But on the other hand if all a user wants is simple persistent
> connection then it would seem logical for the ORM to provide that.
>
> Ideally Django should offer choices to users: if a user doesn't mind
> tearing down and building up a DB connection every time a request is
> processed, he could use non-persistent connection, but if he wants to
> save that time & reuse DB connection, he should be able to choose
> persistent connection.
>
>
>>  if you've got enough traffic
>> through your app that the overhead of DB connections is problematic,
>> you should be using one of those tools.
>
> But this isn't about traffic at all. It's about latency, which has
> nothing to do with traffic.
>
> Amazon has done studies on the effects of response time. They varied
> the response times of their website and observed the resultant changes
> in user behavior. What they found is that for every 50ms increase in
> response time, the rate at which users order an item drops by 10%.
>
> Seen under this light, the additional 150ms latency resulting from non-
> persistent DB connection is huge - it implies almost 30% fewer
> customer orders. And it has nothing to do with traffic.
>
> I could be running a tiny e-commerce site. My traffic could be
> minimal. And I probably wouldn't have the expertise/time/money to run
> a pooling system for my tiny site. But I still wouldn't want to lose
> 30% of my orders just because I can't have persistent DB connections.
>
>
>
>
>
> >
>

"Seen under this light, the additional 150ms latency resulting from non-
persistent DB connection is huge - it implies almost 30% fewer
customer orders. And it has nothing to do with traffic."

I'd just like to take a moment to point out that that simply *cannot*
be, else the only logical conclusion would be that .5s of latency
results in 0 sales, which plainly makes no sense.  It's also worth
noting, that as James has pointed out, if you merely want to persist
connections it's a matter of unregistering the signal handler and
registering your own to reset the connection.

Alex

-- 
"I disapprove of what you say, but I will defend to the death your
right to say it." -- Voltaire
"The people's good is the highest law." -- Cicero
"Code can always be simpler than you think, but never as simple as you
want" -- Me

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



Signals API

2009-07-24 Thread Glenn Maynard

Is the Signals API public?  There's
http://docs.djangoproject.com/en/dev/topics/signals/, which explains
connecting to signals (so Signal.connect is public), but the rest of
Signal, eg. Signal.disconnect, doesn't seem to be in there anywhere.
Google can't find the Signal.disconnect docstring
(site:http://docs.djangoproject.com/en/ "The registered receiver to
disconnect." - did not match any documents).

It seems intended to be public, but I can only find disconnect
mentioned in 1.0-porting-guide (site:http://docs.djangoproject.com/en/
signal disconnect).

-- 
Glenn Maynard

--~--~-~--~~~---~--~~
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: Database connection closed after each request?

2009-07-24 Thread Andy

On Jul 23, 10:50 pm, Glenn Maynard  wrote:
> In this case, that's a terrible-performance-by-default approach.
> (It's also not a default, but the only behavior, but I'll probably
> submit a patch to add a setting for this if I don't hit any major
> problems.)

Agreed.

Please share any patches you have.
--~--~-~--~~~---~--~~
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: Database connection closed after each request?

2009-07-24 Thread Andy

On Jul 24, 4:39 pm, James Bennett  wrote:
> Except this is what it turns into. So suppose a patch is added which
> does nothing except keep the database connection open; well, that's
> problematic because it means a server process/thread that's not
> handling a request at the moment is still tying up a handle to a DB
> connection. So somebody will say it'd be much better if Django
> maintained a pool of connections independent of request/response
> cycles, and just doled them out as needed.

I think you're mixing 2 different things together: persistent
connection & connection pooling.

There's no reason that you can't have persistent connection without
connection pooling.

For connection pooling you can make an argument whether it belongs in
an ORM or not (although SQLAlchemy supports connection pooling just
fine)

But on the other hand if all a user wants is simple persistent
connection then it would seem logical for the ORM to provide that.

Ideally Django should offer choices to users: if a user doesn't mind
tearing down and building up a DB connection every time a request is
processed, he could use non-persistent connection, but if he wants to
save that time & reuse DB connection, he should be able to choose
persistent connection.


>  if you've got enough traffic
> through your app that the overhead of DB connections is problematic,
> you should be using one of those tools.

But this isn't about traffic at all. It's about latency, which has
nothing to do with traffic.

Amazon has done studies on the effects of response time. They varied
the response times of their website and observed the resultant changes
in user behavior. What they found is that for every 50ms increase in
response time, the rate at which users order an item drops by 10%.

Seen under this light, the additional 150ms latency resulting from non-
persistent DB connection is huge - it implies almost 30% fewer
customer orders. And it has nothing to do with traffic.

I could be running a tiny e-commerce site. My traffic could be
minimal. And I probably wouldn't have the expertise/time/money to run
a pooling system for my tiny site. But I still wouldn't want to lose
30% of my orders just because I can't have persistent DB connections.





--~--~-~--~~~---~--~~
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: Database connection closed after each request?

2009-07-24 Thread James Bennett

On Fri, Jul 24, 2009 at 7:03 PM, Glenn Maynard wrote:
> What I need is sensible, simple and faster, but since someone else
> might want to turn it into something complex and unnecessary, it
> shouldn't be done?

While the specific thing you personally are asking for might not be
that much, we can't really commit it to Django and then say "Hey, we
only did this for Glenn and nobody else gets to ask for features
building on it". And since there have already been multiple requests
for Django to grow full-blown connection-pooling utilities, I feel
pretty confident that's where it would end up.

If you don't like it, simply detach the signal handler that closes the
connection (and register your own handler that resets the connection).
But Django itself shouldn't add that because it really throws open a
Pandora's box of things which shouldn't be in Django but which will be
demanded anyway.


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



Re: Database connection closed after each request?

2009-07-24 Thread Glenn Maynard

On Fri, Jul 24, 2009 at 4:39 PM, James Bennett wrote:
> Except this is what it turns into. So suppose a patch is added which
> does nothing except keep the database connection open; well, that's
> problematic because it means a server process/thread that's not
> handling a request at the moment is still tying up a handle to a DB
> connection. So somebody will say it'd be much better if Django
> maintained a pool of connections independent of request/response
> cycles, and just doled them out as needed.

What I need is sensible, simple and faster, but since someone else
might want to turn it into something complex and unnecessary, it
shouldn't be done?  Sorry, this argument applies to every change
anyone might possibly make.  There's no "slippery slope" here.  I
don't want a connection pooler (and all the issues that brings, like
not being able to use "local" authentication in Postgres); just to
eliminate needless database reconnections.

-- 
Glenn Maynard

--~--~-~--~~~---~--~~
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: Enforcing requirements for user passwords on admin site

2009-07-24 Thread Scot Hacker

On Jul 22, 8:13 am, Topa  wrote:
> I'd like to require that userpasswordsbe of a certain level of
> complexity when they're added to or changed on the admin site. I see a
> way to do this fairly easily with the password reset view since I can
> pass in a custom form, but I don't see an easy way to do it when
> adding a user or using the password_change view.

I'm going to have to implement the same requirement. Not providing a
way to prevent users from selecting passwords like "123" seems like a
real oversight in a framework of Django's caliber. If anyone is aware
of any recipes, sample code, external apps etc. for enforcing password
strength (in the admin, for starters, though I'd think this could be
established system-wide), please post.

Thanks,
Scot


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



Re: How to create this filter

2009-07-24 Thread David

anybody likes to give me help? thanks so much.



On Jul 24, 4:23 pm, David  wrote:
> I used this syntax
>
> .extra(where=['%s >= %s - %s'], params=['criteria1_metric1',
> 'criteria1_metric2',  'criteria1_value'])
>
> however I got error.
>
> On Jul 24, 4:16 pm, David  wrote:
>
>
>
> > Here comes a new problem. I do not know which columns' values to use;
> > all I know is that they are represented with variables. These
> > variables are
>
> > col_var_1, condition_operator, col_var_2, manipulation_operator,
> > constant_value
>
> > where:
> > col_var_1:  col1, or col2, or col3, etc
> > condition_operator: >, >=, <, =, etc
> > col_var_2: col1, or col2, etc
> > manipulation_operator: +, -, x, /
> > constant_value: float value
>
> > in the where clause, I have to use these variables. What's the
> > syntax?
>
> > any help? thanks so much.
>
> > On Jul 24, 2:39 pm, David  wrote:
>
> > > Great. I go to pick up extra() to use.
>
> > > Thanks Tim.
>
> > > On Jul 24, 2:33 pm, Tim Chase  wrote:
>
> > > > > Such a transformation is fine. I found that my Django has no F().
> > > > > Checking the Django doc I saw that this new feature is "New in Django
> > > > > Development version".
>
> > > > > So I have to wait for the new version? Are there any other ways to
> > > > > create such a filter?
> > > > >>  col1_value >= col2_value * 2
>
> > > > >> something like col1__gte=F('col2') * 2
>
> > > > You can always fall back to the .extra() method[1]:
>
> > > >    results = MyFoo.objects.extra(where=[
> > > >      "col1_value >= col2_value * 2",
> > > >      ])
>
> > > > which is how it was done back in the day before ya'll young
> > > > whippersnappers had such fancy shenanigans as F() objects...and
> > > > to get data, we walked up hill, in the snow.  Both ways.  ;-)
>
> > > > -tim
>
> > > > [1]http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-sele...quoted
> > > >  text -
>
> > > - Show quoted text -- Hide quoted text -
>
> > - Show quoted text -- Hide quoted text -
>
> - Show quoted text -
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: How to create this filter

2009-07-24 Thread David

I used this syntax


.extra(where=['%s >= %s - %s'], params=['criteria1_metric1',
'criteria1_metric2',  'criteria1_value'])

however I got error.


On Jul 24, 4:16 pm, David  wrote:
> Here comes a new problem. I do not know which columns' values to use;
> all I know is that they are represented with variables. These
> variables are
>
> col_var_1, condition_operator, col_var_2, manipulation_operator,
> constant_value
>
> where:
> col_var_1:  col1, or col2, or col3, etc
> condition_operator: >, >=, <, =, etc
> col_var_2: col1, or col2, etc
> manipulation_operator: +, -, x, /
> constant_value: float value
>
> in the where clause, I have to use these variables. What's the
> syntax?
>
> any help? thanks so much.
>
> On Jul 24, 2:39 pm, David  wrote:
>
>
>
> > Great. I go to pick up extra() to use.
>
> > Thanks Tim.
>
> > On Jul 24, 2:33 pm, Tim Chase  wrote:
>
> > > > Such a transformation is fine. I found that my Django has no F().
> > > > Checking the Django doc I saw that this new feature is "New in Django
> > > > Development version".
>
> > > > So I have to wait for the new version? Are there any other ways to
> > > > create such a filter?
> > > >>  col1_value >= col2_value * 2
>
> > > >> something like col1__gte=F('col2') * 2
>
> > > You can always fall back to the .extra() method[1]:
>
> > >    results = MyFoo.objects.extra(where=[
> > >      "col1_value >= col2_value * 2",
> > >      ])
>
> > > which is how it was done back in the day before ya'll young
> > > whippersnappers had such fancy shenanigans as F() objects...and
> > > to get data, we walked up hill, in the snow.  Both ways.  ;-)
>
> > > -tim
>
> > > [1]http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-sele...Hide
> > >  quoted text -
>
> > - Show quoted text -- Hide quoted text -
>
> - Show quoted text -
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: How to create this filter

2009-07-24 Thread David

Here comes a new problem. I do not know which columns' values to use;
all I know is that they are represented with variables. These
variables are

col_var_1, condition_operator, col_var_2, manipulation_operator,
constant_value

where:
col_var_1:  col1, or col2, or col3, etc
condition_operator: >, >=, <, =, etc
col_var_2: col1, or col2, etc
manipulation_operator: +, -, x, /
constant_value: float value

in the where clause, I have to use these variables. What's the
syntax?

any help? thanks so much.







On Jul 24, 2:39 pm, David  wrote:
> Great. I go to pick up extra() to use.
>
> Thanks Tim.
>
> On Jul 24, 2:33 pm, Tim Chase  wrote:
>
>
>
> > > Such a transformation is fine. I found that my Django has no F().
> > > Checking the Django doc I saw that this new feature is "New in Django
> > > Development version".
>
> > > So I have to wait for the new version? Are there any other ways to
> > > create such a filter?
> > >>  col1_value >= col2_value * 2
>
> > >> something like col1__gte=F('col2') * 2
>
> > You can always fall back to the .extra() method[1]:
>
> >    results = MyFoo.objects.extra(where=[
> >      "col1_value >= col2_value * 2",
> >      ])
>
> > which is how it was done back in the day before ya'll young
> > whippersnappers had such fancy shenanigans as F() objects...and
> > to get data, we walked up hill, in the snow.  Both ways.  ;-)
>
> > -tim
>
> > [1]http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-sele...-
> >  Hide quoted text -
>
> - Show quoted text -
--~--~-~--~~~---~--~~
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: Where are the admin app icons from?

2009-07-24 Thread Alex Gaynor

On Fri, Jul 24, 2009 at 5:12 PM, Margie wrote:
>
> Hi,
>
> I'm wondering if the icons in the admin app (for example, the
> addlink.gif icon) come from some standard icon (free) icon package
> where there are more goodies of the same sort?  Anyone have any
> pointers for where those came from?
>
> Margie
>
> >
>

I don't know where the Django ones came from (they may have been
custom designed for all I know), but if you're looking for good free
icons I'm quite fond of the famfamfam silk icon set:
http://www.famfamfam.com/lab/icons/silk/

Alex

-- 
"I disapprove of what you say, but I will defend to the death your
right to say it." -- Voltaire
"The people's good is the highest law." -- Cicero
"Code can always be simpler than you think, but never as simple as you
want" -- Me

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



Re: How to create this filter

2009-07-24 Thread David

Great. I go to pick up extra() to use.

Thanks Tim.



On Jul 24, 2:33 pm, Tim Chase  wrote:
> > Such a transformation is fine. I found that my Django has no F().
> > Checking the Django doc I saw that this new feature is "New in Django
> > Development version".
>
> > So I have to wait for the new version? Are there any other ways to
> > create such a filter?
> >>  col1_value >= col2_value * 2
>
> >> something like col1__gte=F('col2') * 2
>
> You can always fall back to the .extra() method[1]:
>
>    results = MyFoo.objects.extra(where=[
>      "col1_value >= col2_value * 2",
>      ])
>
> which is how it was done back in the day before ya'll young
> whippersnappers had such fancy shenanigans as F() objects...and
> to get data, we walked up hill, in the snow.  Both ways.  ;-)
>
> -tim
>
> [1]http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-sele...
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: How to create this filter

2009-07-24 Thread Tim Chase

> Such a transformation is fine. I found that my Django has no F().
> Checking the Django doc I saw that this new feature is "New in Django
> Development version".
> 
> So I have to wait for the new version? Are there any other ways to
> create such a filter?
>>  col1_value >= col2_value * 2
>>
>> something like col1__gte=F('col2') * 2


You can always fall back to the .extra() method[1]:

   results = MyFoo.objects.extra(where=[
 "col1_value >= col2_value * 2",
 ])

which is how it was done back in the day before ya'll young 
whippersnappers had such fancy shenanigans as F() objects...and 
to get data, we walked up hill, in the snow.  Both ways.  ;-)

-tim


[1]
http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none





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



Re: How to create this filter

2009-07-24 Thread David

Such a transformation is fine. I found that my Django has no F().
Checking the Django doc I saw that this new feature is "New in Django
Development version".

So I have to wait for the new version? Are there any other ways to
create such a filter?

Any ideas?

Thanks again.



On Jul 24, 2:01 pm, Frédéric Hébert  wrote:
> It seems to me that you have to transform your fields lookup like that :
>
>  col1_value >= col2_value * 2
>
> something like col1__gte=F('col2') * 2
>
> Frédéric
>
> 2009/7/24 David :
>
>
>
>
>
>
>
> > Hello,
>
> > Here is a table "myTable" with columns of "col1", "col2", "col3", ...,
> > "col5". The types of these columns are all float. Now for two values
> > from any two columns of these columns, I may need to add, or subtract,
> > or multiply or divide these two values. With this result, I do a
> > condition check.
>
> > For example, I want to retrieve all objects that meet "col1_value /
> > col2_value >= 2.0". How to create such a filter? It seems to me that F
> > () might be the right choice, however the document on this part in
> > QuerySet API is quite rough.
>
> > Anybody knows how to create such a filter? or anybody knows any url
> > links that introduce F() in details?
>
> > Thanks so much.
>
> --http://www.openidfrance.fr/fhebert- Hide quoted text -
>
> - Show quoted text -
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Where are the admin app icons from?

2009-07-24 Thread Margie

Hi,

I'm wondering if the icons in the admin app (for example, the
addlink.gif icon) come from some standard icon (free) icon package
where there are more goodies of the same sort?  Anyone have any
pointers for where those came from?

Margie

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



Model Formsets Have an Extra Blank Form?

2009-07-24 Thread derek

I'm following the instructions here:

http://docs.djangoproject.com/en/dev/topics/forms/modelforms/

But when I do this kind of thing:

formset = AuthorFormSet(queryset=Author.objects.filter
(name__startswith='O'))

I always get an extra blank form at the end of my formset - regardless
of how I set up the query set. How can I prevent this?

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



Re: How to create this filter

2009-07-24 Thread Frédéric Hébert

It seems to me that you have to transform your fields lookup like that :

 col1_value >= col2_value * 2

something like col1__gte=F('col2') * 2

Frédéric

2009/7/24 David :
>
> Hello,
>
> Here is a table "myTable" with columns of "col1", "col2", "col3", ...,
> "col5". The types of these columns are all float. Now for two values
> from any two columns of these columns, I may need to add, or subtract,
> or multiply or divide these two values. With this result, I do a
> condition check.
>
> For example, I want to retrieve all objects that meet "col1_value /
> col2_value >= 2.0". How to create such a filter? It seems to me that F
> () might be the right choice, however the document on this part in
> QuerySet API is quite rough.
>
> Anybody knows how to create such a filter? or anybody knows any url
> links that introduce F() in details?
>
> Thanks so much.
> >
>



-- 
http://www.openidfrance.fr/fhebert

--~--~-~--~~~---~--~~
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: Database connection closed after each request?

2009-07-24 Thread James Bennett

On Fri, Jul 24, 2009 at 1:31 AM, Glenn Maynard wrote:
> I see no need for a complex connection pooling service.  You're making
> this sound much more complicated than it is, resulting in people
> needing to use configurations much more complicated than necessary.

Except this is what it turns into. So suppose a patch is added which
does nothing except keep the database connection open; well, that's
problematic because it means a server process/thread that's not
handling a request at the moment is still tying up a handle to a DB
connection. So somebody will say it'd be much better if Django
maintained a pool of connections independent of request/response
cycles, and just doled them out as needed.

And then you need configuration to manage the size of the pool, when
connections get recycled, how to reset connections portably...

And then somebody will notice that it's got all the infrastructure for
pgpool's "poor man's replication" and helpfully submit a patch for
that...

And then we end up in the unenviable state of having wasted a bunch of
time reimplementing features already available in the standard tool
people should've been using from the start, but without getting any of
that tool's useful flexibility (e.g., changing the stuff behind the
pool without changing the application layer).

Or we could just accept that there are tools right now which will do
all this and more for you, and that if you've got enough traffic
through your app that the overhead of DB connections is problematic,
you should be using one of those tools.


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



Re: Middleware that injects data for template

2009-07-24 Thread Tim Chase

Stodge wrote:
> Say I want to inject a piece of data into every page view. For
> now, let's just say I want to inject the current time into
> each page view. I write a piece of middleware that will do it.
> But how? Do I modify the request? Or the view (process_view)?

I understand that this should be done by modifying the request in 
your middleware and then making use of it in your templates (if 
it's to appear on every page, it may (or may not) make sense to 
put it in your base.html template).  This assumes your views are 
using a RequestContext which pass the request object into the 
template as part of the rendering context.

-tim



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



Middleware that injects data for template

2009-07-24 Thread Stodge

Say I want to inject a piece of data into every page view. For now,
let's just say I want to inject the current time into each page view.
I write a piece of middleware that will do it. But how? Do I modify
the request? Or the view (process_view)?
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



How to create this filter

2009-07-24 Thread David

Hello,

Here is a table "myTable" with columns of "col1", "col2", "col3", ...,
"col5". The types of these columns are all float. Now for two values
from any two columns of these columns, I may need to add, or subtract,
or multiply or divide these two values. With this result, I do a
condition check.

For example, I want to retrieve all objects that meet "col1_value /
col2_value >= 2.0". How to create such a filter? It seems to me that F
() might be the right choice, however the document on this part in
QuerySet API is quite rough.

Anybody knows how to create such a filter? or anybody knows any url
links that introduce F() in details?

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



Re: Following part 2 of the tutorial, I get the following error when trying to view /admin/:

2009-07-24 Thread Amit Sethi

On Fri, Jul 24, 2009 at 6:04 PM, ashish wrote:
Well as your error message says , Template does not exist my first
guess would be that you did not Activate the admin site .. if that is
not so , you should have  a look at the section , Customize the look
and feel of admin ... it is talking about the basics of Django's
templating system .


-- 
A-M-I-T S|S

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



Re: How to tell if a fields was modified

2009-07-24 Thread ankit rai
use clean method and use self.instance.fieldname to know previous value and
then compare with the new value.


On Fri, Jul 24, 2009 at 10:50 PM, Tim Chase
wrote:

>
> >> How can I tell which model fields have been modified (this is, the
> >> difference between the Model instance and the data originally retrieved
> >> from the database) from inside the model's save() method?
> >
> > You can always retrieve the model by it's primary key from the db, and
> > then compare self to it.  Something like:
> >
> > def save(stuff_and_junk):
> > existing_instance = self.__class__.objects.get(id=self.id)
> > if existing_instance.attribute != self.attribute:
> > print 'Holy Crap!'
> > super(self.__class__, self).save(stuff_and_junk)
>
> Remembering, of course, that get() can throw an exception if
> you're creating a new object...
>
> -tim
>
>
>
> >
>

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



Re: How to tell if a fields was modified

2009-07-24 Thread Tim Chase

>> How can I tell which model fields have been modified (this is, the 
>> difference between the Model instance and the data originally retrieved 
>> from the database) from inside the model's save() method?
> 
> You can always retrieve the model by it's primary key from the db, and
> then compare self to it.  Something like:
> 
> def save(stuff_and_junk):
> existing_instance = self.__class__.objects.get(id=self.id)
> if existing_instance.attribute != self.attribute:
> print 'Holy Crap!'
> super(self.__class__, self).save(stuff_and_junk)

Remembering, of course, that get() can throw an exception if 
you're creating a new object...

-tim



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



Following part 2 of the tutorial, I get the following error when trying to view /admin/:

2009-07-24 Thread ashish

TemplateDoesNotExist? at /admin/ admin/login.html Request Method: GET
Request URL: http://localhost:8000/admin/ Exception Type:
TemplateDoesNotExist? Exception Value: admin/login.html Exception
Location: C:\PROGRA~1\PYTHON24\Lib\site-packages\django\template
\loader.py in find_template_source, line 72

Template-loader postmortem Django tried loading these templates, in
this order:

Using loader django.template.loaders.filesystem.load_template_source:
Using loader
django.template.loaders.app_directories.load_template_source:
Traceback (innermost last) Switch to copy-and-paste view

C:\PROGRA~1\PYTHON24\Lib\site-packages\django\core\handlers\base.py in
get_response

# Apply view middleware for middleware_method in
self._view_middleware: response = middleware_method(request, callback,
callback_args, callback_kwargs) if response: return response try:
response = callback(request, *callback_args, **callback_kwargs) ...
except Exception, e: # If the view raised an exception, run it through
exception # middleware, and if the exception middleware returns a #
response, use that. Otherwise, reraise the exception. for
middleware_method in self._exception_middleware: response =
middleware_method(request, e)▶ Local vars

Variable Value callback 
callback_args () callback_kwargs {} debug 
e 
exceptions 
mail_admins  middleware_method
> request
, POST:,
COOKIES:{'sessionid': 'ef7d8ca1024c725cabf1bfb1f80a5b9a'}, META:
{'ALLUSERSPROFILE': 'C:\\DOCUME~1\\ALLUSE~1', 'APPDATA': 'C:\\DOCUME~1\
\User1\\APPLIC~1', 'BLASTER': 'A220 I5 D1 P330 T3', 'CLIENTNAME':
'Console', 'COMMONPROGRAMFILES': 'C:\\PROGRA~1\\COMMON~1',
'COMPUTERNAME': 'YOUR-F42298D1A0', 'COMSPEC': 'C:\\WINDOWS\\system32\
\cmd.exe', 'CONTENT_LENGTH': , 'CONTENT_TYPE': 'text/plain',
'DJANGO_SETTINGS_MODULE': 'mysite.settings', 'FP_NO_HOST_CHECK': 'NO',
'GATEWAY_INTERFACE': 'CGI/1.1', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\
\Documents and Settings\\User1', 'HTTP_ACCEPT': 'image/gif, image/x-
xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash,
application/vnd.ms-excel, application/vnd.ms-powerpoint, application/
msword, */*', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
'HTTP_ACCEPT_LANGUAGE': 'en-ie', 'HTTP_CONNECTION': 'Keep-Alive',
'HTTP_COOKIE': 'sessionid=ef7d8ca1024c725cabf1bfb1f80a5b9a',
'HTTP_HOST': 'localhost:8000', 'HTTP_USER_AGENT': 'Mozilla/4.0
(compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)',
'LANG': 'C', 'LOGONSERVER': 'YOUR-F42298D1A0',
'NUMBER_OF_PROCESSORS': '1', 'OS': 'Windows_NT', 'PATH': 'C:\\WINDOWS\
\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\PROGRA~1\\Intel\
\Wireless\\Bin\\;C:\\PROGRA~1\\COMMON~1\\Adobe\\AGL;C:\\PROGRA~1\
\MICROS~2\\80\\Tools\\Binn\\;C:\\PROGRA~1\\COMMON~1\\GTK\\2.0\\bin',
'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH',
'PATH_INFO': '/admin/', 'PROCESSOR_ARCHITECTURE': 'x86',
'PROCESSOR_IDENTIFIER': 'x86 Family 6 Model 13 Stepping 8,
GenuineIntel?', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_REVISION': '0d08',
'PROGRAMFILES': 'C:\\PROGRA~1', 'PROMPT': '$P$G', 'QUERY_STRING': ,
'REMOTE_ADDR': '127.0.0.1', 'REMOTE_HOST': , 'REQUEST_METHOD': 'GET',
'RUN_MAIN': 'true', 'SCRIPT_NAME': , 'SERVER_NAME': 'localhost',
'SERVER_PORT': '8000', 'SERVER_PROTOCOL': 'HTTP/1.1',
'SERVER_SOFTWARE': 'WSGIServer/0.1 Python/2.4.3', 'SESSIONNAME':
'Console', 'SONICCENTRAL': 'C:\\Program Files\\Common Files\\Sonic
Shared\\Sonic Central\\', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\
\WINDOWS', 'TEMP': 'C:\\WINDOWS\\TEMP', 'TMP': 'C:\\WINDOWS\\TEMP',
'TVDUMPFLAGS': '8', 'USERDOMAIN': 'YOUR-F42298D1A0', 'USERNAME':
'User1', 'USERPROFILE': 'C:\\DOCUME~1\\User1', 'wsgi.errors': ', mode 'w' at 0x0096E0B0>, 'wsgi.file_wrapper': , 'wsgi.input':
, 'wsgi.multiprocess': False,
'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme':
'http', 'wsgi.version': (1, 0)}> resolver

response None self  settings 
urlconf 'mysite.urls' urlresolvers 

C:\PROGRA~1\PYTHON24\Lib\site-packages\django\contrib\admin\views
\decorators.py in _checklogin

# If this isn't already the login page, display it. if not
request.POST.has_key(LOGIN_FORM_KEY): if request.POST: message = _
("Please log in again, because your session has expired. Don't worry:
Your submission has been saved.") else: message = "" return
_display_login_form(request, message) ... # Check that the user
accepts cookies. if not request.session.test_cookie_worked(): message
= _("Looks like your browser isn't configured to accept cookies.
Please enable cookies, reload this page, and try again.") return
_display_login_form(request, message)▶ Local vars

Variable Value args () kwargs {} message request , POST:, COOKIES:
{'sessionid': 'ef7d8ca1024c725cabf1bfb1f80a5b9a'}, META:
{'ALLUSERSPROFILE': 'C:\\DOCUME~1\\ALLUSE~1', 'APPDATA': 'C:\\DOCUME~1\
\User1\\APPLIC~1', 'BLASTER': 'A220 I5 D1 P330 T3', 'CLIENTNAME':
'Console', 'COMMONPROGRAMFILES': 'C:\\PROGRA~1\\COMMON~1',
'COMPUTERNAME': 'YOUR-F42298D1A0', 'COMSPEC': 'C:\\WINDOWS\\system32\
\cmd.exe', 'CONTENT_LENGTH

Best way to render 1-to-many relationship in a template

2009-07-24 Thread SweetPete

Hi,

Python/Django newb here.  I have a question regarding the best
approach to rendering 1-to-many relationships in a template.

I have 2 tables, Customers and Cars, where a Customer can have many
Cars, hence the 1-to-many relationship.  I need to display all the
Customers with all their Cars, like this:

Customer1
Car: car1
Car: car2

Customer2
Car: car1
Car: car2
Car: car3
...

I've taken 2 approaches to solving this problem, described below.

The first approach involves creating a complete Customers queryset,
and then using a FOR loop inside the template to create a Cars
queryset, once for each customer.  The problem is obvious: if I have
10,000 customers, the Cars table is going to be queried 10,000 times
(correct?).  The DBA is going to be mad, and I'm going to look
foolish.  Here's the code:

{% for customer in customers %}
{{ customer.full_name }}

{% for car in customer.car_set.all %}
Car: {{ car }}
{% endfor %}

{% endfor %}

My second approach involves both complete Customers and Cars
querysets.  Then, inside the template, iterate through the Cars
queryset based on the current Customer.id, and then output the car.
Here's the code:

{% for customer in customers %}
{{ customer.full_name }}

{% for car in cars %}
{% ifequal car.customer_id customer.id %}
Car: {{ car }}
{% endifequal %}
{% endfor %}

{% endfor %}

I *think* the problem with the 2nd approach is that I'm forcing Python
to iterate through the Cars queryset 10,000 times to find the car(s)
belonging to each driver.

Is there a 3rd, better/best approach to this problem?  Thanks!

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



Re: html text field ...disabled in form?

2009-07-24 Thread Jacob Kaplan-Moss

On Fri, Jul 24, 2009 at 8:57 AM, Asinox wrote:
> how ill make a html text field with attr disabled?

See the ``attrs`` argument to widgets:
http://docs.djangoproject.com/en/dev/ref/forms/widgets/#customizing-widget-instances

Jacob

--~--~-~--~~~---~--~~
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: ImageFile bug? (Re: ImageField questions)

2009-07-24 Thread Jacob Kaplan-Moss

On Fri, Jul 24, 2009 at 8:23 AM, Rusty Greer wrote:
> from what i can tell, get_image_dimensions in
> django/core/files/images.py seems to open the files but never closes
> them.  is this a bug?

Yes, it was #8817 (http://code.djangoproject.com/ticket/8817) which
was fixed a few months ago
(http://code.djangoproject.com/changeset/10708).

So the fix is in the 1.1 release candidate released earlier this week,
and will be in the 1.1 final and also in the next release of the 1.0.X
series.

Jacob

--~--~-~--~~~---~--~~
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: Slugs, why would you ever need to store one in the database?

2009-07-24 Thread Andy Mikhailenko

Just one more addition to the replies above: there's a number of
snippets[1], recipes and packages[2] which introduce purely
autogenerated safe (unique and sometimes also non-ascii-friendly)
slugs without using admin.

Autopopulated slugs, when used in URLs without exposing internal
autoincremented IDs, can be a problem if you change them (to match an
updated title) after the URL is bookmarked or linked somewhere else.
However, PKs can change too (e.g. splitting a topic in a forum or
merging it into another one, etc.), and slugs can help with hiding
away the implementation details so that you can keep the URLs
permanent without imposing unnecessary restrictions on models and
views.

[1] http://djangosnippets.org/tags/slug/
[2] http://pypi.python.org/pypi/django-autoslug

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



Re: How to tell if a fields was modified

2009-07-24 Thread Randy Barlow

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Matias declared:
> How can I tell which model fields have been modified (this is, the 
> difference between the Model instance and the data originally retrieved 
> from the database) from inside the model's save() method?

You can always retrieve the model by it's primary key from the db, and
then compare self to it.  Something like:

def save(stuff_and_junk):
existing_instance = self.__class__.objects.get(id=self.id)
if existing_instance.attribute != self.attribute:
print 'Holy Crap!'
super(self.__class__, self).save(stuff_and_junk)

- --
Randy Barlow
Software Developer
The American Research Institute
http://americanri.com
919.228.4971
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkpp5RwACgkQw3vjPfF7QfWmUgCePIAaqGQ6XFWtdEKa86V98Xij
bnUAnjn758cASuyP8wCPkbOEV6Oa3ZGQ
=NqNX
-END PGP SIGNATURE-

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



How to tell if a fields was modified

2009-07-24 Thread Matias

Hi,

How can I tell which model fields have been modified (this is, the 
difference between the Model instance and the data originally retrieved 
from the database) from inside the model's save() method?


Any idea?

Thanks a lot!


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



html text field ...disabled in form?

2009-07-24 Thread Asinox

hi, guys,

how ill make a html text field with attr disabled?

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



Re: problem with forms, ForeignKey, get_or_create

2009-07-24 Thread Nail

> Have you tried the save_formset of the ModelAdmin?
> http://docs.djangoproject.com/en/dev/ref/contrib/admin/

No, i am trying to create user view, not admin.
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



ImageFile bug? (Re: ImageField questions)

2009-07-24 Thread Rusty Greer

On Thu, Jul 23, 2009 at 5:55 PM, Joshua Russo wrote:
> On Thu, Jul 23, 2009 at 9:31 PM, Rusty Greer  wrote:
>>
>> how do i create a query on the size of an image?
>>
>> for example:
>> class Image(models.Model):
>>
>>    image = models.ImageField(upload_to=upload_to('images'), db_index=True)
>>
>>
>> if i try something like:
>>
>>    for image in Image.objects.filter(image__height_field__gte=100):
>>          # do something
>>
>> i get the following error:
>>
>> django.core.exceptions.FieldError: Join on field 'image' not permitted.
>
> The filters are translated into SQL for the database and the database
> doesn't have a mechanism for reading the image properties. As far as the db
> is concerned it's just another binary field. What I would recommend is to
> create columns for extra information like height and width. Then you can
> override your Image model's save method and extract information and save it
> into the column automatically.
> class Image(models.Model):
>    image = models.ImageField(upload_to=upload_to('images'), db_index=True)
>    height = models.IntegerField()
>    width = models.IntegerField()
>    def save(self, force_insert=False, force_update=False):
>         # The following is sudo code, I have no experience with image
> objects
>         self.height = self.image.height
>         self.width = self.image.width
>         super(Image, self).save(force_insert, force_update) # Call the
> "real" save() method.
> You can read more about models and all the cool stuff  you can do with them
> here: http://docs.djangoproject.com/en/dev/topics/db/models/#topics-db-models
>
>

ok, i have done this.  it seems simple enough.

now i have another issue.  i have a script that imports a few hundred
images into my db.  when i run the script at some point, i get to the
point where i get the following error:

IOError: [Errno 24] Too many open files:
u'/Users/greer/projects/django/static/demo/logos/logo_signs_stars_only_sm0028.png'

from what i can tell, get_image_dimensions in
django/core/files/images.py seems to open the files but never closes
them.  is this a bug?

thanks for any help.

rusty greer

--~--~-~--~~~---~--~~
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: A confusing traceback.

2009-07-24 Thread Daniel Roseman

On Jul 24, 3:13 pm, cornjuliox  wrote:

> File "C:\Blog2\..\Blog2\Engine2\models.py" in save
>   48.         super(Entry).save()
>
> Exception Type: AttributeError at /admin_add/
> Exception Value: 'super' object has no attribute 'save'
>
> Am I not supposed to be using 'super' here?

The signature for super() is super(MyClass, self). Your save method
should read:

def save(self, force_insert=False, force_update=False):
# Since I'm using a custom form, I've got to slugify by hand
# before the model is saved.
unique_slugify(self, "title")
super(Entry, self).save(force_insert, force_update)

--
DR.
--~--~-~--~~~---~--~~
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, multiple domains, multiple locales/languages

2009-07-24 Thread Joshua Russo
I ran into some conceptual problems with lazy vs non-lazy too. Any global
context needs to be lazy. This includes everything declared outside of any
function or class context and the class instance variable declarations (tho
not the declarations made in __init__ or __new__ of a class)
On Fri, Jul 24, 2009 at 10:34 AM, MS  wrote:

>
>
> OK, thanks for suggestion - however it seems the problem was somewhere
> else - I was using ugettext where ugettext_lazy was supposed to be
> used (ex. in forms.py).
> The documentation should be more clear that the choice between
> ugettext and ugettext_lazy is quite important and may lead to strange
> problems.
>
>
> > If me, I would seperate those settings binding to domain from those not.
> > And create setting module for each domain.
> > Then in different virtual host configuration, just set setting module
> > pointing to different setting.py
> >
> > Just my opinion, sorry if it doesn't work for you.
>
> >
>

--~--~-~--~~~---~--~~
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: Admin - related objects when using multiple foreign keys to a parent model

2009-07-24 Thread Haestan


--
From: "Karen Tracey" 
Sent: Friday, July 24, 2009 3:16 PM
To: 
Subject: Re: Admin - related objects when using multiple foreign keys to a 
parent model

> On Fri, Jul 24, 2009 at 9:02 AM, Haestan  wrote:
>
>>
>> Hi,
>>
>> let's assume the following simple model:
>>
>> class Child(models.Model):
>>father = models.ForeignKey(Adult, related_name="father")
>>mother = models.ForeignKey(Adult, related_name="mother")
>>
>> class Adult(models.Model):
>>name = models.CharField(max_length=255)
>>
>> Now, if I try to delete an Adult object in the admin, only "fathers" warn
>> about their children as related objects. If I delete a "mother" with a
>> related Child object, then there is no warning about related objects and
>> their children silently get deleted as well.
>>
>> Is this a bug in the admin application or am I missing something to make
>> this work as intended?
>>
>> Cheers.
>>
>> PS: I'm running 1.0.2
>>
>
> I believe this problem is logged in this ticket:
>
> http://code.djangoproject.com/ticket/6191

thanks alot,

that was exactly the problem. After applying the 
'newforms-admin_deleted_objects.patch' from this ticket, it's now showing 
all the related objects.

Cheers. 


--~--~-~--~~~---~--~~
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: problem with forms, ForeignKey, get_or_create

2009-07-24 Thread Joshua Russo
On Thu, Jul 23, 2009 at 10:53 PM, Nail  wrote:

>
> Hello, developers!
>
> Please help me with one problem. I spent 2 days attempting to solve
> it. And now i have some solution, but i don't like it.
>
> My application manages music tracks.
> There is models: Artist, Album, Track.
> Simply:
>
> class Artist:
>  name = CharField()
>
> class Album:
>  title = CharField()
>  artist = ForeignKey(Artist)
>
> class Track:
>  title = CharField()
>  album = ForeignKey(Album)
>  artist = ForeignKey(Artist)
>
> class FeaturedLink:
>  artist = ForeignKey(Artist)
>  track = ForeignKey(Track)
>  text = CharField()
>
> Some explanations: artist may have several tracks, and track may
> belong to several artists - one primary and some featured (e.g. 50
> cents feat. Justin). text field in FeaturedLink contains "feat.",
> "remix by" etc.
>
> User interface needs to be very simple. For example if user creates
> some album, he enters name of artist(ajax name suggestion helps him),
> title and presses save. If artist with this name doesn't exist, it
> must be created.
> This is not a problem. I create AlbumForm(ModelForm), with artist
> field excluded, define custom char field artist_name. __init__
> provides Initial data for artist_name from instance.artist.name. save
> () method gets artist from existing or creates new
> (Artist.objects.get_or_create(name=artist_name)) and fills
> instance.artist.
>
> Problem is in TrackForm. Primary artist is being filled in without
> problems. But featuredlink_set uses InlineFormSet to be able to edit
> any number of featured links in one form. Inline form set uses default
> ModelForm instances for each model instance. So there will be
> ChoiceField for artist field in FeaturedLink. But i need simple char
> field with behavior as in album form. But i don't find a way to do
> this. Changing a form for InlineFormSet doesn't help, formset never
> calls save() method of form, it saves objects by oneself. Overriding
> save method of inline form set is very complex. It handles to many
> tasks.
>
> And what a solution i found: create custom form field, that will
> accept char data from request data and clean() it to artist id. But i
> think this is not a true solution, because such field clean will
> change database in validation stage.


Have you tried the save_formset of the ModelAdmin?
http://docs.djangoproject.com/en/dev/ref/contrib/admin/

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



A confusing traceback.

2009-07-24 Thread cornjuliox

Could someone lend a hand? Instead of using the built-in admin
interface, I'm trying to build an 'admin page' of my own using
ModelForms, but the problem is that the SlugField won't prepopulate
like it does with the default admin so I've resorted to overriding the
save() method and including a method (that I got from Django Snippets)
that's supposed to slugify the title before the Entry is saved to the
database.

CODE:
def unique_slugify(instance, value, slug_field_name='slug',
queryset=None,
   slug_separator='-'):
"""
Calculates and stores a unique slug of ``value`` for an instance.

``slug_field_name`` should be a string matching the name of the
field to
store the slug in (and the field to check against for uniqueness).

``queryset`` usually doesn't need to be explicitly provided -
it'll default
to using the ``.all()`` queryset from the model's default manager.
"""
slug_field = instance._meta.get_field(slug_field_name)

slug = getattr(instance, slug_field.attname)
slug_len = slug_field.max_length

# Sort out the initial slug, limiting its length if necessary.
slug = slugify(value)
if slug_len:
slug = slug[:slug_len]
slug = _slug_strip(slug, slug_separator)
original_slug = slug

# Create the queryset if one wasn't explicitly provided and
exclude the
# current instance from the queryset.
if queryset is None:
queryset = instance.__class__._default_manager.all()
if instance.pk:
queryset = queryset.exclude(pk=instance.pk)

# Find a unique slug. If one matches, at '-2' to the end and try
again
# (then '-3', etc).
next = 2
while not slug or queryset.filter(**{slug_field_name: slug}):
slug = original_slug
end = '%s%s' % (slug_separator, next)
if slug_len and len(slug) + len(end) > slug_len:
slug = slug[:slug_len-len(end)]
slug = _slug_strip(slug, slug_separator)
slug = '%s%s' % (slug, end)
next += 1

setattr(instance, slug_field.attname, slug)

def _slug_strip(value, separator='-'):
 """
 Cleans up a slug by removing slug separator characters that occur
at the
 beginning or end of a slug.

 If an alternate separator is used, it will also replace any
instances of
 the default '-' separator with the new separator.
 """
 separator = separator or ''
 if separator == '-' or not separator:
 re_sep = '-'
 else:
 re_sep = '(?:-|%s)' % re.escape(separator)
 # Remove multiple instances and if an alternate separator is
provided,
 # replace the default '-' separator.
 if separator != re_sep:
 value = re.sub('%s+' % re_sep, separator, value)
 # Remove separator from the beginning and end of the slug.
 if separator:
 if separator != '-':
 re_sep = re.escape(separator)
 value = re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value)
 return value

class Entry(models.Model):
title = models.CharField(max_length=250, unique=True)
slug = models.SlugField(
help_text="This field will be filled in automatically based on
the title field.\
  You don't need to fill this in. Honest."
)
subject = models.CharField(max_length=140)
category = models.ManyToManyField(Category)
author = models.ForeignKey(User)
dateTime = models.DateTimeField(default=datetime.datetime.now)
content = models.TextField()

class Meta:
ordering = ['-dateTime']
verbose_name_plural = "Entries"

def __unicode__(self):
return self.title

def save(self):
# Since I'm using a custom form, I've got to slugify by hand
# before the model is saved.
unique_slugify(self, "title")
super(Entry).save()

TRACE:
Environment:

Request Method: POST
Request URL: http://localhost:42766/admin_add/
Django Version: 1.0.2 final
Python Version: 2.5.2
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'Blog2.Engine2']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware')

Traceback:
File "C:\Python25\Lib\site-packages\django\core\handlers\base.py" in
get_response
  86. response = callback(request, *callback_args,
**callback_kwargs)
File "C:\Blog2\..\Blog2\Engine2\views.py" in admin_add_entry
  48. my_form.save()
File "C:\Python25\Lib\site-packages\django\forms\models.py" in save
  319. return save_instance(self, self.instance,
self._meta.fields, fail_message, commit)
File "C:\Python25\Lib\site-packages\django\forms\models.py" in
save_instance
  74. instance.save()
File "C:\Blog2\..\Blog2\Engine2\models.py" in save
  48. super(Entry).save()

Exception Type: AttributeError at /admin_add

Re: Admin - related objects when using multiple foreign keys to a parent model

2009-07-24 Thread Karen Tracey
On Fri, Jul 24, 2009 at 9:02 AM, Haestan  wrote:

>
> Hi,
>
> let's assume the following simple model:
>
> class Child(models.Model):
>father = models.ForeignKey(Adult, related_name="father")
>mother = models.ForeignKey(Adult, related_name="mother")
>
> class Adult(models.Model):
>name = models.CharField(max_length=255)
>
> Now, if I try to delete an Adult object in the admin, only "fathers" warn
> about their children as related objects. If I delete a "mother" with a
> related Child object, then there is no warning about related objects and
> their children silently get deleted as well.
>
> Is this a bug in the admin application or am I missing something to make
> this work as intended?
>
> Cheers.
>
> PS: I'm running 1.0.2
>

I believe this problem is logged in this ticket:

http://code.djangoproject.com/ticket/6191

Karen

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



Admin - related objects when using multiple foreign keys to a parent model

2009-07-24 Thread Haestan

Hi,

let's assume the following simple model:

class Child(models.Model):
father = models.ForeignKey(Adult, related_name="father")
mother = models.ForeignKey(Adult, related_name="mother")

class Adult(models.Model):
name = models.CharField(max_length=255)

Now, if I try to delete an Adult object in the admin, only "fathers" warn 
about their children as related objects. If I delete a "mother" with a 
related Child object, then there is no warning about related objects and 
their children silently get deleted as well.

Is this a bug in the admin application or am I missing something to make 
this work as intended?

Cheers.

PS: I'm running 1.0.2 


--~--~-~--~~~---~--~~
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: Please help me design Model

2009-07-24 Thread urosh

Thank you Emily For pointing me to right direction.

On Jul 24, 11:41 am, Emily Rodgers 
wrote:
> On Jul 23, 11:06 pm, urosh  wrote:
>
>
>
> > Hi.
>
> > I want to create phone book. I want that this phone book list will be
> > ordered by number of dialing this number. I think of using two tables
> > one with phone numbers and one for phone dialing statistics (how many
> > times user dialed number). Each user has his own ordering rule based
> > on his user-name. I will populate this phonebook statistics with other
> > function regular running.
>
> > This is what I have so far.
>
> > class phonebook(models.Model):
> >         person_company = models.CharField(blank=True,max_length=30)
> >         address = models.CharField(blank=True,max_length=50)
> >         e_mail = models.EmailField(blank=True,max_length=70)
> >         number = models.CharField(unique=True,max_length=15)
> >         dialed = models.ForeignKey('phonebook_stat')
> >         def __unicode__(self):
> >                 return self.person_company
>
> > class phonebook_stat(models.Model):
> >         username = models.CharField(max_length=30)
> >         number = models.CharField(max_length=15)
> >         dialed_times = models.IntegerField(max_length=10)
> >         class Admin:
> >                 pass
> > in admin.py
> > class PhonebookAdmin(admin.ModelAdmin):
> >         def queryset(self, request):
> >                 qs = super(PhonebookAdmin, self).queryset(request)
> >                 global caller_id
> >                 caller_id = str(request.user)
> >                 return qs
> >         list_per_page = 20
> >         search_fields = ('person_company','number')
> >         list_display = ['person_company','number','address',]
> >         fields = ('person_company','number','address','e_mail',)
> >         #ordering = (order_common_used,)
>
> > THANK YOU in advance.
>
> Hello,
>
> Wouldn't you want the 'dialed' to be a many to many field so that one
> phonebook entry could be used for more than one user?
>
> class Phonebook(models.Model):
>         person_company = models.CharField(blank=True,max_length=30)
>         address = models.CharField(blank=True,max_length=50)
>         e_mail = models.EmailField(blank=True,max_length=70)
>         number = models.CharField(unique=True,max_length=15)
>         dialed = models.ManyToManyField('PhonebookStat')
>         def __unicode__(self):
>                 return self.person_company
>
> class PhonebookStat(models.Model):
>         username = models.CharField(max_length=30)
>         number = models.CharField(max_length=15)
>         dialed_times = models.IntegerField(max_length=10)
>         class Admin:
>                 pass
>
> I haven't really used the admin app for ages, so probably not the best
> person to advise on that, but I can't see how the code you have
> written would work. You need to have some kind of filter on the dialed
> field.
>
> HTH a bit,
> Em
--~--~-~--~~~---~--~~
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: Slugs, why would you ever need to store one in the database?

2009-07-24 Thread Alex Robbins

You might want to look into the SlugField [1]. It makes sure you only
have url friendly stuff. You can also autopopulate it from another
field in the admin[2]. That way you just type the title and it makes a
slug for you.

One reason to hide pks is that they allow people to learn more about
your site than you might want. They can guess the next user, see what
order things were created in, or even statistics and figure out things
like how many users sign up a month.[3]

[1]http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield
[2]http://docs.djangoproject.com/en/dev/ref/contrib/admin/
#django.contrib.admin.ModelAdmin.prepopulated_fields
[3]http://www.guardian.co.uk/world/2006/jul/20/
secondworldwar.tvandradio
--~--~-~--~~~---~--~~
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: Extending AdminSite

2009-07-24 Thread Jan-Herbert Damm


Hi,

thanks a lot, that will keep me occupied for a while!

Dr.Hamza Mousa wrote:
> Try those :  [tutorials]...

jan

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



Strange error saving in admin

2009-07-24 Thread Julien Phalip

Hi,

I've got a really strange error on one of my sites. There is an
Organisation model which has a dozen of fields and 1,300 rows.

Saving organisation details in the admin usually works fine except for
one organisation. When I click 'Save', the page loads for ever and
then it fails with a 502 Proxy Error. I can edit the corresponding row
in Phpmyadmin without any problem so the database doesn't seem to be
damaged. Saving works with all other organisations I've tested.

It is using Django revision 9975.

Would you have any tips for debugging this?

Thanks a lot!

Regards,

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



Tutorial 3 templates

2009-07-24 Thread Timbadu

Hi folks,

I'm working throu the Django Tutorials and am on no. 3.

No matter where I put my 404.html and 500.html template files I am
always getting this traceback:

Traceback (most recent call last):

  File "C:\Python26\lib\site-packages\django\core\servers
\basehttp.py", line 278, in run
self.result = application(self.environ, self.start_response)

  File "C:\Python26\lib\site-packages\django\core\servers
\basehttp.py", line 635, in __call__
return self.application(environ, start_response)

  File "C:\Python26\lib\site-packages\django\core\handlers\wsgi.py",
line 239, in __call__
response = self.get_response(request)

  File "C:\Python26\lib\site-packages\django\core\handlers\base.py",
line 116, in get_response
return self.handle_uncaught_exception(request, resolver,
sys.exc_info())

  File "C:\Python26\lib\site-packages\django\core\handlers\base.py",
line 160, in handle_uncaught_exception
return callback(request, **param_dict)

  File "C:\Python26\lib\site-packages\django\views\defaults.py", line
23, in server_error
t = loader.get_template(template_name) # You need to create a
500.html template.

  File "C:\Python26\lib\site-packages\django\template\loader.py", line
80, in get_template
source, origin = find_template_source(template_name)

  File "C:\Python26\lib\site-packages\django\template\loader.py", line
73, in find_template_source
raise TemplateDoesNotExist, name

TemplateDoesNotExist: 500.html

I've been strugglin with this for a while now but can't work it out.
Can anyone see what I'm doing wrong?

Thanks,
Tim

--~--~-~--~~~---~--~~
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, multiple domains, multiple locales/languages

2009-07-24 Thread MS


OK, thanks for suggestion - however it seems the problem was somewhere
else - I was using ugettext where ugettext_lazy was supposed to be
used (ex. in forms.py).
The documentation should be more clear that the choice between
ugettext and ugettext_lazy is quite important and may lead to strange
problems.


> If me, I would seperate those settings binding to domain from those not.
> And create setting module for each domain.
> Then in different virtual host configuration, just set setting module
> pointing to different setting.py
>
> Just my opinion, sorry if it doesn't work for you.

--~--~-~--~~~---~--~~
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: which version of django should I choose?

2009-07-24 Thread Ronghui Yu
In my opinion, every version is good for learning. Just try it. And if 
you encounter difficuties for upgrading to another one, you will learn a 
lot from it.


XUN ZHOU 写道:
> hello, I am new beginner in django. I want to learn python with django 
> and later I want to write my first application in google App engine.
> there are so many different version of django.
> which version should I beginn? thanks your help or advice
>
> -- 
> Xun Zhou
> TU Berlin
>
> >

-- 
Ronghui Yu 

--~--~-~--~~~---~--~~
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: which version of django should I choose?

2009-07-24 Thread Russell Keith-Magee

On Fri, Jul 24, 2009 at 6:32 PM, Kenneth
Gonsalves wrote:
>
> On Friday 24 Jul 2009 2:59:29 pm XUN ZHOU wrote:
>> hello, I am new beginner in django. I want to learn python with django and
>> later I want to write my first application in google App engine.
>> there are so many different version of django.
>> which version should I beginn? thanks your help or advice
>
> latest trunk - and update every week.

I'm so glad you took the time to give such a detailed and reasoned
analysis, Kenneth. :-)

Xun - There are really only two versions of Django that you should be
considering. They are:

 * v1.0.2 - the most recent official release of the stable 1.0 branch
 * The tip of the SVN Trunk (containing bug fixes and new features.
This will eventually get released as v1.1)

If you're just starting out, I would recommend using a stable version
- in this case v1.0.2. This means you will miss out on some new
features. However, if you're just starting out, it's not likely that
you'll miss them. Django's documentation is fairly extensive, and all
new features are marked as such, so as you read up you will find out
the new features that are on offer. If you find that you need a
feature that is only available in the development branch, it isn't a
major task to upgrade your Django install - Django is very sensitive
about making changes that are backwards incompatible, so it should be
as simple as updating your Django install.

You may notice that this is the opposite advice to that given by
Kenneth. I have been cautious based on the fact that you're a newcomer
- since you will be learning Python and Django at the same time, using
a stable version is one less moving part to be worried about. I
suspect Kenneth is basing his recommendation on his experience -
Django's core team (which I am a member of) is very sensitive to
introducing instabilities into the code base, so Django's trunk is,
with very few exceptions, a very stable release to use. If you're
feeling a little adventurous, Kenneth's recommendation is sound - I
doubt you will experience many problems using the SVN trunk.

The other critical factor is that you have mentioned Google App
Engine. Please note that while you can use parts of Django on App
Engine, there are some important differences. I would strongly advise
consulting an App Engine-specific forum to see if they can provide any
more helpful advice with regards to Django version compatibility.

Also - note that my answer will change slightly in the middle of next
week, when we expect to release Django v1.1. When we make these
releases, v1.1 will become the stable branch - so all the new features
that are currently only available in the development branch will
become formally part of the stable release. Once v1.1 is released, a
new development branch will start, and more new features will be
added. We will continue to update v1.0.3, but only to fix critical
security issues in v1.0.3.

Yours,
Russ Magee %-)

--~--~-~--~~~---~--~~
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: cannot store images into file system using Imageupload

2009-07-24 Thread Ronghui Yu
You didn't save the file in the form save() method. In the form, 
self.cleaned['photo1'] is an object of UploadedFile(may be typo error)
You need to save it if you handle the save method by yourself

Actually, you don't need to redefine those fields in the form if what 
you do is the same as what Django does by default.

guptha ??:
> hi friends
> I 'm facing a wried behavior of Imageupload
> In Models.py
> class Market(...)
>title_name=models.CharField(max_length=125)
>photo1  = models.ImageField(upload_to= 'img/marketplace/%Y/%m/
> %d', null=True, blank=True)
>
> In views.py
> def postyour_adds(request):
> if request.method=='POST':
> form=MarketplaceForm(request.POST,request.FILES)
> if form.is_valid():
> postdict=request.POST.copy()
> newmarket=form.save()
> .
>  .
>
> In forms.py
> class MarketplaceForm(forms.Form):
> title_name = forms.CharField(max_length=125)
> photo1 = forms.ImageField(widget=forms.FileInput
> (),required=False)
> # I tried with another way in vain
> #photo1 = forms.Field(widget=forms.FileInput(),required=False)
>   def save(self):
> new_market =Marketplace.objects.create
> (title_name=self.cleaned_data['title_name'],
>  
> photo1=self.cleaned_data['photo1'],
>return new_market
>
>
> In html file
> {% block content %}
>  Enter your choice
>   
>   
>   {{ form.as_table }}
>   
>   
>   
> {% endblock %}
>
> Issue is that image names are stored in Database but when i search in
> my file system I could not find the image .
> when i repeat the same in admin site i could see the file name with
> the path i specified in Models.py and the actual image file is present
> in the specified location .
> I'm not sure why this wried behavior when i upload images from the
> user page .Why is that the image is not constructed in my file system
> Your solution is very much appreciated
> thanks
> >
>
>   

-- 
Ronghui Yu 

--~--~-~--~~~---~--~~
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, multiple domains, multiple locales/languages

2009-07-24 Thread Ronghui Yu
If me, I would seperate those settings binding to domain from those not. 
And create setting module for each domain.
Then in different virtual host configuration, just set setting module 
pointing to different setting.py

Just my opinion, sorry if it doesn't work for you.

MS ??:
> Hi,
>
> I have a problem with Django - I'm trying to build a website which
> will work on a couple of different domains and each domain should have
> a different language/locale.
>
> Example:
> domain.com -> English
> domain2.pl -> Polish
>
> The SITE_ID should change accordingly when I visit the corresponding
> domain (I have 2 records in django_site table)
>
> So - my solution to this is to use a snippet for SITE_ID:
> http://www.djangosnippets.org/snippets/1099/
> In settings.py it reads now:
> from threading import local
> SITE_THREAD_INFO = local()
> SITE_THREAD_INFO.SITE_ID = 1
> class SiteIDHook(object):
> def __int__(self):
> return SITE_THREAD_INFO.SITE_ID
> def __hash__(self):
> return SITE_THREAD_INFO.SITE_ID
> SITE_ID = SiteIDHook()
>
>
> And a middleware which handles the SITE_ID changes + my modifications
> based on LocaleMiddleware, which should change locale (LANGUAGE_CODE).
>
> middleware.py:
> from django.conf import settings
> from django.contrib.sites.models import Site
> from django.http import HttpResponseRedirect
>
> from django.utils.cache import patch_vary_headers
> from django.utils import translation
>
> import logging
> log = logging.getLogger('multisite')
>
> class MultiSiteMiddleware(object):
> def process_request(self, request):
> settings.SITE_THREAD_INFO.SITE_ID = 1
>
> host = request.META.get('HTTP_HOST').split(':')[0]
> if host.startswith('www.'): host = host[4:]
>
> log.debug('host=' + host)
>
> if host:
> try:
> site = Site.objects.get(domain=host)
> settings.SITE_THREAD_INFO.SITE_ID = site.id
> if '.pl' in host:
> translation.activate('pl-pl')
> request.LANGUAGE_CODE = translation.get_language()
> else:
> translation.activate('en-us')
> request.LANGUAGE_CODE = translation.get_language()
>
> except Site.DoesNotExist:
> settings.SITE_THREAD_INFO.SITE_ID = 1
>
> def process_response(self, request, response):
> patch_vary_headers(response, ('Accept-Language',))
> if 'Content-Language' not in response:
> response['Content-Language'] = translation.get_language()
> translation.deactivate()
> return response
>
>
> middleware.py is attached just after SessionMiddleware as suggested in
> the docs.
>
> The problem is that Django has some problems with it - it sometimes
> shows some strings translated and some not. When I browse just one
> site/domain everything is OK. But when I open another tab and browse
> the other domain (in different language) then this weirdness happens.
>
> What's wrong with that code, and how to do it properly?
>
> Regards,
> MS
>
> >
>
>   

-- 
Ronghui Yu 

--~--~-~--~~~---~--~~
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: which version of django should I choose?

2009-07-24 Thread Kenneth Gonsalves

On Friday 24 Jul 2009 2:59:29 pm XUN ZHOU wrote:
> hello, I am new beginner in django. I want to learn python with django and
> later I want to write my first application in google App engine.
> there are so many different version of django.
> which version should I beginn? thanks your help or advice

latest trunk - and update every week.
-- 
regards
kg
http://lawgon.livejournal.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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



which version of django should I choose?

2009-07-24 Thread XUN ZHOU
hello, I am new beginner in django. I want to learn python with django and
later I want to write my first application in google App engine.
there are so many different version of django.
which version should I beginn? thanks your help or advice

-- 
Xun Zhou
TU Berlin

--~--~-~--~~~---~--~~
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: Please help me design Model

2009-07-24 Thread Emily Rodgers



On Jul 23, 11:06 pm, urosh  wrote:
> Hi.
>
> I want to create phone book. I want that this phone book list will be
> ordered by number of dialing this number. I think of using two tables
> one with phone numbers and one for phone dialing statistics (how many
> times user dialed number). Each user has his own ordering rule based
> on his user-name. I will populate this phonebook statistics with other
> function regular running.
>
> This is what I have so far.
>
> class phonebook(models.Model):
>         person_company = models.CharField(blank=True,max_length=30)
>         address = models.CharField(blank=True,max_length=50)
>         e_mail = models.EmailField(blank=True,max_length=70)
>         number = models.CharField(unique=True,max_length=15)
>         dialed = models.ForeignKey('phonebook_stat')
>         def __unicode__(self):
>                 return self.person_company
>
> class phonebook_stat(models.Model):
>         username = models.CharField(max_length=30)
>         number = models.CharField(max_length=15)
>         dialed_times = models.IntegerField(max_length=10)
>         class Admin:
>                 pass
> in admin.py
> class PhonebookAdmin(admin.ModelAdmin):
>         def queryset(self, request):
>                 qs = super(PhonebookAdmin, self).queryset(request)
>                 global caller_id
>                 caller_id = str(request.user)
>                 return qs
>         list_per_page = 20
>         search_fields = ('person_company','number')
>         list_display = ['person_company','number','address',]
>         fields = ('person_company','number','address','e_mail',)
>         #ordering = (order_common_used,)
>
> THANK YOU in advance.

Hello,

Wouldn't you want the 'dialed' to be a many to many field so that one
phonebook entry could be used for more than one user?

class Phonebook(models.Model):
person_company = models.CharField(blank=True,max_length=30)
address = models.CharField(blank=True,max_length=50)
e_mail = models.EmailField(blank=True,max_length=70)
number = models.CharField(unique=True,max_length=15)
dialed = models.ManyToManyField('PhonebookStat')
def __unicode__(self):
return self.person_company

class PhonebookStat(models.Model):
username = models.CharField(max_length=30)
number = models.CharField(max_length=15)
dialed_times = models.IntegerField(max_length=10)
class Admin:
pass

I haven't really used the admin app for ages, so probably not the best
person to advise on that, but I can't see how the code you have
written would work. You need to have some kind of filter on the dialed
field.

HTH a bit,
Em
--~--~-~--~~~---~--~~
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, multiple domains, multiple locales/languages

2009-07-24 Thread MS

Hi,

I have a problem with Django - I'm trying to build a website which
will work on a couple of different domains and each domain should have
a different language/locale.

Example:
domain.com -> English
domain2.pl -> Polish

The SITE_ID should change accordingly when I visit the corresponding
domain (I have 2 records in django_site table)

So - my solution to this is to use a snippet for SITE_ID:
http://www.djangosnippets.org/snippets/1099/
In settings.py it reads now:
from threading import local
SITE_THREAD_INFO = local()
SITE_THREAD_INFO.SITE_ID = 1
class SiteIDHook(object):
def __int__(self):
return SITE_THREAD_INFO.SITE_ID
def __hash__(self):
return SITE_THREAD_INFO.SITE_ID
SITE_ID = SiteIDHook()


And a middleware which handles the SITE_ID changes + my modifications
based on LocaleMiddleware, which should change locale (LANGUAGE_CODE).

middleware.py:
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect

from django.utils.cache import patch_vary_headers
from django.utils import translation

import logging
log = logging.getLogger('multisite')

class MultiSiteMiddleware(object):
def process_request(self, request):
settings.SITE_THREAD_INFO.SITE_ID = 1

host = request.META.get('HTTP_HOST').split(':')[0]
if host.startswith('www.'): host = host[4:]

log.debug('host=' + host)

if host:
try:
site = Site.objects.get(domain=host)
settings.SITE_THREAD_INFO.SITE_ID = site.id
if '.pl' in host:
translation.activate('pl-pl')
request.LANGUAGE_CODE = translation.get_language()
else:
translation.activate('en-us')
request.LANGUAGE_CODE = translation.get_language()

except Site.DoesNotExist:
settings.SITE_THREAD_INFO.SITE_ID = 1

def process_response(self, request, response):
patch_vary_headers(response, ('Accept-Language',))
if 'Content-Language' not in response:
response['Content-Language'] = translation.get_language()
translation.deactivate()
return response


middleware.py is attached just after SessionMiddleware as suggested in
the docs.

The problem is that Django has some problems with it - it sometimes
shows some strings translated and some not. When I browse just one
site/domain everything is OK. But when I open another tab and browse
the other domain (in different language) then this weirdness happens.

What's wrong with that code, and how to do it properly?

Regards,
MS

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



Re: forms with django and extjs 3.0.0

2009-07-24 Thread Emily Rodgers

2009/7/24 Russell Keith-Magee :
>
> On Thu, Jul 23, 2009 at 5:43 PM, Emily
> Rodgers wrote:
>>
>> Hi all,
>>
>> I am currently working on some web apps that use django for the back
>> end, and extjs for the front end (using JSON to pass data between the
>> two).
>>
>> I am getting to the point where I am going to have to start doing some
>> form integration. Has anyone done this lately (with the latest version
>> of extjs)? If so, how did you go about it? I have looked on the web,
>> but most of the extjs / modelform examples are using either an old
>> version of django or an old version of extjs, both of which have
>> undergone fairly backwards incompatible changes in recent revisions. I
>> just thought that I would ask here before spending lots of time trying
>> to figure it out from scratch.
>
> I can't speak for ExtJS, but Django hasn't had any backwards
> incompatible changes in almost a year - and the areas where you are
> delving here (i.e., view and forms handling) have been stable for much
> longer.
>
> So - you shouldn't have any problems (from a Django point of view)
> with any tutorial that is a year old.

Yep, but a lot of the examples / how-tos I have found are from 2007
before the forms changed in django. Admittedly, extjs has changed a
lot more than django (they pretty much scrapped the original design
and restructured the object heirarchy for extjs 2).

> I can't offer much advice than that, though. Firstly, I'm not that
> familar with ExtJS; secondly, there isn't that much to explain.
>  * You write a Django view.
>  * That view serves a HTML page.
>  * The HTML page contains some javascript.
>  * The javascript makes a call on another Django view.
>  * The second Django view serves JSON, or some other raw data format.
>  * The javascript running on the first page uses that data to modify
> in-situ the original page.
>
> And boom, you have an AJAX website. To be sure, there is some
> complexity in getting your Javascript working - but that complexity is
> almost 100% a function of your JS toolkit of choice. From Django's
> perspective, all you ever do is serve individual pages - either HTML
> for human consumption, or JSON/some other format for automated
> Javascript consumption.

Yep - as I said, I am fairly familiar with django, I have been using
it for over a year and have built 3 or 4 fairly big apps. I have
already been using django with extjs for displaying data (pretty much
how you describe above), however the thing that is slightly more
tricky is how best to handle forms.

Extjs does its own form handling (validation / widgets etc), and it is
tricky to know whether it is best to get django to do the translation
into extjs like data (maybe create an as_ext() method, analogous to
as_table() for rendering the form), or get extjs to understand the
django form data. I also need to consider what to do about validation
(it doesn't seem very dry to make extjs do the validation, but it can
do 'as you type' validation which is quite nice for the user
interface).  Has anyone had actually done this before recently? If so,
do they have any advice on which way to go? Or unforseen problems with
m2m fields etc?

On the extjs forums, the django examples are aimed at people who are
familiar with ext js but not django and don't really offer a lot of
help for the actual integration, so I was hoping that on the
django-users forum, there might be someone who would be able to offer
advice for someone familiar with django, but less so with extjs.

I will post a how-to somewhere when I have figured out what the best
way is (currently reading up / playing with extjs forms a bit more).

Em

--~--~-~--~~~---~--~~
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: view/form with fields from multiple models

2009-07-24 Thread Matthias Kestenholz

On Fri, Jul 24, 2009 at 10:46 AM, Benjamin  Wohlwend wrote:
>
> On Jul 24, 10:37 am, Benjamin  Wohlwend  wrote:
>
>>
>> if all(f.is_valid() for f in (form1, form2, form3)):
>>     # ok, save
>>
>
> Oops, forgot to mention that I had to implement my own version of all
> (), which doesn't short cut:
>
> def really_all(iter):
>    all_true = True
>    for val in iter:
>        if not val:
>            all_true = False
>    return all_true


There is a function in Django proper which does exactly that:
django.forms.formsets.all_valid

Since is_valid works the same for forms and formsets you can use this
for plain forms too.


Matthias

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



Returning pretty pages with 410 status code

2009-07-24 Thread Metin Amiroff

Hello everyone!

I was wondering what technique people use to return pretty pages with
410 status code (ResponseGone) since search engines keep coming back
for removed pages that return 404. I currently use something like
this, but maybe someone has come up with a nicer shortcut or
implementation:

# skipping imports

try:
stuff = Stuff.objects.get(slug=stuff_slug)
except:
t = loader.get_template('410.html')
return HttpResponseGone(t.render(Context()))

Thanks.

--
Metin
--~--~-~--~~~---~--~~
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: view/form with fields from multiple models

2009-07-24 Thread Benjamin Wohlwend

On Jul 24, 10:37 am, Benjamin  Wohlwend  wrote:

>
> if all(f.is_valid() for f in (form1, form2, form3)):
>     # ok, save
>

Oops, forgot to mention that I had to implement my own version of all
(), which doesn't short cut:

def really_all(iter):
all_true = True
for val in iter:
if not val:
all_true = False
return all_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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: view/form with fields from multiple models

2009-07-24 Thread Benjamin Wohlwend

Hi,

On Jul 24, 8:41 am, Matthias Kestenholz
 wrote:

> if request.method == 'POST':
>     # initialize forms with request.POST and prefix
>     if form1.is_valid() and form2.is_valid() and form3.is_valid():
>         # save the data from the individual forms
> else:
>     # 
>

Just a little remark, as I hit this stumbling block a couple of days
ago: if you validate the forms like this (f1.is_valid() and f2.is_valid
() and ...) and your first form is not valid, Python will short cut
the if statement and not call is_valid on the other forms, which isn't
generally what you want in this situation. This works better:

if all(f.is_valid() for f in (form1, form2, form3)):
# ok, save

Regards,
Benjamin
--~--~-~--~~~---~--~~
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: pdb session and auto-reload: input problem

2009-07-24 Thread Jeremy Sule
Thank you for your help.

Now I don't have to restart the terminal again. I still have to interrupt
django though. But it's better than before. I whish Django would just
interrupt the session by itself.

Toutanc


On Thu, Jul 23, 2009 at 3:00 PM, Tom Evans  wrote:

>
> On Thu, 2009-07-23 at 14:11 +0100, Jeremy Sule wrote:
> > Hi everyone,
> >
> > I use pdb a lot and just drop "import pdb; pdb.set_trace()" here and
> > there in my code.
> > Often I find I have to change my code and do the change in the source
> > code and save it.
> >
> > The auto reload feature of django then reloads the files and restarts
> > the development server (nice).
> >
> > The problem is that if I didn't close my pdb session by a continue,
> > any input I'd make in the terminal would not appear:
> > Any character I type is passed to the terminal but does not appear on
> > the screen, even if I interrupt the django server. I have to close the
> > terminal and restart everything.
> >
> > Should I do something differently? (remembering to press "c" each time
> > has proven too difficult so far)
> >
> > Toutanc
>
> If you are using a UNIX like shell, you can simply type 'reset' to reset
> your terminal to a proper state. If you have a regular keyboard, 'reset
> -e ^?' is probably correct.
>
> 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: cross-referencing design question

2009-07-24 Thread Daniel Roseman

On Jul 24, 5:46 am, Mike Dewhirst  wrote:
> I'm new to Django and want to express a self-referencing design
> feature to link clients in the same table with each other. Django is
> currently objecting to this. Could you please point me to
> documentation which will let me figure it out?
>
> This is my models.py in a play project using Django from svn rev ...
>
> - - - - - - - - - - -
> from django.db import models
>
> def when():
>     return datetime.now()
>
> class Client(models.Model):
>     """ base class for everyone/thing """
>     surname = models.CharField(max_length=48, blank=False)
>     client_type = models.CharField(max_length=24, blank=False)
>     def __unicode__(self):
>         return self.client_type + ": " + self.surname
>
> class Membership(models.Model):
>     """ cross (xr) referencing and linking clients """
>     client_x = models.ForeignKey(Client)
>     client_r = models.ForeignKey(Client)
>     def __unicode__(self):
>         return str(self.client_x + " : " + str(self.client_r)
>
> - - - - - - - - - - -

You don't say what the error is. I can guess, though, and as always
the clue is in the error message (why do people never seem to read
these?)

You've got two foreign keys from membership to client. Django
automatically creates a backwards relationship from client to
membership, and it usually calls it  'foo_set' where foo is the lower-
case name of the related model. Since you've got two relationships,
though, Django wants to create two attributes called 'membership_set'
on the Client model, which obviously isn't possible. So to solve this,
do exactly what the error message says - add a 'related_name'
parameter on the ForeignKey definition:

client_x = models.ForeignKey(Client,
related_name='membership_x_set')
client_r = models.ForeignKey(Client,
related_name='membership_r_set')

--
DR.
--~--~-~--~~~---~--~~
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: Admin Customisations

2009-07-24 Thread Daniel Roseman

On Jul 24, 8:27 am, StevenC  wrote:
> Hey,
>
> Im new to Django and have create an online application system.
>
> I need to know is it possible to customise the List Display and have a
> customn link next to EVERY entry which points to a nother URL with its
> ID within.
>
> For example,
>
> If i have a student application. Their ID being 1. I need a link next
> to it which points to ../application/1/
>
> Does anyone have any ideas?
>
> Cheers


Sure. Just create a custom method on your ModelAdmin subclass which
returns the HTML of the link you want.

class MyAdmin(admin.ModelAdmin):
list_display = ('name', 'my_link')
class Meta:
 model = MyModel

def my_link(self, obj):
return 'My Link' % obj.id
my_link.allow_tags = True

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



Admin Customisations

2009-07-24 Thread StevenC

Hey,

Im new to Django and have create an online application system.

I need to know is it possible to customise the List Display and have a
customn link next to EVERY entry which points to a nother URL with its
ID within.

For example,

If i have a student application. Their ID being 1. I need a link next
to it which points to ../application/1/

Does anyone have any ideas?

Cheers

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