Re: can't clear form data in runserver (works in shell)

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 23:05 -0800, Mark Jones wrote:
> I have a form that is working well.  However I want to allow them to
> reuse the form multiple times.  Each time they submit the form, I will
> send up to 6 emails.  Then, if an email is sent successfully, 

Right there you have your first problem. Emails aren't necessarily sent
immediately. What does "sent" mean? Accepted by your server? Received at
the target end and not bounced? There are lots of way an email can fail.
Further, it can take some time to send email (connection times and so
on), even just to a local system. So blocking the web response based on
some "success or fail" measure in the email system is a bit fragile.

Maybe you've carefully evaluated all the steps in the pipeline and have
your risks worked out. I'd consider whether you're really solving the
right problem, however.

> I want
> to remove that email address from the form that I present to them.  If
> the email isn't successfully sent, I want to move that field up the
> list.
> 
> The problem comes when I get to
> 
> self.data[friend] = ''
> 
> inside clearsent
> 
> When I work thru this in the shell, it works as expected, but when
> runserver is going, it generates the error: This QueryDict instance is
> immutable
> 
> I don't want to clear all the fields, I want to leave the email
> subject and body alone and clear the 'To' fields and present the form
> for another round of emails to be sent.  How do you do this?

Copy the data dictionary: request.POST.copy() is the usual idiom when
you want to change something like that. You can't change Django's copy
of the data, but you can certainly make your own copy and change that.

Regards,
Malcolm



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



Re: EmptyResultSet exception

2009-02-02 Thread omat

I am using a recent svn checkout.

I opened a ticket for the issue:
http://code.djangoproject.com/ticket/10181


Best.


On Feb 3, 5:03 am, Malcolm Tredinnick 
wrote:
> On Mon, 2009-02-02 at 03:23 -0800,omatwrote:
> > Hi,
>
> > I am receiving an EmptyResultSet exception in 'in' lookups, if the
> > lookup is against an empty ValuesListQuerySet.
>
> > Here is the case:
>
> > >>> ids = Tag.objects.filter(id__in=[]).values_list(id, flat=True)
>
> > Now the ids is an empty ValuesListQuerySet as expected. If I use it in
> > an 'in' lookup:
>
> > >>> Tag.objects.filter(id__in=ids)
>
> > This results in an EmptyResultSet exception, where I would expect an
> > empty QuerySet instead.
>
> > Am I missing something here?
>
> Probably a bug. Please open a ticket with a short description of the
> problem. Nested queryset handling is fairly new, so there are some edge
> cases that might not work yet.
>
> I'm assuming here that you're using a recent subversion trunk checkout,
> by the way. If you're using Django 1.0.x, that's a different story,
> since nested querysets aren't supported there.
>
> Regards,
> Malcolm
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: object_detail 404 (queryset outdated?)

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 22:32 -0800, Simon Westphahl wrote:
> On 3 Feb., 03:54, Malcolm Tredinnick  wrote:
> > Have you verified that an object exists for whatever the slug value is
> > that you're passing in? Using Django's debug page, you should be able to
> > see the slug value and try it out at a Python prompt. That would be the
> > first step.
> >
> > On the surface, your code looks fine. The queryset is cloned each time
> > the generic view is called, which causes it to be refreshed, so that
> > shouldn't be an issue. I suggest you start debugging from the error
> > message: why is nothing matching the query (remember that it's
> > performing a "get()" based on the slug, so that's why you're getting an
> > ObjectDoesNotExist exception).
> >
> > Regards,
> > Malcolm
> 
> The poblem is with the 'datetime.now' callable passed to my custom
> manager. I was able to reproduce the same behavior by starting the
> development server and manually changing the clock to a date in the
> future. The 'object_detail' generic view of 'objects' created AFTER
> the start date of the dev server (emulated by manually changing the
> clock ...) are not accessible since the generic view seems to to some
> kind of caching.

It's much simpler than that. Hear hoofbeats, think horses.. not
zebras. :-)

As I mentioned in my reply, the queryset is cloned in the generic view,
which causes the query to be run against the database each time (cloning
removes any cached Python results). It does *not* mean that the query
parameters will be re-evaluated each time, since that could be
exorbitantly expensive, given the number of times we clone querysets in
the overall scheme of things.

The goal in generic views is to make sure we're retrieving the most
up-to-date database values for the (same) query each time. Re-evaluating
the parameters would lead to a different query each time.

Sure, it's a subtle point and maybe you could come up with a
documentation change to make it clearer (without overwhelming the
explanation of the less minor points, which is always the tricky
balance). Hopefully the above paragraphs explain the logic of what's
going on behind the scenes and why your solution gives you what you
want.


> It seems to me as if there is some magic going on ;)

Only in the "any sufficiently advanced technology..." sense. :-)

Regards,
Malcolm



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



can't clear form data in runserver (works in shell)

2009-02-02 Thread Mark Jones

I have a form that is working well.  However I want to allow them to
reuse the form multiple times.  Each time they submit the form, I will
send up to 6 emails.  Then, if an email is sent successfully, I want
to remove that email address from the form that I present to them.  If
the email isn't successfully sent, I want to move that field up the
list.

The problem comes when I get to

self.data[friend] = ''

inside clearsent

When I work thru this in the shell, it works as expected, but when
runserver is going, it generates the error: This QueryDict instance is
immutable

I don't want to clear all the fields, I want to leave the email
subject and body alone and clear the 'To' fields and present the form
for another round of emails to be sent.  How do you do this?

class AnnounceForm(forms.Form):
friend1 = forms.EmailField(label='1st Friend', required=True,
help_text='Enter the first friend you want to tell about this')
friend2 = forms.EmailField(label='2nd Friend', required=False)
friend3 = forms.EmailField(label='3rd Friend', required=False)
friend4 = forms.EmailField(label='4th Friend', required=False)
friend5 = forms.EmailField(label='5th Friend', required=False)
friend6 = forms.EmailField(label='6th Friend', required=False)
cc_myself = forms.BooleanField(label='cc myself', required=False)
emailsubject = forms.CharField(label='Email Subject')
emailbody = forms.CharField(widget=forms.Textarea, label='The
email will say:')

friends =
('friend1','friend2','friend3','friend4','friend5','friend6')
def recipients(self):
data = super(AnnounceQuizForm, self).clean()
recipients = []
for friend in self.friends:
if data[friend]:
recipients.append(data[friend])
return recipients

def clearsent(self, sentto):
"""
Clear the form of all the emails that are contained in sentto
and repopulate the fields from the top down with the ones that did not
send successfully
"""
again = []
for friend in self.friends:
if self.cleaned_data[friend] not in sentto:
again.append(self.cleaned_data[friend])
self.data[friend] = ''
if len(again):
fields = list(self.friends)
fields.reverse()
for email in again:
self.data[fields.pop()] = email


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Can't create a record with a Foreign Key: IntegrityError: (1048, "Column 'user_id' cannot be null")

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 22:22 -0800, Theme Park Photo, LLC wrote:
> I can't get anything with Foreign keys to work. I trimmed everything
> down to the simplest example:
> 
> from django.db import models
> from django.contrib.auth.models import User
> 
> class Ranking(models.Model):
>   user = models.ForeignKey(User)
>   score = models.IntegerField()
>   def __unicode__(self):
>   return u'%s %d' % (self.user, self.score)
> 
> I can't add any "Ranking" records. I try like this (from the django
> shell) and always get an error like this:
> IntegrityError: (1048, "Column 'user_id' cannot be null")
> 
> Can someone give me a hint as to the right way to do this?
> 
> (Django shell session below)
> 
> >>> from django.db import models
> >>> from django.contrib.auth.models import User
> >>> from djbaytzim.bayscore.models import Ranking
> >>> u = User (username="swirsky")
> >>> print type(u)
> 

You have to save the User object before you can use it anywhere. At this
point in time, it doesn't have a primary key value, which is what the
Ranking object needs to refer to it. Actually, the pk value is None,
which 'r' then uses, which causes problems later.

Another way of thinking of this: right now, 'u' does not exist in the
database. So you cannot save 'r' to the database, since it needs to
refer to another row in the database (the one for 'u', which doesn't
exist) for the User object.

Call u.save() here (or use User.objects.create(username="swirsky")) and
everything will work.

Regards,
Malcolm



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



Re: Django session

2009-02-02 Thread Malcolm Tredinnick

On Tue, 2009-02-03 at 13:26 +0700, Harryanto Ie wrote:
> thx, but i didn't get what i need for, how to create 
> session using request.session[] with multi value.

You got most of what you needed, though. I attempt to answer the broader
problem people ask, particularly when there's confusion over the
implementation.

Please, please, please consider NOT top-posting all the time (along with
trimming the really annoying 20 line message signature -- do you really
need to be a walking advertising billboard?). It means I have to read
your answer and then play hide-and-seek to try and find what portion of
the previous messages in the thread that you're trying to answer. Repeat
that a few hundred times a day and you can see the difficulty.

Now, to answer your specific question this time: it's not explained
explicitly in the documentation, although all the information is there
if you read the sessions docs, but a session is just a dictionary. So
you can store a list as the value for some key if you wanted to store
multiple values.

Regards,
Malcolm



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



Re: object_detail 404 (queryset outdated?)

2009-02-02 Thread Simon Westphahl

On 3 Feb., 03:54, Malcolm Tredinnick  wrote:
> Have you verified that an object exists for whatever the slug value is
> that you're passing in? Using Django's debug page, you should be able to
> see the slug value and try it out at a Python prompt. That would be the
> first step.
>
> On the surface, your code looks fine. The queryset is cloned each time
> the generic view is called, which causes it to be refreshed, so that
> shouldn't be an issue. I suggest you start debugging from the error
> message: why is nothing matching the query (remember that it's
> performing a "get()" based on the slug, so that's why you're getting an
> ObjectDoesNotExist exception).
>
> Regards,
> Malcolm

The poblem is with the 'datetime.now' callable passed to my custom
manager. I was able to reproduce the same behavior by starting the
development server and manually changing the clock to a date in the
future. The 'object_detail' generic view of 'objects' created AFTER
the start date of the dev server (emulated by manually changing the
clock ...) are not accessible since the generic view seems to to some
kind of caching.

This behavior can be prevented by wrapping the generic view:

###
def object_detail(request):
return django.views.generic.list_detail.object_detail(
request,
queryset = Service.valid_objects.all()
)
###

It seems to me as if there is some magic going on ;)

Regards,
Simon
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 session

2009-02-02 Thread Harryanto Ie

thx, but i didn't get what i need for, how to create 
session using request.session[] with multi value.



On Tue, 03 Feb 2009 17:07:36 +1100
  Malcolm Tredinnick  wrote:
> 
> On Tue, 2009-02-03 at 12:55 +0700, Harryanto Ie wrote:
>> i.e def login is called with the login template, 
> 
> The code you have posted only passes "request" to the 
>login() function.
> If you passed anything else, it would fail, since your 
>login() function
> only expects one parameter.
> 
>> example 
>> the first client's username is JOHN and the second is 
>>DAPH
>> JOHN's module template is moduleA and DAPH's module 
>> template is moduleB. when JOHN login the session has 
>> create with username JOHN (request.session['userlogin'] 
>>= 
>> login.name) and when DAPH also login while JOHN has not 
>> logout, the session changed into DAPH's username.
> 
> So you want to change the template name based on some 
>value in the
> session, then? Well, why not just do exactly that?
> 
>def login(request):
># work out the template name based on 
>request.session.
># make it guest.html by default.
>template_name = ...
>
>return render_to_response(template_name, 
>)
> 
> You should probably stop using the phrase "module 
>template", since it
> doesn't really make sense. Or, rather, it's ambiguous. 
>Python has
> modules, Django has templates. If you're using "module 
>template" to mean
> some kind of business word at your own end, that adds 
>multiple meanings
> to everything and it becomes even harder than normal to 
>understand. I
> realise you don't have English as a first language and 
>that's fine --
> with a bit of thinking, what you're saying is mostly 
>understandable. But
> it's still worth using the same technical terms as 
>everybody else to
> avoid as much confusion as possible.
> 
> Regards,
> Malcolm
> 
> 
> > 


"Flexi - Gratis bicara sepanjang waktu se-Jawa Barat, Banten dan DKI Jakarta."

"Speedy - Gratis internetan unlimited dari pkl. 20.00 s/d 08.00 se-Jabodetabek, 
Banten, Karawang dan Purwakarta."

“Nikmati akses TelkomNet Instan Week End Net hanya Rp 1.000/jam. Berlaku untuk 
Sabtu-Minggu, khusus Jawa Tengah dan DIY s/d 

31 Desember 2008”.

"Kini telah hadir Protector, layanan keamanan online yang dapat digunakan 
langsung saat menjelajahi internet kapan saja dan 

di mana saja. Dapatkan secara GRATIS layanan Protector hingga 31 Desember 2008. 
Klik ke: http://protector.telkomspeedy.com;.



Ikuti Speedy Blogging Competition 2008, ajang kompetisi Blog yang terbuka bagi 
semua Blogger dengan tema: Seperti Apa Konten Hebat Menurutmu? Dapatkan hadiah 
utama 1 Buah Notebook Mininote. Informasi lebih lanjut kunjungi 
http://lomba.blog.telkomspeedy.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
-~--~~~~--~~--~--~---



Can't create a record with a Foreign Key: IntegrityError: (1048, "Column 'user_id' cannot be null")

2009-02-02 Thread Theme Park Photo, LLC

I can't get anything with Foreign keys to work. I trimmed everything
down to the simplest example:

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

class Ranking(models.Model):
user = models.ForeignKey(User)
score = models.IntegerField()
def __unicode__(self):
return u'%s %d' % (self.user, self.score)

I can't add any "Ranking" records. I try like this (from the django
shell) and always get an error like this:
IntegrityError: (1048, "Column 'user_id' cannot be null")

Can someone give me a hint as to the right way to do this?

(Django shell session below)

>>> from django.db import models
>>> from django.contrib.auth.models import User
>>> from djbaytzim.bayscore.models import Ranking
>>> u = User (username="swirsky")
>>> print type(u)

>>> r = Ranking(user=u, score=10)
>>> r.save()
Traceback (most recent call last):
  File "", line 1, in 
  File "/Library/Python/2.5/site-packages/django/db/models/base.py",
line 311, in save
self.save_base(force_insert=force_insert,
force_update=force_update)
  File "/Library/Python/2.5/site-packages/django/db/models/base.py",
line 383, in save_base
result = manager._insert(values, return_id=update_pk)
  File "/Library/Python/2.5/site-packages/django/db/models/
manager.py", line 138, in _insert
return insert_query(self.model, values, **kwargs)
  File "/Library/Python/2.5/site-packages/django/db/models/query.py",
line 894, in insert_query
return query.execute_sql(return_id)
  File "/Library/Python/2.5/site-packages/django/db/models/sql/
subqueries.py", line 309, in execute_sql
cursor = super(InsertQuery, self).execute_sql(None)
  File "/Library/Python/2.5/site-packages/django/db/models/sql/
query.py", line 1734, in execute_sql
cursor.execute(sql, params)
  File "/Library/Python/2.5/site-packages/django/db/backends/util.py",
line 19, in execute
return self.cursor.execute(sql, params)
  File "/Library/Python/2.5/site-packages/django/db/backends/mysql/
base.py", line 88, in execute
raise Database.IntegrityError(tuple(e))
IntegrityError: (1048, "Column 'user_id' cannot be null")



--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 session

2009-02-02 Thread Malcolm Tredinnick

On Tue, 2009-02-03 at 12:55 +0700, Harryanto Ie wrote:
> i.e def login is called with the login template, 

The code you have posted only passes "request" to the login() function.
If you passed anything else, it would fail, since your login() function
only expects one parameter.

> example 
> the first client's username is JOHN and the second is DAPH
> JOHN's module template is moduleA and DAPH's module 
> template is moduleB. when JOHN login the session has 
> create with username JOHN (request.session['userlogin'] = 
> login.name) and when DAPH also login while JOHN has not 
> logout, the session changed into DAPH's username.

So you want to change the template name based on some value in the
session, then? Well, why not just do exactly that?

def login(request):
# work out the template name based on request.session.
# make it guest.html by default.
template_name = ...

return render_to_response(template_name, )

You should probably stop using the phrase "module template", since it
doesn't really make sense. Or, rather, it's ambiguous. Python has
modules, Django has templates. If you're using "module template" to mean
some kind of business word at your own end, that adds multiple meanings
to everything and it becomes even harder than normal to understand. I
realise you don't have English as a first language and that's fine --
with a bit of thinking, what you're saying is mostly understandable. But
it's still worth using the same technical terms as everybody else to
avoid as much confusion as possible.

Regards,
Malcolm


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



Re: Django session

2009-02-02 Thread Harryanto Ie

i.e def login is called with the login template, example 
the first client's username is JOHN and the second is DAPH
JOHN's module template is moduleA and DAPH's module 
template is moduleB. when JOHN login the session has 
create with username JOHN (request.session['userlogin'] = 
login.name) and when DAPH also login while JOHN has not 
logout, the session changed into DAPH's username.

how to make 2 different session so when it send back to 
server, the server can read their both session separately,
thx

in this case, how to make session name has multi value?

On Tue, 03 Feb 2009 16:27:46 +1100
  Malcolm Tredinnick  wrote:
> 
> On Tue, 2009-02-03 at 12:17 +0700, Harryanto Ie wrote:
>> hmm... i have createed the server, and i have 2 client 
>> site. each client has different module to access and 
>>there 
>> are separated when login section.
>> 
>> i'm doing now is :
>> i.e :
>> 
>> def login(request) :
>>login = 
>> User.objects.get(username=request.POST['uname'])
>>request.session['userlogin'] = login.name
> 
> This looks like a very difficult way to handle logging 
>in. The session
> already contains a reference to the logged-in user's 
>User instance. So
> why not just use the normal path? When user #2 logs in, 
>they will get a
> new session, completely independent of user #1. You seem 
>to be writing
> your own login layer on top of the existing login layer 
>here.
> 
>>
>>return 
>> response_to_render('guest.html',{'userlogin':request.session['userlogin']})
>> 
>> def moduleA(request) :  --> this is module for 1st 
>>client
>>return 
>> response_to_render('module2.html',{'userlogin':request.session['userlogin']})
>> 
>> def moduleB(request) :  --> this is module for 2nd 
>>client
>>return 
>> response_to_render('module1.html',{'userlogin':request.session['userlogin']})
> 
> So what code is responsible for deciding whether moduleA 
>or moduleB is
> called? Nothing in this code calls either one.
> 
> Malcolm
> 
> 
> 
> > 


"Flexi - Gratis bicara sepanjang waktu se-Jawa Barat, Banten dan DKI Jakarta."

"Speedy - Gratis internetan unlimited dari pkl. 20.00 s/d 08.00 se-Jabodetabek, 
Banten, Karawang dan Purwakarta."

“Nikmati akses TelkomNet Instan Week End Net hanya Rp 1.000/jam. Berlaku untuk 
Sabtu-Minggu, khusus Jawa Tengah dan DIY s/d 

31 Desember 2008”.

"Kini telah hadir Protector, layanan keamanan online yang dapat digunakan 
langsung saat menjelajahi internet kapan saja dan 

di mana saja. Dapatkan secara GRATIS layanan Protector hingga 31 Desember 2008. 
Klik ke: http://protector.telkomspeedy.com;.



Ikuti Speedy Blogging Competition 2008, ajang kompetisi Blog yang terbuka bagi 
semua Blogger dengan tema: Seperti Apa Konten Hebat Menurutmu? Dapatkan hadiah 
utama 1 Buah Notebook Mininote. Informasi lebih lanjut kunjungi 
http://lomba.blog.telkomspeedy.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
-~--~~~~--~~--~--~---



Re: Displaying Data from Multiple Tables

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 21:37 -0800, Alexiski wrote:
> 
> > On Mon, 2009-02-02 at 21:21 -0800, Alexiski wrote:
> > > Hi Malcolm,
> >
> > > Thanks for your response, but I'm not quite sure how to iterate using
> > > obj.query.all to get all the instances I'm after.
> >
> > > Could you please provide a code snippet or direct me to a relevant
> > > page?
> >
> > Iteration in templates is done with the forloop template tag. You must
> > already be using that to iteratate over all the copy instances.
> 
> Correct I am using the {% for Copy in object_list %} tag. I access the
> fields like so - {{ Copy.id }} {{ Copy.question }}
> 
> In order to access the n Query objects per Copy object, do I nest {%
> for Query in object_list %} and access using {{ Query.id }}
> {{ Query.requirements }} ?

No, because object_list is an sequence of Copy instances, not a sequence
of Query instances. You need to iterate over Copy.query_set.all, using
your variable names, in the nested loop. That is, for each copy instance
loop over the related Query instances.

Note that I probably made a typo earlier, it should be
Copy.query_set.all, not Copy.query.all. In case I've continued to get it
wrong, read the documentation for the queryset API, in particular the
part about accessing reverse relations.

Regards,
Malcolm



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



Difficulty with filtering a queryset using the "in" method

2009-02-02 Thread Brandon Taylor

Hi everyone,

I need to return a queryset using the "in" statement. My IDs are in an
array of int values.

vehicle_ids = [1, 2, 3]

If I do: vehicles = VehiclePhoto.objects.filter(vehicle__id__in=
[vehicle_ids])

I get a type error: sequence item 0, expected string, int found. I've
tried just about every combination I can think of, but can't seem to
pass in a list of IDs.

Can someone shed some light on what I'm doing wrong?

Many TIA,
Brandon
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: NetBeans IDE for Python

2009-02-02 Thread mrsixcount

Can't seem to get the auto complete to work when I import
django.db.models as models.  Shows models when I start typing but
after the . nothing in the django model section comes up.  Shows the
master list of python options.  IntegerField isn't in there nor could
I find any of the other ones.  Oh well hopefully it will be out soon
with more support for Django

On Jan 17, 3:29 am, Gautam  wrote:
> There is some problem with the parser recognizing package imports in
> the from ... import ... syntax. What seems to work is if you import
> packages directly as import ... as 
>
> So for the django models import as:
>
> import django.db.models as models
>
> And voila, completion in Netbeans works!
>
> On Nov 20 2008, 5:01 pm, lig  wrote:
>
> > On 19 нояб, 21:22, Delta20  wrote:
>
> > > NetBeans for Python has been released and based on the NB Python
> > > roadmap, it looks interesting for those of us working with Django. I
> > > haven't had much of a chance to play with it yet since it just came
> > > out today, but here's the info for anyone interested:
>
> > > NetBeans IDE for 
> > > Python:http://download.netbeans.org/netbeans/6.5/python/ea/
> > > NB Python Roadmap:http://wiki.netbeans.org/Python
>
> > from django.db import models
>
> > class Page(models.Model):
> > name= models. # hitting Ctrl+Space here don't show field type
> > suggestions or anything from imported models package
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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
-~--~~~~--~~--~--~---



openlayers TemplateSyntaxError

2009-02-02 Thread Waruna de Silva

Hi ,

I'm newbie to django as well as geodjango. I tried out first tutorial
in geodjango docs using world data. When i tried to add new entry or
tying to modified existing entry i get following errors.

""---
TemplateSyntaxError at /admin/world/worldborders/add/

Caught an exception while rendering: gis/admin/openlayers.html

Request Method: GET
Request URL:http://127.0.0.1:8000/admin/world/worldborders/add/
Exception Type: TemplateSyntaxError
Exception Value:

Caught an exception while rendering: gis/admin/openlayers.html

Original Traceback (most recent call last):
  File "/usr/lib/python2.5/site-packages/django/template/debug.py",
line 71, in render_node
result = node.render(context)
  File "/usr/lib/python2.5/site-packages/django/template/debug.py",
line 87, in render
output = force_unicode(self.filter_expression.resolve(context))
  File "/usr/lib/python2.5/site-packages/django/utils/encoding.py",
line 49, in force_unicode
s = unicode(s)
  File "/usr/lib/python2.5/site-packages/django/forms/forms.py", line
347, in __unicode__
return self.as_widget()
  File "/usr/lib/python2.5/site-packages/django/forms/forms.py", line
379, in as_widget
return widget.render(name, data, attrs=attrs)
  File "/usr/lib/python2.5/site-packages/django/contrib/gis/admin/
widgets.py", line 64, in render
context_instance=geo_context)
  File "/usr/lib/python2.5/site-packages/django/template/loader.py",
line 102, in render_to_string
t = get_template(template_name)
  File "/usr/lib/python2.5/site-packages/django/template/loader.py",
line 80, in get_template
source, origin = find_template_source(template_name)
  File "/usr/lib/python2.5/site-packages/django/template/loader.py",
line 73, in find_template_source
raise TemplateDoesNotExist, name
TemplateDoesNotExist: gis/admin/openlayers.html

---

openlayers.html file is there, I also tried with latest version of
django, getting it from SVN but still didn't fix the problem.

What will be the possible problem, can some one plz help

thanks in advance
waruna




--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Displaying Data from Multiple Tables

2009-02-02 Thread Alexiski


> On Mon, 2009-02-02 at 21:21 -0800, Alexiski wrote:
> > Hi Malcolm,
>
> > Thanks for your response, but I'm not quite sure how to iterate using
> > obj.query.all to get all the instances I'm after.
>
> > Could you please provide a code snippet or direct me to a relevant
> > page?
>
> Iteration in templates is done with the forloop template tag. You must
> already be using that to iteratate over all the copy instances.

Correct I am using the {% for Copy in object_list %} tag. I access the
fields like so - {{ Copy.id }} {{ Copy.question }}

In order to access the n Query objects per Copy object, do I nest {%
for Query in object_list %} and access using {{ Query.id }}
{{ Query.requirements }} ?

Alex
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: newbie: printing a date in a template

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 10:08 -0800, KJ wrote:
> On Feb 2, 7:11 pm, Christian Joergensen  wrote:
> >
> > Is `todaysdate` listed in your context?
> >
> 
> This is my return line for the view, the locals() part should add all
> the local variables to the template context right?
> 
> return render_to_response('items/browse.html', locals(),
> context_instance=RequestContext(request))

Well, it should. However, that's probably a fairly bad habit to get into
at this early stage. You'll end up passing all sorts of junk to your
templates over time, which will make debugging harder and harder. Having
to worry about whether using a new variable name in your view will
affect your template reduced productivity.

If you rewrite your view to explicitly pass only what you need to the
template and *then* things don't work, debugging will be much easier,
for a start. If it does start working, that would be interesting,
because I can't see why the above code doesn't work, but, then again,
you've only posted small fragments, so it's hard to be sure.

The standard advice applies: create the smallest possible view function
that demonstrates the problem. In the process of doing so, you'll almost
certainly discover what the key line is that is triggering the issue.

Regards,
Malcolm



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



Re: Displaying Data from Multiple Tables

2009-02-02 Thread Malcolm Tredinnick

On Tue, 2009-02-03 at 16:28 +1100, Malcolm Tredinnick wrote:
> On Mon, 2009-02-02 at 21:21 -0800, Alexiski wrote:
> > Hi Malcolm,
> > 
> > Thanks for your response, but I'm not quite sure how to iterate using
> > obj.query.all to get all the instances I'm after.
> > 
> > Could you please provide a code snippet or direct me to a relevant
> > page?
> 
> Iteration in templates is done with the forloop template tag.

Err .. the *for* template tag, rather.

Malcolm



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



Re: Displaying Data from Multiple Tables

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 21:21 -0800, Alexiski wrote:
> Hi Malcolm,
> 
> Thanks for your response, but I'm not quite sure how to iterate using
> obj.query.all to get all the instances I'm after.
> 
> Could you please provide a code snippet or direct me to a relevant
> page?

Iteration in templates is done with the forloop template tag. You must
already be using that to iteratate over all the copy instances.

Regards,
Malcolm



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



Re: Django session

2009-02-02 Thread Malcolm Tredinnick

On Tue, 2009-02-03 at 12:17 +0700, Harryanto Ie wrote:
> hmm... i have createed the server, and i have 2 client 
> site. each client has different module to access and there 
> are separated when login section.
> 
> i'm doing now is :
> i.e :
> 
> def login(request) :
>login = 
> User.objects.get(username=request.POST['uname'])
>request.session['userlogin'] = login.name

This looks like a very difficult way to handle logging in. The session
already contains a reference to the logged-in user's User instance. So
why not just use the normal path? When user #2 logs in, they will get a
new session, completely independent of user #1. You seem to be writing
your own login layer on top of the existing login layer here.

>
>return 
> response_to_render('guest.html',{'userlogin':request.session['userlogin']})
> 
> def moduleA(request) :  --> this is module for 1st client
>return 
> response_to_render('module2.html',{'userlogin':request.session['userlogin']})
> 
> def moduleB(request) :  --> this is module for 2nd client
>return 
> response_to_render('module1.html',{'userlogin':request.session['userlogin']})

So what code is responsible for deciding whether moduleA or moduleB is
called? Nothing in this code calls either one.

Malcolm



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



Re: Displaying Data from Multiple Tables

2009-02-02 Thread Alexiski

Hi Malcolm,

Thanks for your response, but I'm not quite sure how to iterate using
obj.query.all to get all the instances I'm after.

Could you please provide a code snippet or direct me to a relevant
page?

Thanks again,
Alex

On Feb 3, 4:04 pm, Malcolm Tredinnick 
wrote:
> On Mon, 2009-02-02 at 20:52 -0800, Alexiski wrote:
> > Hi all,
> > This is a difficulty related to me being new to Django/Python I
> > assume, so I hope you can forgive my ignorance and help me out :)
>
> > I have 4 tables - User(overriding the user object), Copy, Query,
> > QueryClassification. The main tables are Copy and Query. There can be
> > many Queries for each Copy, so...
>
> > Query has:
> > copy = models.ForeignKey(Copy)
> > classification = models.ManyToManyField(QueryClassification)
> > Copy has:
> > user = models.ForeignKey(User)
>
> > Basically it isn't displaying any of the fields from Query or
> > QueryClassification and I'm not quite sure how to reference the other
> > foreign tables in reference to a one-to-many field. Clearly I can
> > iterate through the Copy items, but I can't get it to print the
> > multiple Query items next to the appropriate Copy items.
>
> Given a Copy instance, obj, you can access the related Query instances
> (in a template) as obj.query.all. So iterate over that to get all the
> instances you're after.
>
> Regards,
> Malcolm
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Django session

2009-02-02 Thread Harryanto Ie

hmm... i have createed the server, and i have 2 client 
site. each client has different module to access and there 
are separated when login section.

i'm doing now is :
i.e :

def login(request) :
   login = 
User.objects.get(username=request.POST['uname'])
   request.session['userlogin'] = login.name
   
   return 
response_to_render('guest.html',{'userlogin':request.session['userlogin']})

def moduleA(request) :  --> this is module for 1st client
   return 
response_to_render('module2.html',{'userlogin':request.session['userlogin']})

def moduleB(request) :  --> this is module for 2nd client
   return 
response_to_render('module1.html',{'userlogin':request.session['userlogin']})

the first client login sukses and he got his own module,
but when the second client login with different id, the 
first client session has changed with the second, and when 
he tried to open his own module, it changed to 2nd 
client's module, what should i do?

i think my codes wrong, how to create the session to solve 
my problem?

thx

On Mon, 2 Feb 2009 10:08:04 -0500
  Karen Tracey  wrote:
>FYI, you have 20+ lines of signature that look like spam 
>to me because they
> are mostly in a language I cannot read.  My first 
>reaction to your post was
> to wonder how it got through moderation, then I saw you 
>have this short
> question buried before the spammish signature:
> 
> On Mon, Feb 2, 2009 at 4:35 AM, Harryanto Ie 
>wrote:
> 
>> i have some problem using django session, how to create
>> session so it can be different user access the site from
>> client site? thx
> 
> 
> which, I am afraid, I don't understand.  I appreciate 
>that there may be a
> language barrier here, but if you would devote some more 
>words and effort to
> explaining the problem you are tying to solve, what you 
>have tried and how
> it is not working, and get rid of the signature that I 
>fear will make many
> entirely dismiss your messages, you may get better 
>responses.
> 
> Karen
> 
> > 


"Flexi - Gratis bicara sepanjang waktu se-Jawa Barat, Banten dan DKI Jakarta."

"Speedy - Gratis internetan unlimited dari pkl. 20.00 s/d 08.00 se-Jabodetabek, 
Banten, Karawang dan Purwakarta."

“Nikmati akses TelkomNet Instan Week End Net hanya Rp 1.000/jam. Berlaku untuk 
Sabtu-Minggu, khusus Jawa Tengah dan DIY s/d 

31 Desember 2008”.

"Kini telah hadir Protector, layanan keamanan online yang dapat digunakan 
langsung saat menjelajahi internet kapan saja dan 

di mana saja. Dapatkan secara GRATIS layanan Protector hingga 31 Desember 2008. 
Klik ke: http://protector.telkomspeedy.com;.



Ikuti Speedy Blogging Competition 2008, ajang kompetisi Blog yang terbuka bagi 
semua Blogger dengan tema: Seperti Apa Konten Hebat Menurutmu? Dapatkan hadiah 
utama 1 Buah Notebook Mininote. Informasi lebih lanjut kunjungi 
http://lomba.blog.telkomspeedy.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
-~--~~~~--~~--~--~---



Re: Integrating raw SQL and model objects

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 23:56 -0500, Jack Orenstein wrote:
> Hello, I am new to Django, and trying to figure out how best to use  
> it. My immediate problem is that I'm trying to figure out how to use  
> raw SQL in combination with the model layer. Here are the issues I've  
> run into:
> 
> 1) How do I turn a row into a model object? There is some discussion  
> of writing raw SQL in the docs (http://docs.djangoproject.com/en/dev/ 
> topics/db/sql/#topics-db-sql), but I didn't see anything on turning  
> the row into a model object. Do I need to create a dict from the row  
> values and then call the model object's __init__ method?

Yes.

>  Or is there  
> something simpler that I'm missing?

I realise that's just a turn of phrase, but when I read it literally, I
have to wonder just how much simpler could it get? :-)

You know the field attribute names, since you constructed the query.You
have their values, returned from the database. So it's a one-liner:

MyModel(**dict(zip(field_names, row_data)))


> 2) If the model object as a ForeignKey, then the construction of a  
> model object is trickier. From playing around, it appears to be the  
> case that the dict must have an object of the referenced type, not  
> the value of the foreign key. This could make manual construction of  
> model objects difficult. I must be doing something wrong -- forcing  
> creation of the related objects seems wasteful, especially as it  
> could propagate, (if the referenced object has its own FKs).

If you know the id value for the referenced model, you can assign to the
'*_id' attribute, which is the hidden field containing the related value
(not the referred-to instance). For example, with a ForeignKey field
called "foo", you can create a model with foo_id=6 or whatever, to set
the appropriate element.

Regards,
malcolm


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



Re: Displaying Data from Multiple Tables

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 20:52 -0800, Alexiski wrote:
> Hi all,
> This is a difficulty related to me being new to Django/Python I
> assume, so I hope you can forgive my ignorance and help me out :)
> 
> I have 4 tables - User(overriding the user object), Copy, Query,
> QueryClassification. The main tables are Copy and Query. There can be
> many Queries for each Copy, so...
> 
> Query has:
> copy = models.ForeignKey(Copy)
> classification = models.ManyToManyField(QueryClassification)
> Copy has:
> user = models.ForeignKey(User)
> 
> 
> Basically it isn't displaying any of the fields from Query or
> QueryClassification and I'm not quite sure how to reference the other
> foreign tables in reference to a one-to-many field. Clearly I can
> iterate through the Copy items, but I can't get it to print the
> multiple Query items next to the appropriate Copy items.

Given a Copy instance, obj, you can access the related Query instances
(in a template) as obj.query.all. So iterate over that to get all the
instances you're after.

Regards,
Malcolm



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



Re: newbie: printing a date in a template

2009-02-02 Thread Harryanto Ie
i think you must put like this :

return render_to_response('items/browse.html', locals(),
context_instance=RequestContext(request), 
{'todaysdate':todaysdate})



On Mon, 2 Feb 2009 10:08:37 -0800 (PST)
  KJ  wrote:
> 
> On Feb 2, 7:11 pm, Christian Joergensen  
>wrote:
>>
>> Is `todaysdate` listed in your context?
>>
> 
> This is my return line for the view, the locals() part 
>should add all
> the local variables to the template context right?
> 
> return render_to_response('items/browse.html', locals(),
> context_instance=RequestContext(request))
> 
> KJ
> > 


"Flexi - Gratis bicara sepanjang waktu se-Jawa Barat, Banten dan DKI Jakarta."

"Speedy - Gratis internetan unlimited dari pkl. 20.00 s/d 08.00 se-Jabodetabek, 
Banten, Karawang dan Purwakarta."

“Nikmati akses TelkomNet Instan Week End Net hanya Rp 1.000/jam. Berlaku untuk 
Sabtu-Minggu, khusus Jawa Tengah dan DIY s/d 

31 Desember 2008”.

"Kini telah hadir Protector, layanan keamanan online yang dapat digunakan 
langsung saat menjelajahi internet kapan saja dan 

di mana saja. Dapatkan secara GRATIS layanan Protector hingga 31 Desember 2008. 
Klik ke: http://protector.telkomspeedy.com;.



Ikuti Speedy Blogging Competition 2008, ajang kompetisi Blog yang terbuka bagi 
semua Blogger dengan tema: Seperti Apa Konten Hebat Menurutmu? Dapatkan hadiah 
utama 1 Buah Notebook Mininote. Informasi lebih lanjut kunjungi 
http://lomba.blog.telkomspeedy.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
-~--~~~~--~~--~--~---



Integrating raw SQL and model objects

2009-02-02 Thread Jack Orenstein

Hello, I am new to Django, and trying to figure out how best to use  
it. My immediate problem is that I'm trying to figure out how to use  
raw SQL in combination with the model layer. Here are the issues I've  
run into:

1) How do I turn a row into a model object? There is some discussion  
of writing raw SQL in the docs (http://docs.djangoproject.com/en/dev/ 
topics/db/sql/#topics-db-sql), but I didn't see anything on turning  
the row into a model object. Do I need to create a dict from the row  
values and then call the model object's __init__ method? Or is there  
something simpler that I'm missing?

2) If the model object as a ForeignKey, then the construction of a  
model object is trickier. From playing around, it appears to be the  
case that the dict must have an object of the referenced type, not  
the value of the foreign key. This could make manual construction of  
model objects difficult. I must be doing something wrong -- forcing  
creation of the related objects seems wasteful, especially as it  
could propagate, (if the referenced object has its own FKs).

Jack Orenstein

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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
-~--~~~~--~~--~--~---



Displaying Data from Multiple Tables

2009-02-02 Thread Alexiski

Hi all,
This is a difficulty related to me being new to Django/Python I
assume, so I hope you can forgive my ignorance and help me out :)

I have 4 tables - User(overriding the user object), Copy, Query,
QueryClassification. The main tables are Copy and Query. There can be
many Queries for each Copy, so...

Query has:
copy = models.ForeignKey(Copy)
classification = models.ManyToManyField(QueryClassification)
Copy has:
user = models.ForeignKey(User)


Basically it isn't displaying any of the fields from Query or
QueryClassification and I'm not quite sure how to reference the other
foreign tables in reference to a one-to-many field. Clearly I can
iterate through the Copy items, but I can't get it to print the
multiple Query items next to the appropriate Copy items.

Below is some code for context:
#views.py
def copy_query(request, copy, query):
obj_list = copy.objects.select_related()
template_name = 'query/copyquery.html'
return render_to_response(template_name, {'object_list':
obj_list,})

The page outputs the following multi-column list. Where you see
brackets, that's me isolating where data particularly isn't showing.
The data that isn't showing is the data from Query and
QueryClassification.

Copy with Queries

* 34   1085   alexk   292   ST-S (--distpool)   (--q)   (--c)   (--
req)   Yes -   Q8 = Pp, Q9 = No (--expl)
* 34   1081   alexk   292   ST-S (--distpool)   (--q)   (--c)   (--
req)   Yes -   Q8 = Pa, Q9 = No (--expl)
* 34   1079   alexk   292   ST-S (--distpool)   (--q)   (--c)   (--
req)   Yes -   Q8 = Pr, Q9 = No (--expl)
* 34   1073   alexk   292   ST-S (--distpool)   (--q)   (--c)   (--
req)   Yes -   Q8 = Py, Q9 = No (--expl)

Regards and thanks,
Alex
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 sqlite autoincrement bug

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 23:16 -0500, alexander lind wrote:
>  
> On Feb 2, 2009, at 10:05 PM, Malcolm Tredinnick wrote:
> > > I always make my auto-inc fields primary as well, so no argument
> > > there.
> > > I tried using the AutoField when I noticed django didn't create
> > > the  
> > > auto-incrementing fields correctly by itself in sqlite, but that  
> > > didn't work either until I patched it.
> > 
> > Then something else is going on and maybe SQLite doesn't need the
> > AUTOINCREMENT marker for some reason. Because automatic primary key
> > fields work fine with SQLite. If that ever broke, we'd hear about it
> > very quickly.
> 
> 
> According to sqlite themselves, you can create a primary key without
> using the AUTOINCREMENT marker, and this key will _almost_ act as an
> autoinc field, but there is one important difference, and that is that
> without the use of AUTOINCREMENT, sqlite does not guarantee that a new
> ID is created for each insert. If you for example deleted the latest
> row in the table, sqlite would re-use the ID of the deleted row for
> the next insert. This is because without AUTOINCREMENT, the primary
> key becomes an alias for sqlite:s internal ROWID, that works this way.

Okay, that sounds like the behaviour we need. So I'm comfortable that
there isn't a major bug in Django now.

[...]
> I think django should use the AUTOINCREMENT marker on the AutoField
> myself, makes sense to me.

It's possible, but not a requirement. Since the documentation recommends
what we're doing now, our current choice seems like a good idea, too. 

In the absence of any concrete bug and a real use-case that requires a
change, I'd be unenthusiastic about changing current behaviour.

> Still, sqlite does not behave as documented above for me. If I try to
> use just the ROWID as primary key, I end up not being able to insert
> any new rows because it will just tell me that the primary key may not
> be null (when leaving the field out of the insert query, like you
> would an auto-inc field). 

So you're trying to do something a bit weird then, since at least a few
thousand people use SQLite in Django applications all the time without
problems. I still don't really understand what it is you're trying to
do, but I've decided I'm not particularly worried by it.

Auto-generated primary keys in SQLite work fine. You can happily create
and save models with them. If you want to manually declare the primary
key field, go for it. You can even use AutoField and it will work fine
with Django. If you want a field with different behaviour from
AutoField, that's also fine, since it's easy to create custom fields for
custom database types -- we've put a lot of effort into making that
possible.

Regards,
Malcolm


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



Re: django sqlite autoincrement bug

2009-02-02 Thread alexander lind
On Feb 2, 2009, at 10:05 PM, Malcolm Tredinnick wrote:
>> I always make my auto-inc fields primary as well, so no argument  
>> there.
>> I tried using the AutoField when I noticed django didn't create the
>> auto-incrementing fields correctly by itself in sqlite, but that
>> didn't work either until I patched it.
>
> Then something else is going on and maybe SQLite doesn't need the
> AUTOINCREMENT marker for some reason. Because automatic primary key
> fields work fine with SQLite. If that ever broke, we'd hear about it
> very quickly.

According to sqlite themselves, you can create a primary key without  
using the AUTOINCREMENT marker, and this key will _almost_ act as an  
autoinc field, but there is one important difference, and that is that  
without the use of AUTOINCREMENT, sqlite does not guarantee that a new  
ID is created for each insert. If you for example deleted the latest  
row in the table, sqlite would re-use the ID of the deleted row for  
the next insert. This is because without AUTOINCREMENT, the primary  
key becomes an alias for sqlite:s internal ROWID, that works this way.

 From their manual:
The behavior implemented by the AUTOINCREMENT keyword is subtly  
different from the default behavior. With AUTOINCREMENT, rows with  
automatically selected ROWIDs are guaranteed to have ROWIDs that have  
never been used before by the same table in the same database. And the  
automatically generated ROWIDs are guaranteed to be monotonically  
increasing. These are important properties in certain applications.  
But if your application does not need these properties, you should  
probably stay with the default behavior since the use of AUTOINCREMENT  
requires additional work to be done as each row is inserted and thus  
causes INSERTs to run a little slower.
http://www.sqlite.org/autoinc.html

I think django should use the AUTOINCREMENT marker on the AutoField  
myself, makes sense to me.

Still, sqlite does not behave as documented above for me. If I try to  
use just the ROWID as primary key, I end up not being able to insert  
any new rows because it will just tell me that the primary key may not  
be null (when leaving the field out of the insert query, like you  
would an auto-inc field). This is not djangos fault of course, just an  
oddity that I really don't understand.

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



Re: select_related and OneToOneField

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 14:40 -0500, Michael Hrivnak wrote:
> Does select_related work for OneToOneField relationships?  

Yes. This wasn't something you could have just tried out and seen for
yourself?

> If so, does it work 
> in both directions?

No.

Probably will in 1.1, but not yet.

Regards,
Malcolm



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



Re: Can I control contents of SELECT in queryset?

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 09:50 -0800, phoebebright wrote:
> After replicating you test and it still failing and various other
> experiments I downloaded the latest django trunk and it works fine!
> Always check the version first Phoebe!
> 
> Sorry for the run around.
> 
> For the record here are the two queries - correct one first, the
> difference is in the SELECT part of subquery, SELECT U1.`cat_id`
> instead of SELECT U0.`id`
> 
> SELECT `town_subcategory`.`name` FROM `town_subcategory` WHERE NOT
> (`town_subcategory`.`id` IN (SELECT U0.`id` FROM `town_subcategory`
> U0 LEFT OUTER JOIN `town_business` U1 ON (U0.`id` = U1.`cat_id`) WHERE
> U1.`directory_ptr_id` IS NULL))
> 
> SELECT `town_subcategory`.`name` FROM `town_subcategory` WHERE NOT
> (`town_subcategory`.`id` IN (SELECT U1.`cat_id` FROM
> `town_subcategory` U0 LEFT OUTER JOIN `town_business` U1 ON (U0.`id` =
> U1.`cat_id`) WHERE U1.`directory_ptr_id` IS NULL))

Oh, right. I fixed that a little while back and it's not in any release
yet. It will be in both Django 1.1 and 1.0.3.

Sorry -- I keep losing track of what bug fixes affect what areas at
times.

Regards,
Malcolm



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



Re: django sqlite autoincrement bug

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 09:42 -0500, alexander lind wrote:
> >>> Shows how infrequently AutoField's are really used in practice.
> >>> They're
> >>> generally just not that useful to specify.
> >>
> >>
> >> What else do people use for specifying autoinc fields?
> >
> > Auto-increment fields generally aren't that useful in practice,  
> > outside
> > of primary keys (the reasonsing being that, since they can act as
> > primary keys, you might as well make it the table's primary key if
> > you're using one. A non-primary key auto-inc field is usually a sign  
> > of
> > an unnecessarily denormalised data model). Since Django automatically
> > creates an auto-increment primary key field, the majority of the time
> > the manual specification isn't needed.
> 
> I always make my auto-inc fields primary as well, so no argument there.
> I tried using the AutoField when I noticed django didn't create the  
> auto-incrementing fields correctly by itself in sqlite, but that  
> didn't work either until I patched it.

Then something else is going on and maybe SQLite doesn't need the
AUTOINCREMENT marker for some reason. Because automatic primary key
fields work fine with SQLite. If that ever broke, we'd hear about it
very quickly.

Regards,
Malcolm



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



Re: EmptyResultSet exception

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 03:23 -0800, omat wrote:
> Hi,
> 
> I am receiving an EmptyResultSet exception in 'in' lookups, if the
> lookup is against an empty ValuesListQuerySet.
> 
> Here is the case:
> 
> >>> ids = Tag.objects.filter(id__in=[]).values_list(id, flat=True)
> 
> Now the ids is an empty ValuesListQuerySet as expected. If I use it in
> an 'in' lookup:
> 
> >>> Tag.objects.filter(id__in=ids)
> 
> This results in an EmptyResultSet exception, where I would expect an
> empty QuerySet instead.
> 
> Am I missing something here?

Probably a bug. Please open a ticket with a short description of the
problem. Nested queryset handling is fairly new, so there are some edge
cases that might not work yet.

I'm assuming here that you're using a recent subversion trunk checkout,
by the way. If you're using Django 1.0.x, that's a different story,
since nested querysets aren't supported there.

Regards,
Malcolm



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



Re: problem with admin in a .90 site

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 14:36 +0530, Kenneth Gonsalves wrote:
> hi,
> I have an old site running on revision 2486 - had not touched it for years 
> and 
> since it wasnt broken nor needed new features, I did not upgrade it. A new 
> model was required, so I added it, but it was not appearing in sqlall 
> statement. The application is called 'web' and under the directory 'web' 
> there are 2 files 'models.py' and 'views.py'. The new model was 
> called 'Affiliation', and the site started barfing saying 'cannot import 
> affiliations'. I then noticed that views.py had a statement:
> 
> from myapp.web.models.web import *
> 
> there is a directory called myapp.web.models, but that only held an 
> __init__.py file which was empty. In those days django required for models in 
> an app called web, to have a directory like
> web/models/web.py and /web/views/web.py. Apparently some years back I had 
> changed this to the current directory structure as web/views.py and 
> web/models.py. But I could not understand how the site was working until I 
> saw on the production server a file called ~/models/web.pyc. The site had 
> been using this all these years which is why my new model was not noticed. I 
> restored the old directory structure - the site load fine now. But - in 
> admin, the only things that show up are are auth and core - no sign of 'web'. 
> Any clues (I know I should not expect people to help out on such old stuff, 
> but if there *are* any oldtimers with long memories ...)

It's possible you've hit a very old bug that is triggered depending upon
import orders and chained imports and the like. The final patch against
ticket #1796 is what fixed it (note that the ticket title is only the
tip of the iceberg; the final patch and resolution is what's important).
You might need to backport the equivalent of r5919 (and possibly some
other patches that I can't remember now, for checking whether the
many-to-many cache in the Options class can be used).

Regards,
Malcolm



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



Re: Session Variables as Default Form Values

2009-02-02 Thread Ty

Ah, DURR. I just had to put "initial=" before the dictionary. Now it
all makes sense!

On Feb 2, 9:48 pm, Ty  wrote:
> Yes, but that would bound the data to the form and the data would try
> to be validated on page load. I'm looking to pass default values to an
> unbound form.
>
> On Jan 30, 7:13 pm, "Todd O'Bryan"  wrote:
>
> > You can pass data to a form class as a dictionary, so just save a
> > dictionary of the values in your session under some name that you'll
> > know to use.
>
> > On Fri, Jan 30, 2009 at 5:04 PM, Tyler Brownell  
> > wrote:
> > >http://groups.google.com/group/django-users/browse_thread/thread/ed74...
>
> > > On Fri, Jan 30, 2009 at 5:03 PM, Ty  wrote:
>
> > >> I've went through the documentation for "modelforms" and "forms" but I
> > >> couldn't figure our how someone would set the default value for a form
> > >> field to a session variable.
>
> > >> I have a checkbox in my comment form that says "remember my
> > >> information". After a comment is submitted and if the checkbox is
> > >> checked I'm saving the persons name, email address, and website in
> > >> session variables.
>
> > >> Now I'm just trying to figure out how to get these session variables
> > >> to load as the default values in the form fields, if they exist.
>
> > >> Can anyone point me in the right direction?
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: object_detail 404 (queryset outdated?)

2009-02-02 Thread Malcolm Tredinnick

On Mon, 2009-02-02 at 00:16 -0800, Simon Westphahl wrote:
> Hi,
> 
> I'm getting the following 404 when accessing an objects detail page.
> 
> ###
> Page not found (404)
> Request Method: GET
> Request URL: http://127.0.0.1:8000/offers/service/testservice/
> 
> No  found
> matching the query

Hmm ... that error message is a bug. It should display the real verbose
name there. I just looked at the source, and Django's doing that
incorrectly. We should fix that. The message is correct, it just
shouldn't display the functional.__proxy__ stuff -- it should display
the verbose name.

> ###
> 
> This seems a little strange to me since the object overview works like
> a charm.
> I'm using this urly.py for my app: http://dpaste.com/115521/
> 
> The queryset passed to 'extra_context' has to be a python function as
> mentioned in the django generic views documentation, since i want to
> get a queryset that is always fresh (This works!)
> Does this also apply to the 'service_detail' dict passed to the
> 'object_list' generic view?
> It seems as if the the queryset is outdated and only evaluated once?

Have you verified that an object exists for whatever the slug value is
that you're passing in? Using Django's debug page, you should be able to
see the slug value and try it out at a Python prompt. That would be the
first step.

On the surface, your code looks fine. The queryset is cloned each time
the generic view is called, which causes it to be refreshed, so that
shouldn't be an issue. I suggest you start debugging from the error
message: why is nothing matching the query (remember that it's
performing a "get()" based on the slug, so that's why you're getting an
ObjectDoesNotExist exception).

Regards,
Malcolm



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



Re: how to check manytomany field in filter?

2009-02-02 Thread garagefan

well... that worked... to be 100% honest... i didn't expect it to.
Guess i'm still underestimating the framework

thanks :)

On Feb 2, 9:28 pm, Martin Conte Mac Donell  wrote:
> On Tue, Feb 3, 2009 at 12:21 AM, garagefan  wrote:
>
> > Trying to test a manytomany field in a model that will be user names.
> > Building that is simple enough in the model, and so is selecting the
> > users in the admin.
>
> > the problem is filtering a query to test the current logged in user
> > with the manytomany field to ensure they are listed.
>
> > ie:
> > filter(Q(is_private=False) | Q(approvedUsers = str(request.user))
>
> > where approvedUsers is the manytomany field
>
> Actually i don't understand fully what are you trying to do, but based
> on your call:
>
> Did you try filter(Q(is_private=False) | Q(approvedUsers=request.user)?
>
> M
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Session Variables as Default Form Values

2009-02-02 Thread Ty

Yes, but that would bound the data to the form and the data would try
to be validated on page load. I'm looking to pass default values to an
unbound form.


On Jan 30, 7:13 pm, "Todd O'Bryan"  wrote:
> You can pass data to a form class as a dictionary, so just save a
> dictionary of the values in your session under some name that you'll
> know to use.
>
> On Fri, Jan 30, 2009 at 5:04 PM, Tyler Brownell  
> wrote:
> >http://groups.google.com/group/django-users/browse_thread/thread/ed74...
>
> > On Fri, Jan 30, 2009 at 5:03 PM, Ty  wrote:
>
> >> I've went through the documentation for "modelforms" and "forms" but I
> >> couldn't figure our how someone would set the default value for a form
> >> field to a session variable.
>
> >> I have a checkbox in my comment form that says "remember my
> >> information". After a comment is submitted and if the checkbox is
> >> checked I'm saving the persons name, email address, and website in
> >> session variables.
>
> >> Now I'm just trying to figure out how to get these session variables
> >> to load as the default values in the form fields, if they exist.
>
> >> Can anyone point me in the right direction?
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Making fields conditionally required based on another field's state

2009-02-02 Thread Martin Conte Mac Donell

On Mon, Feb 2, 2009 at 7:21 PM, wotaskd  wrote:
>
> Hello everyone, a quick (and I guess easy) one:
>
> Is there any way, on the admin site, to make a field for a model
> mandatory, if another one is blank and vice-versa?

Yeap, you need to write your own form class, subclass clean() method
do your checks and return cleaned_data or raise an exception.

Take a look to:
http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

Also (in advance to your next question) take a look to:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin

M

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



Re: how to check manytomany field in filter?

2009-02-02 Thread Martin Conte Mac Donell

On Tue, Feb 3, 2009 at 12:21 AM, garagefan  wrote:
>
> Trying to test a manytomany field in a model that will be user names.
> Building that is simple enough in the model, and so is selecting the
> users in the admin.
>
> the problem is filtering a query to test the current logged in user
> with the manytomany field to ensure they are listed.
>
> ie:
> filter(Q(is_private=False) | Q(approvedUsers = str(request.user))
>
> where approvedUsers is the manytomany field

Actually i don't understand fully what are you trying to do, but based
on your call:

Did you try filter(Q(is_private=False) | Q(approvedUsers=request.user)?

M

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 check manytomany field in filter?

2009-02-02 Thread garagefan

Trying to test a manytomany field in a model that will be user names.
Building that is simple enough in the model, and so is selecting the
users in the admin.

the problem is filtering a query to test the current logged in user
with the manytomany field to ensure they are listed.

ie:
filter(Q(is_private=False) | Q(approvedUsers = str(request.user))

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



Re: forms not valid

2009-02-02 Thread Martin Conte Mac Donell

On Mon, Feb 2, 2009 at 11:35 PM, vierda  wrote:
>
> Hi all, I have three forms and none of these forms pass is_valid()
> test when I test in intrepeter. kindly help for point out what's
> problem with my forms. thank you.
>
> from django.contrib.auth.models import User
> from django.contrib.auth.forms import UserCreationForm
> from django import forms
> from django.forms import ModelForm
>
> #1st
> class RegistrationForm(UserCreationForm):
>   email = forms.EmailField(label=("e-mail"))
>
>   class Meta:
>  model = User
>  fields = ('username', 'email','password2')
>
>   def clean_email(self):
>email = self.cleaned_data["email"]
>try:
>User.objects.get(email=email)
>except User.DoesNotExist:
>return email
>raise forms.ValidationError(("e-mail already exist."))
>
> #2nd
> class UserProfileForm(ModelForm):
>   class Meta :
>   model = User
>  fields = ('email',)
>
> #3rd
> class DeleteForm(ModelForm):
>   class Meta :
>  model = User
>  fields = ('username',)

Wait. Do you know what "is_valid()" do, right?. :-)

is_valid refers to data sent to the form (for example request.POST),
not form itself.

For instance:

>>> f = UserProfileForm({'email':'a'})
>>> f.is_valid()
False
>>> f.errors
{'email': [u'Enter a valid e-mail address.']}

But:

>>> f = UserProfileForm({'email':'a...@a.com'})
>>> f.is_valid()
True

M

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Custom Aggregate Objects

2009-02-02 Thread alex.gay...@gmail.com



On Feb 2, 9:05 pm, nsitarz  wrote:
> Hey,
>
> Back when the ORM aggregate support was a patch in trac I used to
> create custom aggregate objects that looked like this:
>
> class Date(Aggregate):
>     pass
>
> class DateHour(Aggregate):
>     def __init__(self, lookup):
>         super(DateHour, self).__init__(lookup)
>         self.sql_template = '(DATE(${field}) + INTERVAL HOUR(${field})
> HOUR)'
>
> However now that aggregate support has made its way into trunk the api
> seems to have changed a bit. After reading the aggregate module it
> looks to me like I'd have to reimplement the Aggregate class myself in
> order to have this same kind of functionality. Is there a supported
> way of creating custom aggregate classes for use with the trunk ORM?
>
> I'd appreciate any help that anybody can offer on this.

Aggregates were refactored so that they involve 2 classes, 1
implements the public API, and the other implements the SQL bit.
Basically look here:
http://code.djangoproject.com/browser/django/trunk/django/db/models/aggregates.py#L26

for what you're public API bit should be(instead of pulling the clsas
out of the aggreagetes module it can just refer to te specific class
it goes with).  And then here:
http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/aggregates.py
for what the SQL backened's API is.

Alex
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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
-~--~~~~--~~--~--~---



Custom Aggregate Objects

2009-02-02 Thread nsitarz

Hey,

Back when the ORM aggregate support was a patch in trac I used to
create custom aggregate objects that looked like this:

class Date(Aggregate):
pass


class DateHour(Aggregate):
def __init__(self, lookup):
super(DateHour, self).__init__(lookup)
self.sql_template = '(DATE(${field}) + INTERVAL HOUR(${field})
HOUR)'

However now that aggregate support has made its way into trunk the api
seems to have changed a bit. After reading the aggregate module it
looks to me like I'd have to reimplement the Aggregate class myself in
order to have this same kind of functionality. Is there a supported
way of creating custom aggregate classes for use with the trunk ORM?

I'd appreciate any help that anybody can offer on 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: Filter by ForeignKey reference??

2009-02-02 Thread Martin Conte Mac Donell

On Mon, Feb 2, 2009 at 11:59 PM, Martin Conte Mac Donell
 wrote:
> If you need country_id/country_name:
>
 Profile.objects.values('country__id', 
 'country__name').select_related('country').distinct()
> [{'country__name': u'Country1', 'country__id': 1}, {'country__name':
> u'Country3', 'country__id': 3}]
>
> Which run this query:
>
 Profile.objects.values('country__id', 
 'country__name').select_related('country').distinct().query.as_sql()
> ('SELECT DISTINCT "b_profile"."country_id", "b_country"."name" FROM
> "b_profile" INNER JOIN "b_country" ON ("b_profile"."country_id" =
> "b_country"."id")', ())

Also you can ommit select_related('country') which is implicit with
"country__name" and "country__id".

M.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Filter by ForeignKey reference??

2009-02-02 Thread Martin Conte Mac Donell

On Mon, Feb 2, 2009 at 10:11 PM, Markus T.  wrote:
>
> Hi,
>
> I have two simple models:
>
> class Country(models.Model):
>  name  = models.CharField(_("Name"), max_length=50,
> unique=True)
>
> class Profile(models.Model):
>  name  = models.CharField(_("Name"), max_length=50,
> unique=True)
>  country   = models.ForeignKey(Country)
>
>
> If I want to create a list of all countries that are actually
> referenced (i.e. used by at least one Profile entry), how would I code
> that in Django?

If you need country_id/country_name:

>>> Profile.objects.values('country__id', 
>>> 'country__name').select_related('country').distinct()
[{'country__name': u'Country1', 'country__id': 1}, {'country__name':
u'Country3', 'country__id': 3}]

Which run this query:

>>> Profile.objects.values('country__id', 
>>> 'country__name').select_related('country').distinct().query.as_sql()
('SELECT DISTINCT "b_profile"."country_id", "b_country"."name" FROM
"b_profile" INNER JOIN "b_country" ON ("b_profile"."country_id" =
"b_country"."id")', ())

M.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Non-typical Install - limited ftp access

2009-02-02 Thread Tim Johnson

On Monday 02 February 2009, elithrar wrote:
> Whilst you could technically 'upload' django to the webspace that
> you're jailed into, without the package being on the PYTHONPATH you
> won't be able to import django into your scripts - you'll need to SSH
> in and install the package (via either yum/apt or using the svn
> checkout) first.
 :-) Quick response?
 SSH is not available. Why couldn't I add the django path to sys.path?
 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
-~--~~~~--~~--~--~---



forms not valid

2009-02-02 Thread vierda

Hi all, I have three forms and none of these forms pass is_valid()
test when I test in intrepeter. kindly help for point out what's
problem with my forms. thank you.

from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.forms import ModelForm

#1st
class RegistrationForm(UserCreationForm):
   email = forms.EmailField(label=("e-mail"))

   class Meta:
  model = User
  fields = ('username', 'email','password2')

   def clean_email(self):
email = self.cleaned_data["email"]
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError(("e-mail already exist."))

#2nd
class UserProfileForm(ModelForm):
   class Meta :
   model = User
  fields = ('email',)

#3rd
class DeleteForm(ModelForm):
   class Meta :
  model = User
  fields = ('username',)

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Non-typical Install - limited ftp access

2009-02-02 Thread elithrar

Whilst you could technically 'upload' django to the webspace that
you're jailed into, without the package being on the PYTHONPATH you
won't be able to import django into your scripts - you'll need to SSH
in and install the package (via either yum/apt or using the svn
checkout) first.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Error saving a Model with a custom image field

2009-02-02 Thread Louis Sayers

I think it must be something that I'm not doing.
It all works when I'm using a ModelForm, so there must be a difference
between what I'm doing manually, and what the ModelForm does for me.

The culprit must be my code:

new_image = ImageWithThumbsField(images_to_save[image],
upload_to=ListingModels.image_upload_location,
sizes=((ListingModels.thumb_widths,
ListingModels.thumb_heights),))
image_object= Image(photo=new_image)
image_object.save()


most likely the new_image creation I would think.

In all honesty, I'm not sure if I'm giving the ImageWIthThumbsField
class the image correctly - perhaps my brain is fried(mmm... bacon),
but how exactly do you give an ImageField (ImageWIthThumbsField
extends ImageField) class the actual Image ?


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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
-~--~~~~--~~--~--~---



Non-typical Install - limited ftp access

2009-02-02 Thread Tim Johnson

I do not currently use django. I am an experienced web programmer.
I've developed my own frameworks, but have a small project to do that
I'd like to use as a way of learning and testing django.

To the best of my knowledge, here are the circumstances: 
A virtual domain on a linux redhat or ubuntu box. 
No system-wide acess or SSH access. I can install anything
within reason under the domain itself. 
There is a plex interface and I have FTP access to the domain
itself. I know nothing about plex, but will be briefed on it tomorrow.

How would I approach installing django via FTP? And that assumes
that I would already have it installed on my kubuntu development
box. Pointers to similar topics would be sufficient at this stage.

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: Admin view - merge two tables? (potentially bad db design)

2009-02-02 Thread Carl Meyer

On Feb 2, 6:44 pm, Zbigniew Braniecki 
wrote:
> How can I overwrite the way Questions are selected so that when they
> are returned by Question.objects.get('x') or Question.objects.filter()
> or Question.objects.all() they are already joined with
> QuestionProperties values?

Try select_related() [1].

Carl

[1] http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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
-~--~~~~--~~--~--~---



ifequal and DateQuerySet objects

2009-02-02 Thread Bret W

I've run into a problem with ifequal in one of my templates.

I'm using date-based generic view to display all objects for a given
year.
urls.py:
(r'^taken/(?P\d{4})/$' ...

Part of the extra_context I pass is a DateQuerySet object:
months = Photo.objects.dates('date_taken', 'month', order='DESC')

In my template, I have the following:
{% for month in months %}
{% ifequal year month.year %}
...

It always evaluates to false.

I know this is because Python won't handle the casting:

>>> from datetime import datetime
>>> now = datetime.now()
>>> now.year == 2009
True
>>> now.year == "2009"
False
>>>

So, is it possible to handle this comparison in the template?
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 simple shopping cart

2009-02-02 Thread Andrew Ingram

lnysrogh wrote:
> Hello. I'm new to Django (and web development in general), and this is
> my first post here. Hope someone can help me.
>
> I'm trying to build a shopping cart, and my idea is to store the
> product information (id and quantity) in a session when I add the
> product to the shopping cart, and retrieve it to display in the "show
> cart" page. I'm using sessions for this because I don't want the user
> to have to log in or register just to add some items to the cart and
> see the total price. When he logs in to actually buy something, I
> pretend to store it in a cart model, but I didn't get there yet. I'll
> show you the code I'm testing:
>
> def add(request, product_id):
>   request.session.set_test_cookie()
>   if request.session.test_cookie_worked():
>   request.session.delete_test_cookie()
>   added = Product.objects.get(id=product_id)
>   request.session['product_id'] = added
>   return HttpResponseRedirect('/cart/')
>   else:
>   return HttpResponse('You need to enable cookies')
>
> def cart(request):
>   if 'product_id' in request.session:
>   cart = request.session['product_id']
>   return render_to_response('cart.html', {'cart': cart})
>   else:
>   return HttpResponse('Cart is empty')
>
> That's what I was able to come up with. The first problem is, it's not
> working. The second problem is, I can't figure out how to add more
> than one product to the cart.
>
> The error I'm getting when I add something to the cart is "Caught an
> exception while rendering: 'Product' object is not iterable". I'm
> pretty sure that error has something to do with the cart.html, because
> if I replace that line with:
>
> return HttpResponse('You've added the product %s to the cart' % cart)
>
> it works. The cart.html is just this:
>
> {% for product in cart %}
> Your cart: {{ product.name }} - {{product.price}}
> {% endfor %}
>
> It should work, right? I just can't figure what's causing that error.
>   
I've noticed a few things that you should consider:

Firstly, you're storing the actual product object in the session which 
is less than ideal, it'd be better to load any cart objects from the db 
at the start of each request. This prevents the problem of a session 
product and the real db product getting out of sync if a change is made.

Second problem is that you're assigning request['product_id'] to an 
actual product, but when you're doing the lookup later you're treating 
it as if it is a list of products. When you think about it, it's clear 
why iterating over it isn't working.

What I would do is have a Cart model which contains a set of Products (I 
tend to create a CartItem model as well for storing other info such as 
quantity). Normally you'd just save this to the db and store the cart id 
in the session. This can create a problem with having a bunch of orphan 
carts in the db after the sessions have expired though, normal solution 
is to have a script that periodically cleans up any old carts. Other 
solution is that you store the Cart model in the session but make sure 
the serialized CartItem only stores the product id rather than the whole 
product.

Hope this helps

Regards,
Andrew Ingram

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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
-~--~~~~--~~--~--~---



Filter by ForeignKey reference??

2009-02-02 Thread Markus T.

Hi,

I have two simple models:

class Country(models.Model):
  name  = models.CharField(_("Name"), max_length=50,
unique=True)

class Profile(models.Model):
  name  = models.CharField(_("Name"), max_length=50,
unique=True)
  country   = models.ForeignKey(Country)


If I want to create a list of all countries that are actually
referenced (i.e. used by at least one Profile entry), how would I code
that in Django?

Maybe something like (of course this is rubbush):

referenced_countries = Country.objects.exclude
(profile__country__isnull=True)


Thanks for your help
Markus
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Error saving a Model with a custom image field

2009-02-02 Thread Louis Sayers

I'm running the official release of django 1.02
Do you think there'd be any problems with this version?

I've only been using django for the last 2 months, so I'm fairly new
to it, and haven't investigated different revisions etc

On Feb 3, 12:58 pm, Andrew Ingram  wrote:
> Louis Sayers wrote:
> > I have an Image model:
>
> ...
> > Exception Type: AttributeError at /listings/add/
> > Exception Value: 'ImageWithThumbsField' object has no attribute 'find'
>
> > I'm really struggling with this error, if anyone has any ideas, I'll
> > be glad to hear them :)
>
> > Thanks
>
> What version of Django are you using? Revision 9766 of trunk breaks
> quite a lot of stuff to do with ImageFields and it hasn't been fixed
> yet. Basically anything which requires handling the file prior to saving
> in admin (calculating dimensions for example) doesn't work and will
> cause an exception.
>
> I've rolled back to revision 9765 for the time being.
>
> Regards,
> Andrew Ingram
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Error saving a Model with a custom image field

2009-02-02 Thread Andrew Ingram

Louis Sayers wrote:
> I have an Image model:
>   
...
> Exception Type: AttributeError at /listings/add/
> Exception Value: 'ImageWithThumbsField' object has no attribute 'find'
>
>
> I'm really struggling with this error, if anyone has any ideas, I'll
> be glad to hear them :)
>
> Thanks

What version of Django are you using? Revision 9766 of trunk breaks 
quite a lot of stuff to do with ImageFields and it hasn't been fixed 
yet. Basically anything which requires handling the file prior to saving 
in admin (calculating dimensions for example) doesn't work and will 
cause an exception.

I've rolled back to revision 9765 for the time being.

Regards,
Andrew Ingram

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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
-~--~~~~--~~--~--~---



problem with simple shopping cart

2009-02-02 Thread lnysrogh

Hello. I'm new to Django (and web development in general), and this is
my first post here. Hope someone can help me.

I'm trying to build a shopping cart, and my idea is to store the
product information (id and quantity) in a session when I add the
product to the shopping cart, and retrieve it to display in the "show
cart" page. I'm using sessions for this because I don't want the user
to have to log in or register just to add some items to the cart and
see the total price. When he logs in to actually buy something, I
pretend to store it in a cart model, but I didn't get there yet. I'll
show you the code I'm testing:

def add(request, product_id):
request.session.set_test_cookie()
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
added = Product.objects.get(id=product_id)
request.session['product_id'] = added
return HttpResponseRedirect('/cart/')
else:
return HttpResponse('You need to enable cookies')

def cart(request):
if 'product_id' in request.session:
cart = request.session['product_id']
return render_to_response('cart.html', {'cart': cart})
else:
return HttpResponse('Cart is empty')

That's what I was able to come up with. The first problem is, it's not
working. The second problem is, I can't figure out how to add more
than one product to the cart.

The error I'm getting when I add something to the cart is "Caught an
exception while rendering: 'Product' object is not iterable". I'm
pretty sure that error has something to do with the cart.html, because
if I replace that line with:

return HttpResponse('You've added the product %s to the cart' % cart)

it works. The cart.html is just this:

{% for product in cart %}
Your cart: {{ product.name }} - {{product.price}}
{% endfor %}

It should work, right? I just can't figure what's causing that error.

Also, I need to be able to add more than one product to the cart, of
course, and to remove them as well. I was thinking of having the key
be the product id, and the value be the quantity. But how can I make
the id inside the product_id variable BE the name of the key? I don't
know if I'm making myself clear, english isn't my first language...
but when I call "request.session['product_id']", instead of it being
product_id, it could be the number inside it. If the product_id is 1,
it'd call "request.session['1']" or something like that. Or maybe have
multiple values for the product_id key, but then I'd have to think of
something else to work with the quantities. Maybe this isn't the
solution, but like I said, I'm pretty new to this and maybe I just
don't think like a programmer yet.

If someone has a simple solution to these problems, I'd be eternally
grateful.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Customized model methods

2009-02-02 Thread Alex Jonsson

On Feb 2, 9:50 pm, Daniel Roseman 
wrote:
> You can define as many methods on a model as you like. Models are just
> Python classes, and you can do anything with them that you would do
> with a normal class.
>
> def MyModel(models.Model):
>     ... field definitions ...
>
>     def is_sports(self):
>         return 'sports' in self.tag_list
>
>     def is_personal(self):
>         return 'personal' in self.tag_list
>
> Is that what you want? It'll get unmaintainable pretty fast, though.
> --
> DR.

Daniel,

Thanks for your answer. Yes, I could define a method for each call.
But that would result in a lot of methods, and not to mention; it
violates the DRY principle ;).
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 do I add a Custom ID Field that increments?

2009-02-02 Thread Will Hardy

There's no easy solution without saving the object to the database.
Auto incrementing fields (AutoField or just id) get their value from
the database, so they wont have one until you save. This is good
because it prevents multiple objects ever having the same value. One
way to do what you want is to save a new invoice to the database
straight away when the user clicks "add new invoice" and allow them to
edit it, but if you're using the admin site, this might not be
straightforward.

You wont need to create a new field by the way, you could simply make
a property that uses the ID field of a model:

@property
def invoice_id(self):
if self.id:
return 'INV%d' % self.id

But you wouldn't be able to search for the full INV001 string, you
would have to strip the INV beforehand or create a new charfield and
populate that on save (sounds like what you're doing)

If you don't want to have such obvious incrementing values for your
invoice numbers, you could use a perfect hash function to convert it
to a more obscure value, like
http://www.djangosnippets.org/snippets/1249/ (I wrote this snippet,
don't worry that two people voted against it, they didn't say why... I
have no idea... it's just a simple perfect hash function and base
converter, and it certainly does the job it was designed to do)

Cheers,

Will

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 view - merge two tables? (potentially bad db design)

2009-02-02 Thread Zbigniew Braniecki


On Feb 2, 7:24 am, Carl Meyer  wrote:
(...)
> The other downside is the extra administration complexity, which is
> the meat of your question.  Fortunately Django's admin can help you
> out, and it's quite easy: look into inlines[1].
>
> [1]http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodelad...

That's perfectly what I was looking for! Thanks!

So now I have it presented and I can use django admin panel to manage
it. One following question:

How can I overwrite the way Questions are selected so that when they
are returned by Question.objects.get('x') or Question.objects.filter()
or Question.objects.all() they are already joined with
QuestionProperties values?

Thanks!
Zbigniew Braniecki
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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
-~--~~~~--~~--~--~---



Error saving a Model with a custom image field

2009-02-02 Thread Louis Sayers

I have an Image model:

class Image(models.Model):
photo = ImageWithThumbsField(
upload_to=image_upload_location,
sizes=((thumb_widths,thumb_heights),))

The ImageWithThumbsField is something I got from 
http://code.google.com/p/django-thumbs/
It seems to work fine when I have a ModelForm created from the Image
model, but at the moment I'm trying to create a Image object, and save
it - so I do this:

new_image = ImageWithThumbsField(images_to_save[image],
upload_to=ListingModels.image_upload_location,
sizes=((ListingModels.thumb_widths,
ListingModels.thumb_heights),))
image_object= Image(photo=new_image)
image_object.save()


The ImageWithThumbsField class extends django.db.models.ImageField,
and sets another class 'ImageWithThumbsFieldFile' as the attr_class.

I'm guessing that the attr_class is used when the Model is saved -as
the ImageWithThumbsFieldFile __init__ method is called when the model
is being saved:

class ImageWithThumbsFieldFile(ImageFieldFile):
"""
See ImageWithThumbsField for usage example
"""
def __init__(self, *args, **kwargs):
super(ImageWithThumbsFieldFile, self).__init__(*args,
**kwargs)
self.sizes = self.field.sizes

if self.sizes:
def get_size(self, size):
if not self:
return ''
else:
split = self.url.rsplit('.',1)
thumb_url = '%s.%sx%s.%s' % (split[0],w,h,split
[1])
return thumb_url

for size in self.sizes:
(w,h) = size
setattr(self, 'url_%sx%s' % (w,h), get_size(self,
size))


The Line that causes the failure is in ImageWithThumbsFieldFile, and
is the  split = self.url.rsplit('.',1) line.

Traceback:
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py"
in get_response
  86. response = callback(request, *callback_args,
**callback_kwargs)
File "/usr/lib/python2.5/site-packages/django/contrib/auth/
decorators.py" in __call__
  67. return self.view_func(request, *args, **kwargs)
File "/home/louis/uniListings/../uniListings/listings/views.py" in add
  63. imageModel.save()
File "/usr/lib/python2.5/site-packages/django/db/models/base.py" in
save
  311. self.save_base(force_insert=force_insert,
force_update=force_update)
File "/usr/lib/python2.5/site-packages/django/db/models/base.py" in
save_base
  371. values = [(f, f.get_db_prep_save(raw and getattr
(self, f.attname) or f.pre_save(self, True))) for f in
meta.local_fields if not isinstance(f, AutoField)]
File "/usr/lib/python2.5/site-packages/django/db/models/fields/
__init__.py" in pre_save
  179. return getattr(model_instance, self.attname)
File "/usr/lib/python2.5/site-packages/django/db/models/fields/
files.py" in __get__
  122. instance.__dict__[self.field.name] =
self.field.attr_class(instance, self.field, file)
File "/home/louis/uniListings/listings/thumbs.py" in __init__
  118. setattr(self, 'url_%sx%s' % (w,h), get_size
(self, size))
File "/home/louis/uniListings/listings/thumbs.py" in get_size
  112. split = self.url.rsplit('.',1)
File "/usr/lib/python2.5/site-packages/django/db/models/fields/
files.py" in _get_url
  54. return self.storage.url(self.name)
File "/usr/lib/python2.5/site-packages/django/core/files/storage.py"
in url
  213. return urlparse.urljoin(self.base_url, name).replace('\
\', '/')
File "/usr/lib/python2.5/urlparse.py" in urljoin
  253. urlparse(url, bscheme, allow_fragments)
File "/usr/lib/python2.5/urlparse.py" in urlparse
  154. tuple = urlsplit(url, scheme, allow_fragments)
File "/usr/lib/python2.5/urlparse.py" in urlsplit
  193. i = url.find(':')

Exception Type: AttributeError at /listings/add/
Exception Value: 'ImageWithThumbsField' object has no attribute 'find'


I'm really struggling with this error, if anyone has any ideas, I'll
be glad to hear them :)

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: FormWizard accessing previous fields data

2009-02-02 Thread lbologn...@gmail.com

On Feb 3, 12:17 am, Johan Liseborn  wrote:

> Thus, you could do something like (no changes to get_template):
>
> class EnrollWizard(FormWizard):
>     def process_step(self, request, form, step):
>        if step == 0:
>           self.extra_context['foo'] = form.cleaned_data['foo']
>        elif step == 1:
>           self.extra_context['bar'] = form.cleaned_data['bar']
>        elif step == 3:
>           self.extra_context['baz'] = form.cleaned_data['baz']
>
> Now, in each template you will have access to more and more additional  
> information, just like so:
>
> {{ foo }}

Good solution, i like it!

Thanks,
Lorenzo
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: "invalid reference to FROM-clause" for nested annotate query

2009-02-02 Thread Russell Keith-Magee

On Mon, Feb 2, 2009 at 4:46 PM, omat  wrote:
>
> I just remembered that the above error occured when running on
> Postgresql 8.2. Sorry for the misinformation about SQLite.
>
> Then to give it a try with SQLite, I built a fresh database with
> syncdb on SQLite.
>
> This time, at the same point, I get a:
>
> OperationalError: no such column: tagging_taggeditem.added
>
>
> This is very strange, because the column 'added' is surely there.

I can now confirm I am seeing the same problem. It appears that the
table names aren't being correctly promoted in the GROUP BY clause for
the inner query.

If you could open a ticket providing all the detail you have provided
here, I will ensure this bug gets fixed before we release v1.1

Many Thanks,
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: FormWizard accessing previous fields data

2009-02-02 Thread Johan Liseborn

On Feb 2, 2009, at 23:32, lbologn...@gmail.com wrote:

> On Feb 1, 2:38 am, "mattimust...@gmail.com" 
> wrote:
>
>> I never understood the logic of it either. I also expected to be able
>> to do  something like {{previous_fields.firstname }}.
>
> Found it!
>
> class EnrollWizard(FormWizard):
>
>def get_template(self, step):
>return 'enroll_wizard_%s.html' % step
>
>def process_step(self, request, form, current_step):
>
>if current_step == 3:
>form0 = self.get_form(0, request.POST)
>form1 = self.get_form(1, request.POST)
>form2 = self.get_form(2, request.POST)
>
>context = (dict(form0=form0, form1=form1, form2=form2))
>
>return render_to_response(self.get_template(self.step),
> context)
>
> And then in the template to display a summary i play with ifequal
>
>  {%ifequal form0.course 2%}
>  Intensive course
>  {%endif%}
>
>  {%ifequal form0.course 1%}
>  Standard course
>  {%endif%}
>
> If anybody has a more elegant solution i'm all ears!

Not sure whether it is more elegant or not, but here goes:

As I understand it, the wizard-class contains an extra_context that  
automatically gets handed to the templates. You can modify the  
extra_context in the process_step-method, allowing you to add  
additional information for each step you go through. Also, as I  
understand it, the process_step-method is given a cleaned (correct)  
form for the current step, so you can extract information from that  
form and put it into the extra_context.

Thus, you could do something like (no changes to get_template):

class EnrollWizard(FormWizard):
def process_step(self, request, form, step):
   if step == 0:
  self.extra_context['foo'] = form.cleaned_data['foo']
   elif step == 1:
  self.extra_context['bar'] = form.cleaned_data['bar']
   elif step == 3:
  self.extra_context['baz'] = form.cleaned_data['baz']

Now, in each template you will have access to more and more additional  
information, just like so:

{{ foo }}

{{ bar }}

{{ baz }}

I am not sure exactly how this maps to your example (as I do not fully  
understand it), but maybe it could simplify things slightly for you?


Now, if someone could point me to a simple way of combining form  
wizards with formsets, my day would be complete... :-)


Cheers,

johan

-- 
Johan Liseborn





--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Model Save with Updated Foreign Key

2009-02-02 Thread Jeff

Nevermind. I had overriden the get_query_set with a custom manager
that only returned a subset of the CEOs. Word to the wise.

On Feb 2, 1:04 pm, Jeff  wrote:
> So I have two models a CEO model:
> class Ceo (models.Model):
>     first_name = models.CharField(max_length=63)
>     last_name = models.CharField(max_length=63)
>     website = models.URLField()
>     company_name = models.CharField(max_length=63, unique=False)
>     company_address = models.ForeignKey(Address)
>     ctime = models.DateTimeField(auto_now=True)
>     mtime = models.DateTimeField(auto_now_add=True)
>
> Which was originally created with manage.py syncdb. I've since added a
> model to track industries:
>
> class Industry(models.Model):
>     name = models.CharField(max_length=63)
>
> and a foreignkey field to Ceo:
>     industry = models.ForeignKey(Industry, null=True)
>
> all is fine and good on the backend in the database (e.g. I
> successfully migrated the db after the change). I'm trying to import
> the industries to each ceo instance with the following code:
>
> def update_ceo_industry(**kwargs):
>   ceo  = Ceo.objects.get(**{
>             'first_name': kwargs['fname'],
>             'last_name': kwargs['lname'],
>             'website': kwargs['Website'],
>             'company_name': kwargs['Company'],
>         })
>    #I get the industry's name here and store it in industry
>    industry_obj, created = Industry.objects.get_or_create(**{'name':
> unicode(industry)})
>    ceo.industry = industry_obj
>    ceo.save(force_update=True)
>    return
>
> When I run this I can see that the industry is created, but once it
> gets to the save function throws this error:
>   File "industry_getter.py", line 75, in update_ceo_industry
>     ceo.save(force_update=True)
>   File "/usr/lib/python2.5/site-packages/django/db/models/base.py",
> line 328, in save
>     self.save_base(force_insert=force_insert,
> force_update=force_update)
>   File "/usr/lib/python2.5/site-packages/django/db/models/base.py",
> line 381, in save_base
>     raise DatabaseError("Forced update did not affect any rows.")
>
> When I take out forced_update=True I get:
>
> File "industry_getter.py", line 75, in update_ceo_industry
>     ceo.save()
>   File "/usr/lib/python2.5/site-packages/django/db/models/base.py",
> line 328, in save
>     self.save_base(force_insert=force_insert,
> force_update=force_update)
>   File "/usr/lib/python2.5/site-packages/django/db/models/base.py",
> line 400, in save_base
>     result = manager._insert(values, return_id=update_pk)
>   File "/usr/lib/python2.5/site-packages/django/db/models/manager.py",
> line 144, in _insert
>     return insert_query(self.model, values, **kwargs)
>   File "/usr/lib/python2.5/site-packages/django/db/models/query.py",
> line 1004, in insert_query
>     return query.execute_sql(return_id)
>   File "/usr/lib/python2.5/site-packages/django/db/models/sql/
> subqueries.py", line 317, in execute_sql
>     cursor = super(InsertQuery, self).execute_sql(None)
>   File "/usr/lib/python2.5/site-packages/django/db/models/sql/
> query.py", line 1974, in execute_sql
>     cursor.execute(sql, params)
>   File "/usr/lib/python2.5/site-packages/django/db/backends/util.py",
> line 19, in execute
>     return self.cursor.execute(sql, params)
> psycopg2.IntegrityError: duplicate key value violates unique
> constraint "finance_ceo_pkey"
>
> Now the problem here is that if I try:
>
> select * from finance_ceo where industry_id is not null;
>
> I get 0 rows in either case. But the industry row is there:
>
> select * from finance_industry;  yields:
>
>   1 | Commercial Banks
>
> So what's wrong with the lines:
>
>    ceo.industry = industry_obj
>    ceo.save(force_update=True)
>
> Any thoughts?
>
> --Jeff
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: FileField and moving or updating files

2009-02-02 Thread felix
I was just learning/dealing with this now.

example:

class Mix(models.Model):
   mp3 = models.FileField(upload_to="mixes",blank=True)

# let's say the mix object already exists
mix = Mix.objects.get(  etc )


# however you get a file

file = request.FILES[u'Filedata']

# swfupload is awesome btw.

or by opening it from your post processed folder somewhere
or by creating a file directly in memory using content, or PIL etc.

then the correct way is this:

if mix.mp3.name: # if there is a previous file and we wish to delete it
   mix.mp3.storage.delete( mix.mp3.name )

get the field's defined storage to delete it

#name will be eg. "mixes/oldfile.mp3"

ideal_path = "mixes/newfile.mp3"

# save the new file into storage
saved_to = mix.mp3.storage.save( ideal_path, file )


the path may have _ added to it for non-clobber purposes and is returned
with the real path

# assign the string directly to the file field input
mix.mp3 = saved_to

# and save the new path into the object
mix.save()


this is nice in that you can switch the storage later or use multiple
storage systems across your site,
not just

from django.core.files.storage import default_storage
default_storage.save( path, file)


you can upload to "tempUploads/file.xxx" and then search for files whose
names are still in tempUploads and thus not yet processed

 felix :crucial-systems.com



On Mon, Feb 2, 2009 at 11:26 PM, timc3  wrote:

>
> So I take it that there is no way of doing 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: simple record output

2009-02-02 Thread John M

BRILLIANT, that's what I was looking for , thanks Jake!

On Feb 2, 2:19 pm, Jake Elliott  wrote:
> hi john -
>
> you can use the 'spaceless' tag in your 
> template:http://docs.djangoproject.com/en/dev/ref/templates/builtins/#spaceless
>
> to filter out spaces & carriage returns.
>
> -jake
>
> On Mon, Feb 2, 2009 at 3:41 PM, John M  wrote:
>
> > Grrr, I answered my own quesiton, if I remove all the CR's from the
> > template, then it's OK.
>
> > So changing the template to
>
> > {% if object_list %}{% for obj in object_list %}{{ obj.name }}{%
> > endfor %}{% endif %}
>
> > Works like I want.  But now, how can I not have the CR's in the
> > template effect my output?
>
> > Thanks
>
> > On Feb 2, 12:57 pm, John M  wrote:
> >> I'm trying to use the generic views and templates to get a very simple
> >> text output of records.
>
> >> I don't want HTML, but need them available from a command line (via
> >> curl).
>
> >> Here's my URL setup.
> >> newhosts_dict = {
> >>         'queryset' : unixhost.objects.all().filter(hostsetting__userlist =
> >> False)
> >>         }
>
> >> urlspatterns...
>
> >>         (r'^likewise/newhosts/$',
> >> 'django.views.generic.list_detail.object_list', newhosts_dict),
>
> >> here's the template:
>
> >> {% if object_list %}
> >> {% for obj in object_list %}
> >> {{ obj.name }}
> >> {% endfor %}
> >> {% endif %}
>
> >> If the queryset only has 1 record in it, why do I have three lines in
> >> my output?  1 blank, 1 record output, and one 1 blank.
>
> >> thoughts?
>
> >> 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: FormWizard accessing previous fields data

2009-02-02 Thread lbologn...@gmail.com

On Feb 1, 2:38 am, "mattimust...@gmail.com" 
wrote:

> I never understood the logic of it either. I also expected to be able
> to do  something like {{previous_fields.firstname }}.

Found it!

class EnrollWizard(FormWizard):

def get_template(self, step):
return 'enroll_wizard_%s.html' % step

def process_step(self, request, form, current_step):

if current_step == 3:
form0 = self.get_form(0, request.POST)
form1 = self.get_form(1, request.POST)
form2 = self.get_form(2, request.POST)

context = (dict(form0=form0, form1=form1, form2=form2))

return render_to_response(self.get_template(self.step),
context)

And then in the template to display a summary i play with ifequal

  {%ifequal form0.course 2%}
  Intensive course
  {%endif%}

  {%ifequal form0.course 1%}
  Standard course
  {%endif%}

If anybody has a more elegant solution i'm all ears!

Thanks,
Lorenzo
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Wierd FileField behavior

2009-02-02 Thread timc3

Show us the code for your view. But are you sending through the files
in the POST each time?
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: FileField and moving or updating files

2009-02-02 Thread timc3

So I take it that there is no way of doing 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: simple record output

2009-02-02 Thread Jake Elliott

hi john -

you can use the 'spaceless' tag in your template:
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#spaceless

to filter out spaces & carriage returns.

-jake

On Mon, Feb 2, 2009 at 3:41 PM, John M  wrote:
>
> Grrr, I answered my own quesiton, if I remove all the CR's from the
> template, then it's OK.
>
> So changing the template to
>
> {% if object_list %}{% for obj in object_list %}{{ obj.name }}{%
> endfor %}{% endif %}
>
> Works like I want.  But now, how can I not have the CR's in the
> template effect my output?
>
> Thanks
>
>
> On Feb 2, 12:57 pm, John M  wrote:
>> I'm trying to use the generic views and templates to get a very simple
>> text output of records.
>>
>> I don't want HTML, but need them available from a command line (via
>> curl).
>>
>> Here's my URL setup.
>> newhosts_dict = {
>> 'queryset' : unixhost.objects.all().filter(hostsetting__userlist =
>> False)
>> }
>>
>> urlspatterns...
>>
>> (r'^likewise/newhosts/$',
>> 'django.views.generic.list_detail.object_list', newhosts_dict),
>>
>> here's the template:
>>
>> {% if object_list %}
>> {% for obj in object_list %}
>> {{ obj.name }}
>> {% endfor %}
>> {% endif %}
>>
>> If the queryset only has 1 record in it, why do I have three lines in
>> my output?  1 blank, 1 record output, and one 1 blank.
>>
>> thoughts?
>>
>> 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: simple record output

2009-02-02 Thread John M

Grrr, I answered my own quesiton, if I remove all the CR's from the
template, then it's OK.

So changing the template to

{% if object_list %}{% for obj in object_list %}{{ obj.name }}{%
endfor %}{% endif %}

Works like I want.  But now, how can I not have the CR's in the
template effect my output?

Thanks


On Feb 2, 12:57 pm, John M  wrote:
> I'm trying to use the generic views and templates to get a very simple
> text output of records.
>
> I don't want HTML, but need them available from a command line (via
> curl).
>
> Here's my URL setup.
> newhosts_dict = {
>         'queryset' : unixhost.objects.all().filter(hostsetting__userlist =
> False)
>         }
>
> urlspatterns...
>
>         (r'^likewise/newhosts/$',
> 'django.views.generic.list_detail.object_list', newhosts_dict),
>
> here's the template:
>
> {% if object_list %}
> {% for obj in object_list %}
> {{ obj.name }}
> {% endfor %}
> {% endif %}
>
> If the queryset only has 1 record in it, why do I have three lines in
> my output?  1 blank, 1 record output, and one 1 blank.
>
> thoughts?
>
> 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
-~--~~~~--~~--~--~---



Making fields conditionally required based on another field's state

2009-02-02 Thread wotaskd

Hello everyone, a quick (and I guess easy) one:

Is there any way, on the admin site, to make a field for a model
mandatory, if another one is blank and vice-versa?

Ex: let's pretend that I have two fields, SSN and ID. The customer has
to fill out at least one of the two, any of them, but can't leave both
blank.

In my case, one of the fields will be a CharField and the other one a
ForeignKey.

Thanks!

wotaskd
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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
-~--~~~~--~~--~--~---



simple record output

2009-02-02 Thread John M

I'm trying to use the generic views and templates to get a very simple
text output of records.

I don't want HTML, but need them available from a command line (via
curl).

Here's my URL setup.
newhosts_dict = {
'queryset' : unixhost.objects.all().filter(hostsetting__userlist =
False)
}

urlspatterns...

(r'^likewise/newhosts/$',
'django.views.generic.list_detail.object_list', newhosts_dict),

here's the template:

{% if object_list %}
{% for obj in object_list %}
{{ obj.name }}
{% endfor %}
{% endif %}

If the queryset only has 1 record in it, why do I have three lines in
my output?  1 blank, 1 record output, and one 1 blank.

thoughts?

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: Customized model methods

2009-02-02 Thread Daniel Roseman

On Feb 2, 8:39 pm, Alex Jonsson  wrote:
> Dave,
>
> Thank you for your answer. Thing is, I already use django-tagging.
>
> I was a bit unclear: I'd like the function to return True or False, so
> that I can run some logic on it based on that. When I use django-
> tagging today the closest I can get to check if a tag is included in
> an object is to run a ifequal, and that's no good.
>
> Hopefully you get my point?
>
> Thanks,
> Alex
>

You can define as many methods on a model as you like. Models are just
Python classes, and you can do anything with them that you would do
with a normal class.

def MyModel(models.Model):
... field definitions ...

def is_sports(self):
return 'sports' in self.tag_list

def is_personal(self):
return 'personal' in self.tag_list

Is that what you want? It'll get unmaintainable pretty fast, though.
--
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: Displaying the names of executed tests

2009-02-02 Thread Julien Phalip

On Feb 3, 2:47 am, Alex Koshelev  wrote:
> Look at the `--verbosity` test command option

Thanks Alex, I should have thought of that.

Cheers,

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



Re: Customized model methods

2009-02-02 Thread Alex Jonsson

Dave,

Thank you for your answer. Thing is, I already use django-tagging.

I was a bit unclear: I'd like the function to return True or False, so
that I can run some logic on it based on that. When I use django-
tagging today the closest I can get to check if a tag is included in
an object is to run a ifequal, and that's no good.

Hopefully you get my point?

Thanks,
Alex

On Feb 1, 11:50 pm, Dave Fowler  wrote:
> Well you might want to start by looking into django-tagging
>
> http://code.google.com/p/django-tagging/wiki/UsefulTips
>
> Install that for easy tags, and that link to the useful tips shows how
> to retrieve and set tags.
>
> Also instead of doing a lot of is_this() and is_that() you will
> probably want to do what the tips there describe instead get a list of
> the tags
>
> >>> tag_list = blog_entry.tags()
> >>> tag_list
>
> ['sports', 'whatever']
>
> If you need to run different functions for the different tags you can
> put them into a dict to execute
>
> >>> def example_func( tag_name )
>
> ...        print tag_name
>
> >>> tag_funcs = {'sports': example_func, 'personal': example_func, 
> >>> 'whatever': example_func }
> >>> for tag_name in tag_list:
>
>         tag_funcs[ tag_name ]( tag_name )  # This executes the
> right function from tag_funcs with input tag_name
>
> Hope that helps?
>
> On Feb 1, 3:58 pm, Alex Jonsson  wrote:
>
>
>
> > Hey guys,
>
> > I'm looking to create a model method like is_(), where the tag
> > can be used to lookup if the object is tagged with a certain ... tag.
> > Kind of like this:
>
> > A blog entry is tagged "personal" and "funny".
>
> > >> blog_entry.is_sports()
> > False
> > >> blog_entry.is_personal()
> > True
> > >> blog_entry.is_whatever()
>
> > False
>
> > You probably get the point. Could someone perhaps explain how to do it
> > or point me in the right direction?
>
> > Thanks,
> > Alex
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Autogenerate a Model on Save

2009-02-02 Thread Will Matos
The downside to putting it in the form is that the form should only be used for 
presentation. Putting this logic in the form is pushing programatic decisions 
to the presentation layer. 

I believe the better approach is defining a view method that can be shared by 
multiple urls. 




From: django-users@googlegroups.com 
To: django-users@googlegroups.com 
Sent: Mon Feb 02 15:16:07 2009
Subject: Re: Autogenerate a Model on Save 



the view is the first, and most easily understandable place to put it. 

the form logic may make your head hurt more at first, but eventually you'll 
feel more comfortable putting it there.

nothing wrong with coding it in the view

but OTOH you will get the same functionality if you use the form in your own 
view or in the admin.
and if you create more views for different purposes, they can all use that form.




On Mon, Feb 2, 2009 at 9:09 PM, Will Matos  wrote:


Agreed. Your class is being saved in a view method. Upon successful 
saves create a new one. 





From: django-users@googlegroups.com 
To: django-users@googlegroups.com 
Sent: Mon Feb 02 15:07:48 2009
Subject: Re: Autogenerate a Model on Save 

generally you should keep this type of business logic out of the model

the place to put it is either in the Form
or the view


class OrderModelForm(forms.ModelForm):

class Meta:
model = Order

def save_model(self, request, obj, form, change):
"""
Given a model instance save it to the database.
"""

if not change: # only when adding
obj.created_by = request.user
if(not obj.from_email):
obj.from_email = request.user.email
#create your invoice now

obj.save()


# and if you are using that in the admin then add it to the admin too:

class OrderAdmin(admin.ModelAdmin):

form = OrderModelForm


and register it







  felix :  
crucial-systems.com 



On Mon, Feb 2, 2009 at 8:50 PM, Alfonso  
wrote:



I'm full of queries today!...This one seems a simple notion 
that I
can't get my head around...How would I get django to 
auto-generate a
new Invoice record and populate with some values when a user 
saves a
new Order record?  A custom def save(self) method?

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: Auction app

2009-02-02 Thread bobhaugen

http://code.google.com/p/django-swaps/ is not an auction app, it's a
swapping app (trade anything for anything between registered users of
a django site, initially developed for pinax).

But it might be useful as a starting point for an auction app if you
can't find anything fully tailored.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Autogenerate a Model on Save

2009-02-02 Thread felix
the view is the first, and most easily understandable place to put it.

the form logic may make your head hurt more at first, but eventually you'll
feel more comfortable putting it there.

nothing wrong with coding it in the view

but OTOH you will get the same functionality if you use the form in your own
view or in the admin.
and if you create more views for different purposes, they can all use that
form.



On Mon, Feb 2, 2009 at 9:09 PM, Will Matos  wrote:

> Agreed. Your class is being saved in a view method. Upon successful saves
> create a new one.
>
> --
>  *From*: django-users@googlegroups.com
> *To*: django-users@googlegroups.com
> *Sent*: Mon Feb 02 15:07:48 2009
> *Subject*: Re: Autogenerate a Model on Save
> generally you should keep this type of business logic out of the model
>
> the place to put it is either in the Form
> or the view
>
>
> class OrderModelForm(forms.ModelForm):
>
> class Meta:
> model = Order
>
> def save_model(self, request, obj, form, change):
> """
> Given a model instance save it to the database.
> """
>
> if not change: # only when adding
> obj.created_by = request.user
> if(not obj.from_email):
> obj.from_email = request.user.email
> #create your invoice now
>
> obj.save()
>
>
> # and if you are using that in the admin then add it to the admin too:
>
> class OrderAdmin(admin.ModelAdmin):
>
> form = OrderModelForm
>
>
> and register it
>
>
>
>
>
>  felix :crucial-systems.com
>
>
>
> On Mon, Feb 2, 2009 at 8:50 PM, Alfonso  wrote:
>
>>
>> I'm full of queries today!...This one seems a simple notion that I
>> can't get my head around...How would I get django to auto-generate a
>> new Invoice record and populate with some values when a user saves a
>> new Order record?  A custom def save(self) method?
>>
>> 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: Autogenerate a Model on Save

2009-02-02 Thread Will Matos
Agreed. Your class is being saved in a view method. Upon successful saves 
create a new one. 



From: django-users@googlegroups.com 
To: django-users@googlegroups.com 
Sent: Mon Feb 02 15:07:48 2009
Subject: Re: Autogenerate a Model on Save 


generally you should keep this type of business logic out of the model

the place to put it is either in the Form
or the view


class OrderModelForm(forms.ModelForm):

class Meta:
model = Order

def save_model(self, request, obj, form, change):
"""
Given a model instance save it to the database.
"""

if not change: # only when adding
obj.created_by = request.user
if(not obj.from_email):
obj.from_email = request.user.email
#create your invoice now

obj.save()


# and if you are using that in the admin then add it to the admin too:

class OrderAdmin(admin.ModelAdmin):

form = OrderModelForm


and register it







  felix :  
crucial-systems.com 



On Mon, Feb 2, 2009 at 8:50 PM, Alfonso  wrote:



I'm full of queries today!...This one seems a simple notion that I
can't get my head around...How would I get django to auto-generate a
new Invoice record and populate with some values when a user saves a
new Order record?  A custom def save(self) method?

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: Autogenerate a Model on Save

2009-02-02 Thread felix
generally you should keep this type of business logic out of the model

the place to put it is either in the Form
or the view


class OrderModelForm(forms.ModelForm):

class Meta:
model = Order

def save_model(self, request, obj, form, change):
"""
Given a model instance save it to the database.
"""

if not change: # only when adding
obj.created_by = request.user
if(not obj.from_email):
obj.from_email = request.user.email
#create your invoice now

obj.save()


# and if you are using that in the admin then add it to the admin too:

class OrderAdmin(admin.ModelAdmin):

form = OrderModelForm


and register it





 felix :crucial-systems.com



On Mon, Feb 2, 2009 at 8:50 PM, Alfonso  wrote:

>
> I'm full of queries today!...This one seems a simple notion that I
> can't get my head around...How would I get django to auto-generate a
> new Invoice record and populate with some values when a user saves a
> new Order record?  A custom def save(self) method?
>
> 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
-~--~~~~--~~--~--~---



Autogenerate a Model on Save

2009-02-02 Thread Alfonso

I'm full of queries today!...This one seems a simple notion that I
can't get my head around...How would I get django to auto-generate a
new Invoice record and populate with some values when a user saves a
new Order record?  A custom def save(self) method?

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



How do I add a Custom ID Field that increments?

2009-02-02 Thread Alfonso

Hey,

I want to add a field to an invoice model that contains a custom auto-
incrementing value in the format - 'INV01" which increments...
INV02 (obviously!).  Anyone have a simple way I can build that
into the model when a user clicks 'Add New Invoice'? I've written
custom save methods but not one that implements on adding a new
record?

Thanks, any help would be great



--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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
-~--~~~~--~~--~--~---



select_related and OneToOneField

2009-02-02 Thread Michael Hrivnak

Does select_related work for OneToOneField relationships?  If so, does it work 
in both directions?

Thanks,
Michael

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



Re: object_detail 404 (queryset outdated?)

2009-02-02 Thread Simon Westphahl

I finally got it to work! I wrapped the object_detail view with a view
that calls the manager method as suggested by Carl.

Thank you!

On 2 Feb., 16:38, Carl Meyer  wrote:
> I think you've got the right idea of what's going wrong, but you're
> looking for the problem in the wrong place.  This method isn't module-
> level code; it will be executed anew each time you query on this
> manager.  More likely is that you're storing a reference to the
> returned queryset in module-level code; probably in a dictionary of
> kwargs you're passing to the object_detail generic view (most likely
> in your urls.py).  It's that queryset that is never getting updated;
> the call to your manager method is happening only once, when the
> urls.py module is first loaded.
>
> The solution is to wrap the object_detail view with a very lightweight
> view of your own that calls the manager method and passes the
> resulting queryset in to object_detail.  Then the queryset will be re-
> created for each request.
>
> Carl
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: docs: Problem with 'make html'

2009-02-02 Thread Benjamin Buch

Thanks for ointing me in the right direction!
I had the sphinx version from macports installes, which was something  
about 0.1.6 or something...
Installed 0.5.1 via easy_install (which didn't work quite well, but  
did...)

Now it works.

benjamin

Am 01.02.2009 um 12:40 schrieb Ramiro Morales:

>
> On Sat, Jan 31, 2009 at 8:48 AM, Benjamin Buch   
> wrote:
>>
>> Hi,
>>
>> if I do 'make html' in my django-trunk/docs directory, I get this  
>> error:
>>
>> [...]
>>
>> Traceback (most recent call last):
>>  File "/opt/local/lib/python2.5/site-packages/sphinx/__init__.py",
>> line 114, in main
>>confoverrides, status, sys.stderr, freshenv)
>>  File "/opt/local/lib/python2.5/site-packages/sphinx/
>> application.py", line 81, in __init__
>>self.setup_extension(extension)
>>  File "/opt/local/lib/python2.5/site-packages/sphinx/
>> application.py", line 120, in setup_extension
>>mod.setup(self)
>>  File "/Users/benjamin/Code/django/django-trunk/docs/_ext/
>> djangodocs.py", line 15, in setup
>>app.add_crossref_type(
>> AttributeError: 'Sphinx' object has no attribute 'add_crossref_type'
>>
>> I'm using a recent version of django.
>
> Which version of Sphinx are you using?.
>
> -- 
> Ramiro Morales
>
> 

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



Re: Missing REFERENCES... in SQL of models.ForeignKey('LaterDefinedModel')

2009-02-02 Thread mucisland

On Jan 31, 2:31 am, Malcolm Tredinnick 
wrote:
> On Sat, 2009-01-31 at 12:20 +1100, Malcolm Tredinnick wrote:
> > On Fri, 2009-01-30 at 09:49 -0800, mucisland wrote:
> > > Hi all.
>
> > > If I specify the ForeignKey target model as a string because it is not
> > > yet defined, the (SQLite3) SQL table entry misses the REFERENCES
> > > specifier. Example:
>
> > SQLite doesn't support "references" constraints. So we don't bother
> > writing them out (it doesn't support relations). There's no bug here.
>
> When I said "doesn't support relations", I meant "doesn't *enforce*
> relations* at the database level. You can still use foreign keys and
> many-to-many fields and the like in Django. But the data integrity at
> the database level isn't enforced by SQLite.

Thanks for your answer, Malcolm!

So I assume the PostgreSQL backend would write the references
constrained into the SQL? And for the SQLite3 backend, it's strange
that it sometimes writes the references constraint and sometimes not.
I stress this point because I'd like to have a stable SQL database
scheme before I enter my data. Loading serialized data into a changed
database scheme is a PITA, or I just didn't find the right way to do
it yet...

Best Regards,
Dirk
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 contenttype/renaming of an app

2009-02-02 Thread Benjamin Buch
I think I've got it now.
I didn't dump the data of the seperate apps, but everything.
So I dumped some auth tables too.

Strangely, some tables of 'stanza' were not installed, but ./manage.py  
syncdb fixed this.

Got to get accustomed to SQL some more... ;-)

benjamin

Am 24.01.2009 um 21:38 schrieb felix:

>
> look in auth_permission
>
> I would just rename them by hand or by sql
>
>
> http://crucial-systems.com
>
>
>
> On Sat, Jan 24, 2009 at 8:19 PM, Benjamin Buch   
> wrote:
>
> Hi,
>
> during development, I messed around with an app name.
> First it was called 'body copies' (no native speaker!), then I renamed
> it to 'stanza', which I liked better.
> No problem there: As there was no data in the db, I deleted the tables
> and created them again, with other names.
>
> Then I deployed the project.
> I transfered the data via manage.py dumpdata/loaddata.
> Still no problems when I'm logged in as admin.
>
> But:
> When I create a new user group and want to give permissions, there's
> still 'body copy' instead of 'stanza'.
> ('bodyopies | body copy | Can add static content' and so on...)
>
> If I give the bodycopy permissions and log in as a user with those
> permissions, I'm not able to edit 'stanza'.
> The 'stanza'-area won't even show up in the admin panel, neither does
> 'bodycopies'.
>
> I took a look at the database, and in the table 'django_content_type'
> I found some entries refering to 'bodycopies':
>
> id |name   |  app_label | model
> ---+---++---
> 09 | body copy | bodycopies | bodycopy
>
> I renamed them to the according 'stanza' labels.
> After that, in the group permissions on the group page 'stanza' showed
> up instead of 'bodycopies',
> but I still was not able to edit 'stanza' as non-admin-user.
>
> Any ideas?
>
> 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: newbie: printing a date in a template

2009-02-02 Thread KJ

On Feb 2, 7:11 pm, Christian Joergensen  wrote:
>
> Is `todaysdate` listed in your context?
>

This is my return line for the view, the locals() part should add all
the local variables to the template context right?

return render_to_response('items/browse.html', locals(),
context_instance=RequestContext(request))

KJ
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 Save with Updated Foreign Key

2009-02-02 Thread Jeff

So I have two models a CEO model:
class Ceo (models.Model):
first_name = models.CharField(max_length=63)
last_name = models.CharField(max_length=63)
website = models.URLField()
company_name = models.CharField(max_length=63, unique=False)
company_address = models.ForeignKey(Address)
ctime = models.DateTimeField(auto_now=True)
mtime = models.DateTimeField(auto_now_add=True)

Which was originally created with manage.py syncdb. I've since added a
model to track industries:

class Industry(models.Model):
name = models.CharField(max_length=63)

and a foreignkey field to Ceo:
industry = models.ForeignKey(Industry, null=True)

all is fine and good on the backend in the database (e.g. I
successfully migrated the db after the change). I'm trying to import
the industries to each ceo instance with the following code:

def update_ceo_industry(**kwargs):
  ceo  = Ceo.objects.get(**{
'first_name': kwargs['fname'],
'last_name': kwargs['lname'],
'website': kwargs['Website'],
'company_name': kwargs['Company'],
})
   #I get the industry's name here and store it in industry
   industry_obj, created = Industry.objects.get_or_create(**{'name':
unicode(industry)})
   ceo.industry = industry_obj
   ceo.save(force_update=True)
   return

When I run this I can see that the industry is created, but once it
gets to the save function throws this error:
  File "industry_getter.py", line 75, in update_ceo_industry
ceo.save(force_update=True)
  File "/usr/lib/python2.5/site-packages/django/db/models/base.py",
line 328, in save
self.save_base(force_insert=force_insert,
force_update=force_update)
  File "/usr/lib/python2.5/site-packages/django/db/models/base.py",
line 381, in save_base
raise DatabaseError("Forced update did not affect any rows.")

When I take out forced_update=True I get:

File "industry_getter.py", line 75, in update_ceo_industry
ceo.save()
  File "/usr/lib/python2.5/site-packages/django/db/models/base.py",
line 328, in save
self.save_base(force_insert=force_insert,
force_update=force_update)
  File "/usr/lib/python2.5/site-packages/django/db/models/base.py",
line 400, in save_base
result = manager._insert(values, return_id=update_pk)
  File "/usr/lib/python2.5/site-packages/django/db/models/manager.py",
line 144, in _insert
return insert_query(self.model, values, **kwargs)
  File "/usr/lib/python2.5/site-packages/django/db/models/query.py",
line 1004, in insert_query
return query.execute_sql(return_id)
  File "/usr/lib/python2.5/site-packages/django/db/models/sql/
subqueries.py", line 317, in execute_sql
cursor = super(InsertQuery, self).execute_sql(None)
  File "/usr/lib/python2.5/site-packages/django/db/models/sql/
query.py", line 1974, in execute_sql
cursor.execute(sql, params)
  File "/usr/lib/python2.5/site-packages/django/db/backends/util.py",
line 19, in execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique
constraint "finance_ceo_pkey"

Now the problem here is that if I try:

select * from finance_ceo where industry_id is not null;

I get 0 rows in either case. But the industry row is there:

select * from finance_industry;  yields:

  1 | Commercial Banks

So what's wrong with the lines:

   ceo.industry = industry_obj
   ceo.save(force_update=True)

Any thoughts?

--Jeff



--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Apache ImportError: Could not import settings

2009-02-02 Thread Bradley Wright

I had the following vhost.conf, which worked for me (before I switched
to WSGI):

NameVirtualHost 127.0.0.1

# dynamic Django site

ServerAdmin myem...@mysite.com

ServerName mysite.com

SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonDebug Off
SetEnv DJANGO_SETTINGS_MODULE "apps.production_settings"

PythonPath "['/var/www/sites/mysite'] + sys.path"

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
ErrorLog /var/log/apache2/mysite.error.log

ServerSignature Off



/var/www/sites/mysite/apps/production_settings.py was owned by the www-
data user (which Apache runs under in Debian-like environments) and
was read only (chmod 400).
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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: Can I control contents of SELECT in queryset?

2009-02-02 Thread phoebebright

After replicating you test and it still failing and various other
experiments I downloaded the latest django trunk and it works fine!
Always check the version first Phoebe!

Sorry for the run around.

For the record here are the two queries - correct one first, the
difference is in the SELECT part of subquery, SELECT U1.`cat_id`
instead of SELECT U0.`id`

SELECT `town_subcategory`.`name` FROM `town_subcategory` WHERE NOT
(`town_subcategory`.`id` IN (SELECT U0.`id` FROM `town_subcategory`
U0 LEFT OUTER JOIN `town_business` U1 ON (U0.`id` = U1.`cat_id`) WHERE
U1.`directory_ptr_id` IS NULL))

SELECT `town_subcategory`.`name` FROM `town_subcategory` WHERE NOT
(`town_subcategory`.`id` IN (SELECT U1.`cat_id` FROM
`town_subcategory` U0 LEFT OUTER JOIN `town_business` U1 ON (U0.`id` =
U1.`cat_id`) WHERE U1.`directory_ptr_id` IS NULL))



On Jan 31, 1:50 am, Malcolm Tredinnick 
wrote:
> On Fri, 2009-01-30 at 07:46 -0800, phoebebright wrote:
> > Using your suggestion returns no values:
>
> Then there is something else going on in your code that is important and
> you haven't mentioned yet.
>
> If I use exactly the models you give:
>
>
>
> > class Category(models.Model):
> >     name = models.CharField(max_length=12, unique=True)
> >     description = models.TextField()
>
> > class Subcategory(models.Model):
> >     category = models.ForeignKey(Category)
> >     name =  models.CharField(max_length=30, unique=True)
>
> > class Directory(models.Model):
> >     name = models.CharField(max_length=60)
> >     phone = models.CharField(max_length=15)
>
> > class Business(Directory):
> >     cat = models.ForeignKey(Subcategory, limit_choices_to =
> > {'category__exact': 2})
>
> And I create a couple of categories, a few subcategories and a couple of
> businesses linked to some (but not all) of the subcategories, then the
> queryset I gave:
>
>         Subcategory.objects.values('name').exclude(business=None)
>
> returns exactly the right information (a non-empty collection of the
> subcategories related to businesses).
>
> To work out what is different in your situation, I suggest you start
> from that point, too. Copy and paste exactly what is above, create a few
> objects and try the queryset. Make sure you get back results (or we have
> to work out why you don't). Then work out what is different between that
> simpler example and your real code.
>
> For reference, the SQL query that is being generated for the above
> queryset is this:
>
> In [5]:
> models.Subcategory.objects.values('name').exclude(business=None).query.as_sql()
>
> Out[5]:
> ('SELECT`phoebe_subcategory`.`name` FROM `phoebe_subcategory` WHERE NOT
> (`phoebe_subcategory`.`id` IN (SELECTU0.`id` FROM `phoebe_subcategory`
> U0 LEFT OUTER JOIN `phoebe_business` U1 ON (U0.`id` = U1.`cat_id`) WHERE
> U1.`directory_ptr_id` IS NULL))',
>  ())
>
> (I happen to be using MySQL there, so the quoting of names will vary
> slightly on other databases, but it's the same query in all cases).
>
> Regards,
> Malcolm
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: object_detail 404 (queryset outdated?)

2009-02-02 Thread Daniel Roseman

On Feb 2, 12:36 pm, Simon Westphahl  wrote:
> After some further investigation it seems this problem is related to
> my custom manager.
>
> ###
> class OfferManager(models.Manager):
>     def get_query_set(self):
>         return super(OfferManager, self).get_query_set().exclude
> (start_date__gt=datetime.now).exclude(end_date__lt=datetime.now)
> ###
>
> I'm using a queryset filtered with a callable (datetime.now) which
> appears to be set only once/on load time?!
> Does anyone no a way to work around this?
>
> Regards,
> Simon

Should you actually be calling datetime.now, rather than passing a
callable?
eturn super(OfferManager, self).get_query_set().exclude
(start_date__gt=datetime.now()).exclude(end_date__lt=datetime.now())
--
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: Displaying the names of executed tests

2009-02-02 Thread Alex Koshelev
Look at the `--verbosity` test command option


On Mon, Feb 2, 2009 at 3:16 PM, Julien Phalip  wrote:

>
> Hi,
>
> I'd find quite useful to have the names of all the tests displayed
> after they have been executed. Instead of just having something like
> 'Ran 3 tests 0.672s', it'd be good to have something like 'Ran 3 tests
> 0.672s: test_useraccounts, test_trees, test_blah'.
>
> If that's possible to do, could you please point me out as I can't
> find it in the doc.
>
> If that's not possible, do you think this is worth opening a ticket?
>
> Thanks a lot,
>
> 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
-~--~~~~--~~--~--~---



Re: object_detail 404 (queryset outdated?)

2009-02-02 Thread Carl Meyer

Hi Simon,

On Feb 2, 7:36 am, Simon Westphahl  wrote:
> ###
> class OfferManager(models.Manager):
>     def get_query_set(self):
>         return super(OfferManager, self).get_query_set().exclude
> (start_date__gt=datetime.now).exclude(end_date__lt=datetime.now)
> ###
>
> I'm using a queryset filtered with a callable (datetime.now) which
> appears to be set only once/on load time?!

I think you've got the right idea of what's going wrong, but you're
looking for the problem in the wrong place.  This method isn't module-
level code; it will be executed anew each time you query on this
manager.  More likely is that you're storing a reference to the
returned queryset in module-level code; probably in a dictionary of
kwargs you're passing to the object_detail generic view (most likely
in your urls.py).  It's that queryset that is never getting updated;
the call to your manager method is happening only once, when the
urls.py module is first loaded.

The solution is to wrap the object_detail view with a very lightweight
view of your own that calls the manager method and passes the
resulting queryset in to object_detail.  Then the queryset will be re-
created for each request.

Carl
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 view - merge two tables? (potentially bad db design)

2009-02-02 Thread Carl Meyer

This database design will result in lots of joins, but it's perfectly
normalized and very flexible.  Fine if you expect low traffic and you
need the flexibility.

The other downside is the extra administration complexity, which is
the meat of your question.  Fortunately Django's admin can help you
out, and it's quite easy: look into inlines[1].

Carl

[1] 
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google 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 session

2009-02-02 Thread Karen Tracey
FYI, you have 20+ lines of signature that look like spam to me because they
are mostly in a language I cannot read.  My first reaction to your post was
to wonder how it got through moderation, then I saw you have this short
question buried before the spammish signature:

On Mon, Feb 2, 2009 at 4:35 AM, Harryanto Ie wrote:

> i have some problem using django session, how to create
> session so it can be different user access the site from
> client site? thx


which, I am afraid, I don't understand.  I appreciate that there may be a
language barrier here, but if you would devote some more words and effort to
explaining the problem you are tying to solve, what you have tried and how
it is not working, and get rid of the signature that I fear will make many
entirely dismiss your messages, you may get better responses.

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



Re: UserProfile with django-registration

2009-02-02 Thread Karen Tracey
On Mon, Feb 2, 2009 at 4:33 AM, Praveen wrote:

>
> I am trying to create UserProfile.i am using django-registration.
>
> [snip bunch of code that wraps badly in email, except a key bit]
> regview.py
> --
> def profile_callback(self, user):
> [snip]

   if request.method == 'POST':
>form = form_class(data=request.POST, files=request.FILES)
>if form.is_valid():
>profile_obj = form.save(commit=False)
>profile_obj.user = request.user
>profile_obj.save()
>if hasattr(form, 'save_m2m'):
>form.save_m2m()
>return HttpResponseRedirect(success_url)
>'''else:
>form = form_class()'''
>
[snip]

> when i am running http://127.0.01:8000/profile
>
> error:
> UnboundLocalError at /profile/
>
> local variable 'form' referenced before assignment
>
> Request Method: GET
> Request URL:http://127.0.0.1:8000/profile/
> Exception Type: UnboundLocalError
> Exception Value:
>
> local variable 'form' referenced before assignment
>
> Exception Location: /home/praveen/foodies/../foodies/foodapp/
> regview.py in create_profile, line 127
>
>
Please, if you are going to post that quantity of code, put it on someplace
like dpaste.com and point to it.  It's very hard to follow in email, not to
mention one cannot make use of the line number contained in the error
message.

You seem to have commented out the 'else' leg of the code which sets form to
something in the case where request.method is not POST.  Thus when the code
attempts to reference form later, to put it in the context for rendering the
template, you get the Python error that the variable is being referenced
before being assigned.

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



  1   2   >