Re: SELECT * FROM `student` WHERE mark=(select max(mark) from student)

2010-10-26 Thread Alec Shaner
On Tue, Oct 26, 2010 at 12:40 PM, Phlip  wrote:
>
> So this statement correctly fetches only the latest items:
>
> SELECT a.* FROM things a WHERE a.pid in (select max(b.pid) from
> content_entity b group by b.name)
>
> Now I thought (from my allegedly copious experience with SQL) that I
> could do it with a join-on-self, but I can't seem to get the SQL
> syntax right. And if I did, I would then not know how to ORM-ize that
> syntax (and yes it must be ORM-ized, because this is indeed the core
> of the project, and everything has to see top-level horizons. Except
> auditors).
>

Regarding this query, I think you may be able to do this using
annotate. See http://docs.djangoproject.com/en/dev/topics/db/aggregation/#values

For example (and this probably sucks for performance):

Things.objects.filter(id__in=Things.objects.values('name').annotate(max_id=Max('id')).values_list('max_id',
flat=True))

This is just a self join example, but it could probably be rewritten
to use the two tables in your example.

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



Re: Need help with django url errors

2010-10-17 Thread Alec Shaner
I think nother problem is your polls/urls.py is wrong. The /polls
prefix of the url will be removed by the main urls.py file before
being matched against the included polls/urls.py

http://docs.djangoproject.com/en/1.2/topics/http/urls/#including-other-urlconfs


On Sun, Oct 17, 2010 at 4:52 AM, Daniel Roseman  wrote:
> On Oct 17, 8:36 am, codingJoe  wrote:
>> All,
>>
>> I am working through the django tutorial on the bitnami stack and am
>> having difficulty getting my urls to work properly.  The following
>> references the tutorial part 3 - Poll details.    I suspect the
>> problem may be that the bitnami stack uses apache.  But I have no idea
>> how to configure apache and django to run the tutorial properly.
>>
>> 1.  I enter the following into my browser:  http://192.168.1.6:8080/polls/
>>
>>    Response is a 404 error:
>>
>>    Using the URLconf defined in mysite.urls, Django tried these URL
>> patterns, in this order:
>>       1. ^polls/
>>       2. ^admin/doc/
>>       3. ^admin/
>>    The current URL, , didn't match any of these.
>>
>> Question:  Clearly 'polls' is in both the url and the files below.
>> How do I configure this?
>>
>> begin mysite/urls.py 
>> # Uncomment the next two lines to enable the admin:
>>     4 from django.contrib import admin
>>     5 admin.autodiscover()
>>     6
>>     7 urlpatterns = patterns('',
>>     8       # Example:
>>     9       # (r'^mysite/', include('mysite.foo.urls')),
>>    10       (r'^polls/', include('polls.urls')),
>>    11       (r'^admin/doc/',
>> include('django.contrib.admindocs.urls')),
>>    12       (r'^admin/', include(admin.site.urls)),
>>    13     )
>>
>> end mysite/urls.py 
>>
>> begin mysite/polls/urls.py 
>>  1 from django.conf.urls.defaults import *
>>     2 from django.contrib import admin
>>     3
>>     4 admin.autodiscover()
>>     5
>>     6 urlpatterns = patterns('',
>>     7       (r'^polls/$', 'polls.views.index'),
>>     8       (r'^polls/(?P\d+)/$', 'detail'),
>>     9       (r'^polls/(?P\d+)/results/$', 'results'),
>>    10       (r'^polls/(?P\d+)/vote/$', 'vote'),
>>    11       (r'^admin/doc/',
>> include('django.contrib.admindocs.urls')),
>>    12       (r'^admin/', include(admin.site.urls)),
>>    13     )
>>
>> begin django.conf 
>> # Note:  Tried adding polls to line 3 but that didn't help.
>> 1
>>     2 WSGIScriptAlias /mysite "/Applications/djangostack-1.2.3-0/apps/
>> django/conf/django.wsgi"
>>     3 WSGIScriptAlias /polls "/Applications/djangostack-1.2.3-0/apps/
>> django/conf/django.wsgi"
>>     4
>>     5 
>>     6 Order deny,allow
>>     7 Allow from all
>>     8 
>>
>> end django.conf 
>>
>> begin django.wsgi 
>>  import os, sys
>>     2 sys.path.append('/Applications/djangostack-1.2.3-0/projects')
>>     3 sys.path.append('/Applications/djangostack-1.2.3-0/projects/
>> mysite')
>>     4 os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
>>     5
>>     6 import django.core.handlers.wsgi
>>     7
>>     8 application = django.core.handlers.wsgi.WSGIHandler()
>>
>> end django.wsgi 
>
> You're trying to run before you can walk here. The Django tutorial
> teaches you how to set up urls and views using the built-in
> development server. It's only once you understand those fully that you
> should try and configure it with Apache.
>
> However, the problem you're having is in your Apache configuration
> file. For some reason, you're trying to set up ScriptAliases for each
> URL. Don't do that. Just set up a single one for the root of your
> site:
>
>    WSGIScriptAlias / "/Applications/djangostack-1.2.3-0/apps/django/
> conf/django.wsgi"
>
> That will then pick up all requests and pass them through to Django,
> where they will be routed by urls.py.
> --
> 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-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: F() and timedelta. Bug on django?

2010-10-15 Thread Alec Shaner
doh! Just noticed that you already referenced ticket 10154 in your
original post.

On Fri, Oct 15, 2010 at 3:16 PM, Alec Shaner  wrote:
> Interesting solution - after all that maybe it's more concise to just
> use the 'extra' filter instead since you're making it specific to
> mysql anyway, and you could use mysql date functions.
>
> By the way, in answer to your original question on this thread, there
> already is a ticket to add F() + timedelta.
>
> http://code.djangoproject.com/ticket/10154
>
> On Fri, Oct 15, 2010 at 2:48 PM, Marc Aymerich  wrote:
>>
>>
>> On Fri, Oct 15, 2010 at 7:54 PM, Alec Shaner  wrote:
>>>
>>> On Fri, Oct 15, 2010 at 1:26 PM, Marc Aymerich 
>>> wrote:
>>> >
>>> > Instead of use datatime.timedelta I convert it to string with this
>>> > format:
>>> >  MMDDHHMMSS and now all works fine with mysql :) Unfortunately this
>>> > part
>>> > of code doesn't be database independent :(
>>> >
>>> > Thank you very much alec!
>>> >
>>> > --
>>> > Marc
>>>
>>> No problem.
>>>
>>> So if you don't mind, what does your query filter look like now using
>>> the converted format?
>>>
>>
>> hi :)
>> this is the get_query_set method of my custom Manager:
>> def get_query_set(self):
>>     c=config.get('ignore_bill_period')
>>     #c is a dict like this {u'hours': u'00', u'seconds': u'00', u'minutes':
>> u'00', u'days': u'07'}
>>     ignore_period = c['days']+c['hours']+c['minutes']+c['seconds']
>>     delta_ignore_period = datetime.timedelta(days=int(c['days']),
>>         hours=int(c['hours']), minutes=int(c['minutes']),
>> seconds=int(c['seconds']))
>>     now_sub_ignore = datetime.datetime.now() - delta_ignore_period
>>     #IF db backend is MySQL:
>>     return super(pending_of_billManager,
>> self).get_query_set().filter(Q(cancel_date__isnull=False, \
>>         cancel_date__gt=F('register_date') + ignore_period) |
>> Q(cancel_date__isnull=True, \
>>         register_date__lt=now_sub_ignore))
>>     #ELSE:
>>     #return super(pending_of_billManager,
>> self).get_query_set().filter(Q(cancel_date__isnull=False, \
>>     #    cancel_date__gt=F('register_date') + delta_ignore_period) |
>> Q(cancel_date__isnull=True,
>>     #    register_date__lt=now_sub_ignore))
>> a lot of code for a simple query, but it's the best I can do :)
>> br
>> --
>> Marc
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To post to this group, send email to django-us...@googlegroups.com.
>> To unsubscribe from this group, send email to
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at
>> http://groups.google.com/group/django-users?hl=en.
>>
>

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



Re: F() and timedelta. Bug on django?

2010-10-15 Thread Alec Shaner
Interesting solution - after all that maybe it's more concise to just
use the 'extra' filter instead since you're making it specific to
mysql anyway, and you could use mysql date functions.

By the way, in answer to your original question on this thread, there
already is a ticket to add F() + timedelta.

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

On Fri, Oct 15, 2010 at 2:48 PM, Marc Aymerich  wrote:
>
>
> On Fri, Oct 15, 2010 at 7:54 PM, Alec Shaner  wrote:
>>
>> On Fri, Oct 15, 2010 at 1:26 PM, Marc Aymerich 
>> wrote:
>> >
>> > Instead of use datatime.timedelta I convert it to string with this
>> > format:
>> >  MMDDHHMMSS and now all works fine with mysql :) Unfortunately this
>> > part
>> > of code doesn't be database independent :(
>> >
>> > Thank you very much alec!
>> >
>> > --
>> > Marc
>>
>> No problem.
>>
>> So if you don't mind, what does your query filter look like now using
>> the converted format?
>>
>
> hi :)
> this is the get_query_set method of my custom Manager:
> def get_query_set(self):
>     c=config.get('ignore_bill_period')
>     #c is a dict like this {u'hours': u'00', u'seconds': u'00', u'minutes':
> u'00', u'days': u'07'}
>     ignore_period = c['days']+c['hours']+c['minutes']+c['seconds']
>     delta_ignore_period = datetime.timedelta(days=int(c['days']),
>         hours=int(c['hours']), minutes=int(c['minutes']),
> seconds=int(c['seconds']))
>     now_sub_ignore = datetime.datetime.now() - delta_ignore_period
>     #IF db backend is MySQL:
>     return super(pending_of_billManager,
> self).get_query_set().filter(Q(cancel_date__isnull=False, \
>         cancel_date__gt=F('register_date') + ignore_period) |
> Q(cancel_date__isnull=True, \
>         register_date__lt=now_sub_ignore))
>     #ELSE:
>     #return super(pending_of_billManager,
> self).get_query_set().filter(Q(cancel_date__isnull=False, \
>     #    cancel_date__gt=F('register_date') + delta_ignore_period) |
> Q(cancel_date__isnull=True,
>     #    register_date__lt=now_sub_ignore))
> a lot of code for a simple query, but it's the best I can do :)
> br
> --
> Marc
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

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



Re: F() and timedelta. Bug on django?

2010-10-15 Thread Alec Shaner
On Fri, Oct 15, 2010 at 1:26 PM, Marc Aymerich  wrote:
>
> Instead of use datatime.timedelta I convert it to string with this format:
>  MMDDHHMMSS and now all works fine with mysql :) Unfortunately this part
> of code doesn't be database independent :(
>
> Thank you very much alec!
>
> --
> Marc

No problem.

So if you don't mind, what does your query filter look like now using
the converted format?

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



Re: F() and timedelta. Bug on django?

2010-10-15 Thread Alec Shaner
It should be clarified that this occurs on the mysql backend, but not
the postgres backend. It has to do with how MySQL handles the DATETIME
object. You can't add a timedelta, because it expects a double.

I created a test app using a mysql backend and a Article model with
created and updated datetime fields.

created = 2010-10-15 09:13:02
updated = 2010-10-15 09:18:43

select created - updated from article_article
+---+
| updated - created |
+---+
|541.00 |
+---+

It's using the MMDDHHMMSS format of the datetime fields:

20101015091843 - 20101015091302 = 541

The delta isn't constant either, here are two sets of times that are 5
minutes apart:

created=2010-10-15 09:00:00, updated=2010-10-15 09:05:00
mysql: select created - updated yiels 500

created=2010-10-15:09:59:00, updated=2010-10-15 10:04:00
mysql: select created - updated yields 4500

I haven't looked at the django mysql backend code, but based on this
that warning is fatal in your case because it's definitely not doing
what you want. And I don't see how you could write your query filter
in its current format so that it is postgres/mysql agnostic


On Fri, Oct 15, 2010 at 7:01 AM, Marc Aymerich  wrote:
> This is a fork of this tread:
> http://groups.google.com/group/django-users/browse_thread/thread/5c6beb41fcf961a4
> I'm getting troubles combining instances of F() and timedelta. I'm working
> with the very last trunk revision (14232),
> I create a very simple model for troubleshoting the problem, the model is:
> class dates(models.Model):
>     date1 = models.DateField(auto_now_add=True)
>     date2 = models.DateField()
> And this is what I'm try to do:
 from test.dates.dates import dates
 from django.db.models import F
 import datetime

 dates.objects.filter(date1__gte=F('date2')+datetime.timedelta(minutes=3))
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.6/dist-packages/django/db/models/query.py", line
> 67, in __repr__
>     data = list(self[:REPR_OUTPUT_SIZE + 1])
>   File "/usr/lib/python2.6/dist-packages/django/db/models/query.py", line
> 82, in __len__
>     self._result_cache.extend(list(self._iter))
>   File "/usr/lib/python2.6/dist-packages/django/db/models/query.py", line
> 268, in iterator
>     for row in compiler.results_iter():
>   File "/usr/lib/python2.6/dist-packages/django/db/models/sql/compiler.py",
> line 675, in results_iter
>     for rows in self.execute_sql(MULTI):
>   File "/usr/lib/python2.6/dist-packages/django/db/models/sql/compiler.py",
> line 730, in execute_sql
>     cursor.execute(sql, params)
>   File "/usr/lib/python2.6/dist-packages/django/db/backends/util.py", line
> 18, in execute
>     return self.cursor.execute(sql, params)
>   File "/usr/lib/python2.6/dist-packages/django/db/backends/mysql/base.py",
> line 86, in execute
>     return self.cursor.execute(query, args)
>   File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 168, in
> execute
>     if not self._defer_warnings: self._warning_check()
>   File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 82, in
> _warning_check
>     warn(w[-1], self.Warning, 3)
> Warning: Truncated incorrect DOUBLE value: '0 0:3:0'
>
> On the parent
> thread http://groups.google.com/group/django-users/browse_thread/thread/5c6beb41fcf961a4 Alec
> reports that this works on their django installation.
> More over this pice of django code make use of
> it: http://code.djangoproject.com/attachment/ticket/10154/dateexpressions.diff
> Is this really a bug? it should be reported to django "bug tracker"?
> --
> Marc
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

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



Re: Help with Manager.

2010-10-15 Thread Alec Shaner
Sorry, not sure about that warning because I'm using a postgresql database.

On Fri, Oct 15, 2010 at 3:17 AM, Marc Aymerich  wrote:
>
>
> On Fri, Oct 15, 2010 at 3:39 AM, Alec Shaner  wrote:
>>
>> You can't add a datetime to another datetime - you want to add a
>> datetime.timedelta instance instead. Out of curiosity I just tested it
>> on one of my models and it does work, e.g.,
>>
>> MyModel.objects.filter(update_date__gt=F('entry_date')+timedelta(days=5))
>
>
> Hi Alec, thanks again for your answer :)
> When you executes this filter on a shell you don't get a warning ?
> This is what happens to me:
>>>>
>>>> order.objects.filter(cancel_date__isnull=False).filter(cancel_date__lt=F('register_date')
>>>> + timedelta(days=3))
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.6/dist-packages/django/db/models/query.py", line
> 67, in __repr__
>     data = list(self[:REPR_OUTPUT_SIZE + 1])
>   File "/usr/lib/python2.6/dist-packages/django/db/models/query.py", line
> 82, in __len__
>     self._result_cache.extend(list(self._iter))
>   File "/usr/lib/python2.6/dist-packages/django/db/models/query.py", line
> 268, in iterator
>     for row in compiler.results_iter():
>   File "/usr/lib/python2.6/dist-packages/django/db/models/sql/compiler.py",
> line 672, in results_iter
>     for rows in self.execute_sql(MULTI):
>   File "/usr/lib/python2.6/dist-packages/django/db/models/sql/compiler.py",
> line 727, in execute_sql
>     cursor.execute(sql, params)
>   File "/usr/lib/python2.6/dist-packages/django/db/backends/util.py", line
> 18, in execute
>     return self.cursor.execute(sql, params)
>   File "/usr/lib/python2.6/dist-packages/django/db/backends/mysql/base.py",
> line 86, in execute
>     return self.cursor.execute(query, args)
>   File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 168, in
> execute
>     if not self._defer_warnings: self._warning_check()
>   File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 82, in
> _warning_check
>     warn(w[-1], self.Warning, 3)
> Warning: Truncated incorrect DOUBLE value: '3 0:0:0'
> It's only a warning, but I can't see the output queryset result, maybe it's
> a ""fatal"" warning? you know why this is happening?
> Thanks again!!
>
> --
> Marc
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

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



Re: Help with Manager.

2010-10-14 Thread Alec Shaner
You can't add a datetime to another datetime - you want to add a
datetime.timedelta instance instead. Out of curiosity I just tested it
on one of my models and it does work, e.g.,

MyModel.objects.filter(update_date__gt=F('entry_date')+timedelta(days=5))

On Thu, Oct 14, 2010 at 5:57 PM, Marc Aymerich  wrote:
>
>
> On Thu, Oct 14, 2010 at 10:08 PM, Alec Shaner  wrote:
>>
>> See this:
>>
>> http://ifacethoughts.net/2009/07/14/calculated-fields-in-django/
>>
>> So perhaps the 'extra' query filter is what you need.
>>
>
> Yep, I got a success using extra filter :) Thanks Alec for sharing this!
> by the way, just right now I found the way to reference field on filter and
> operates with it. It can be achieved using instances of F()
>  http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model
> it could be more 'elegant' than using an extra filter, all I need is
> something like that:
> order.objects.filter(Q(cancel_date__isnull=False,
> cancel_date__lt=F('register_date') + Threshold)
> | Q(cancel_date__isnull=True, register_date__gt=Threshold) )
> but i couldn't get working this part: "F('register_date')+Threshold"
> ,(threshold is a datetime.datetime object, and also 'register_date' field.
> Anyone knows the correct way to use instances of F() with date field?
>
> --
> Marc
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

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



Re: Help with Manager.

2010-10-14 Thread Alec Shaner
See this:

http://ifacethoughts.net/2009/07/14/calculated-fields-in-django/

So perhaps the 'extra' query filter is what you need.

2010/10/14 Marc Aymerich :
>
>
> 2010/10/14 Marc Aymerich 
>>
>>
>> 2010/10/14 Jonathan Barratt 
>>>
>>> On 14 ต.ค. 2010, at 22:27, Marc Aymerich wrote:
>>>
>>> Hi,
>>> I'm trying to make a Manager for my model "order". I want that it returns
>>> all orders that their 'active period'* is greater than a certain threshold.
>>> With "active period" I mean: (order.cancel_date - order.register_date )
>>> My Order model looks like this:
>>> class order(models.Model):
>>>     register_date = models.DateTimeField(auto_now_add=True)
>>>     cancel_date = models.DateTimeField(null=True, blank=True)
>>>
>>> I'm wondering if is possible to achieve that using "annotate", something
>>> like that:
>>> (this not work)
>>>
>>> order.objects.annotate(diff=SUB('cancel_date','register_date')).filter(diff__gt=period_threshold)
>>>
>>> or maybe django provides another kind of tool to achieve what i want ?
>>>
>>> Unless I'm misunderstanding what you're looking for, I think this might
>>> suit your needs:
>>> in your model:
>>>
>>> class order(models.Model):
>>>
>>> ...
>>>     def get_active_period(self): return self.cancel_date -
>>> self.register_date active_period = property(get_active_period)
>>> (you may want to add some checking that cancel_date is not null, or that
>>> active_period is not negative but you get the idea)
>>> Then where you need to access that queryset use:
>>> order.objects.filter(active_period__gt=period_threshold)
>>
>> jops ;(, unfortunately the Manager doesn't know what "active_period" is.
>> This is my order model now:
>> class order(models.Model):
>>     [...]
>>     def get_active_period(self):
>>         if self.cancel_date:
>>             return self.cancel_date-self.register_date
>>         else:
>>             return datetime.datetime.now()-self.register_date
>>
>>     active_period = property(get_active_period)
>>     objects = models.Manager()
>>     pending_of_bill = pending_of_billManager()
>>
>> And this is my manager:
>> class pending_of_billManager(models.Manager):
>>     def get_query_set(self):
>>         [...]
>>         return super(pending_of_billManager,
>> self).get_query_set().filter(active_period__gt=threshold)
>> This Works:
>> >>> order.objects.get(pk=1).active_period
>> datetime.timedelta(0, 8347, 24949)
>> but this doesn't:
>> >>> order.pending_of_bill.all()
>> Traceback (most recent call last):
>>   File "", line 1, in 
>>   File "/usr/lib/python2.6/dist-packages/django/db/models/manager.py",
>> line 117, in all
>>     return self.get_query_set()
>>   File "/home/ucp/trunk/ucp/../ucp/order/models.py", line 15, in
>> get_query_set
>>     return super(pending_of_billManager,
>> self).get_query_set().filter(active_period__gt=threshold)
>>   File "/usr/lib/python2.6/dist-packages/django/db/models/query.py", line
>> 549, in filter
>>     return self._filter_or_exclude(False, *args, **kwargs)
>>   File "/usr/lib/python2.6/dist-packages/django/db/models/query.py", line
>> 567, in _filter_or_exclude
>>     clone.query.add_q(Q(*args, **kwargs))
>>   File "/usr/lib/python2.6/dist-packages/django/db/models/sql/query.py",
>> line 1128, in add_q
>>     can_reuse=used_aliases)
>>   File "/usr/lib/python2.6/dist-packages/django/db/models/sql/query.py",
>> line 1026, in add_filter
>>     negate=negate, process_extras=process_extras)
>>   File "/usr/lib/python2.6/dist-packages/django/db/models/sql/query.py",
>> line 1191, in setup_joins
>>     "Choices are: %s" % (name, ", ".join(names)))
>> FieldError: Cannot resolve keyword 'active_period' into field. Choices
>> are: amendment_invoice, amendment_quota, bill, cancel_date, comment,
>> contracted_pack, discount, entity, forward, htacces, htpasswd, id, included,
>> installed_app, mailman, name, order_disk, order_memory, order_swap, ovz,
>> pack, price, register_date, renew, service, size, system_group, system_user,
>> system_user_related, traffic, virtual_aliase, virtual_user,
>> virtual_user_related, virtualhost
>>
>> What I'm missing ?? why super(pending_of_billManager,
>> self).get_query_set() doesn't know about active_period?
>> Thanks!
>
> Seems that we can't use a property as a queryset 'filter', in other words we
> can't use property like this:
>  order.objects.filter(active_time__gt=whatever)
>
>
> --
> Marc
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@g

Re: Rich email with attachments

2010-10-14 Thread Alec Shaner
On Thu, Oct 14, 2010 at 3:45 AM, Sheena  wrote:
> I also want to have the option to add any attachment. So I want to
> have a button that when pressed allows the user to pick a file on
> their hdd and have it uploaded immediately, without loosing anything
> that's already filled in on the email form.

I have implemented this in my project using django-tinymce, swfupload
and jquery. It was definitely one of the hardest features to
implement. If you want to go this route I can tell you one issue I ran
into was flash and cookies. This caused problems with authentication
(my upload service requires auth) and CSRF, but there was a simple fix
I found by googling to add some middleware. Here is one link with some
guidelines:

http://stackoverflow.com/questions/612734/code-samples-for-django-swfupload

I'm not 100% sold on swfupload and I did some research on other flash
based options, but I got so invested in swfupload I didn't have time
to try others.

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



Re: treating different versions of website urls as one

2010-10-05 Thread Alec Shaner
Definitely sounds like a regular expression is what you need.

Not sure what you mean by etcare you saying any variation of a web
address for mysite.com, i.e., with or without www prefix, with our
without protocol http://, and with our without the index page, which
itself could be any variation of index.html, index.php, or
index.whatever?

On Tue, Oct 5, 2010 at 12:17 PM, harryos  wrote:
> hi
> I am trying out a web app where it needs to process user given website
> addresses .My problem is that ,I need to treat
>  http://mysite.com ,
> www.mysite.com,
> mysite.com,
> www.mysite.com/index.html,
> www.mysite.com/index.php ...etc as the same and not different urls.How
> can I do the validation in this case?Do I have to manually do the
> string parsing and validate?
> Any suggestions most welcome
> thanks
> harry
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Why Django Admin Won't Display full graphics

2010-09-30 Thread Alec Shaner
Also, if you're using mod_wsgi (recommended over mod_python), see this:

http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango


On Thu, Sep 30, 2010 at 12:12 PM, Addy Yeow  wrote:
> runserver takes care of thing like this for you but you need to handle
> it properly in Apache.
> See 
> http://docs.djangoproject.com/en/dev/howto/deployment/modpython/#serving-the-admin-files
>
> On Fri, Oct 1, 2010 at 12:03 AM, octopusgrabbus
>  wrote:
>>
>> When I run Django admin with runserver running, I get nice graphics. I
>> don't when I run Django admin from apache. I can log into my django
>> application from apache, but do not get the graphics. I'm looking for
>> examples or documentation on how to fix this.
>>
>> Thanks.
>> cmn
>>
>> --
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To post to this group, send email to django-us...@googlegroups.com.
>> To unsubscribe from this group, send email to 
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at 
>> http://groups.google.com/group/django-users?hl=en.
>>
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Bug in model inheritance?

2010-09-28 Thread Alec Shaner
As to whether it's a bug or not I have no idea, though it seems so.

If you use:

entity = models.OneToOneField(Entity, parent_link=True, primary_key=True)

it will create the primary key in both Kid and Adult tables, which
sounds like what you want?

On Tue, Sep 28, 2010 at 1:06 PM, phill  wrote:
> This looks quite a bit like a bug, but we may be off the reservation
> in terms of how we're using the product. (Disclaimer: I'm relatively
> new to Django, and extremely new to the codebase that I ran into this
> on).
>
> We've got a form of schema-inheritance going on in this project in
> order to accomplish shared-id-space and the ability to relate models
> to one of a number of different types. The way that we've broken it
> out runs us into a strange inconsistency in Django that specifically
> affects our ability to serialize the objects. Here's a simplified
> version of what we're doing:
>
> class Entity(models.Model):
>    entityType = models.CharField(editable=False,max_length=50)
>
>    def __init__(self, *args, **kwargs):
>        super(Entity, self).__init__(*args, **kwargs)
>        self.entityType = self.__class__.__name__
>
>    def __unicode__(self):
>        return 'Entity: %s %s' %(self.entityType, self.id)
>
> class BasePerson(Entity):
>
>    entity = models.OneToOneField(Entity, parent_link=True)
>    name = models.CharField(max_length=50)
>
>    class Meta:
>        abstract = True
>
> class Kid(BasePerson):
>    school = models.CharField(max_length=50)
>
> class Adult(BasePerson):
>    job = models.CharField(max_length=50)
>
>
>
> When I dump instances of these models out using the standard fixtures
> serialization, instances of Kid will serialize the 'entity' field, but
> instances of Adult won't. The reason is because Adult's entity field
> is marked primaryKey=True. Kid's is not. There appears to be a caching
> issue here, because if I swap the order that Kid and Adult are defined
> in.. the error reverses (now Kid's field will be marked pk).
>
> Is this a bug? If not, what's the reasoning behind this behavior? Is
> there a better pattern for accomplishing this kind of inheritance?
>
> Thanks in advance for your help.
>
> Phill
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Querying Exact Foreign Key Sets

2010-09-15 Thread Alec Shaner
Try this:

I'm assuming you define Article.category as a ManyToMany field? I also
assumed for the example that Category has a name field.

# Build a queryset of all categories not in desired set, e.g., 'Exact1' and
'Exact2'
bad_categories = Category.objects.exclude(category_name__in=['Exact1',
'Exact2'])
# Filter your exact categories, then exclude the bad ones
Article.objects.filter(category__name='Exact1').filter(category__name='Exact2').exclude(category__in=bad_categories)


On Tue, Sep 14, 2010 at 5:58 PM, Jason  wrote:

> Say for example you have two models:
>
> Article
> Category
>
>
> Articles can have multiple categories.
>
> How would you go about finding the Articles that contain only a
> certain set of Categories?
>
> The 'in' operator doesn't do me any good. Excludes look like they are
> needed...
>
>
> I'm in a situation where quickly sorting by SETS of categories is
> needed and I'm having a tough time. My database programming skills are
> pretty weak.
>
> I'm thinking of making an intermediate model called CategorySets.
>
> Articles would then have a relationship to a CategorySet and I can
> sort very easily on this.
>
>
> (note my actual project isn't using Articles but it's quicker to
> explain in these terms).
>
> Does anyone have any tips or experience here?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: db filter comparing a minimum to a range

2010-09-13 Thread Alec Shaner
Maybe this is what you want:

http://docs.djangoproject.com/en/1.2/topics/db/aggregation/#filtering-on-annotations

On Mon, Sep 13, 2010 at 3:32 PM, Phlip  wrote:

> Djangoids:
>
> Consider this QuerySet:
>
>   Blog.objects.filter(comment__date__range=(self.yesterday,
> self.tomorrow))
>
> It returns all the blogs with any comment (as a side note, it seems to
> return each blog redundantly, to allow the SELECT to differ each
> returned row by comment).
>
> I need every Blog whose first comment appears in the date range:
>
> SELECT * FROM blog
>  INNER JOIN comment ON comment.blog_id = blog.id
> WHERE MIN(comment.date) BETWEEN '2010-09-12' AND '2010-09-14'
> GROUP BY(blog.id)
>
> Can I get that without dropping to raw SQL?
>
> --
>  Phlip
>  http://zeekland.zeroplayer.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-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Please wait page trouble

2010-09-10 Thread Alec Shaner
Excellent. Glad you got it working.

On Fri, Sep 10, 2010 at 8:54 AM, Bradley Hintze  wrote:

> I got to work! I needed a good nights sleep to see it. the url was
> '/DHM_run/' NOT '/run_DHM/'.
>
> Thanks 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-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Please wait page trouble

2010-09-09 Thread Alec Shaner
A lot of ways to do this. Yes you could do it as above, but that can get
ugly as you start adding more views. You can indeed access the context
dictionary in please_wait.html. It's hard to say without knowing more
details about your application. How does the user pass arguments (if any)
used in these calculations? If you're looking for a simple way to abstract
this process, consider using URL confs:

# Create a url specific to the DHM calulcation
url(r'^DHM_run_start/$', please_wait, kwargs={'calculation_url': 'run_DHM'},
name='run_DHM_start'),

and you'd call it like /DHM_run_start/

or

# Create a URL with a regex pattern to capture a calculation_url
url(r'^please_wait/(?P[\d\w]+)/$', please_wait),

and you'd call it like /please_wait/run_DHM/

The second option is more generic, but you'll need to validate the url
argument. The first option means adding more url entries. In either case
your please_wait view would be defined like:

def please_wait(request, calculation_url):
return render_to_response('please_wait.html', {'calculation_url':
calculation_url}, ...)

please_wait.html could then substitute the {{ calculation_url }} context
variable as the argument to the {% url %} tag.

Your run_DHM view could now return the url to redirect to instead of just
'OK'. You'll have to return the full URL, e.g., '/display_DHM/', from your
run_DHM view. This is probably where you'd start thinking about a JSON
response as you might return a dictionary with an result code ('OK' or
'error') along with a url to redirect the user to.

window.location.href = data;

Or if you've switched to a JSON response it might be data.display_url after
checking that data.result = 'OK'.

Hope that all makes sense.

On Thu, Sep 9, 2010 at 12:00 PM, Bradley Hintze  wrote:

> OK,
>
> Got it working. Sorry one more question. I have a couple of places
> where I'd like to display the 'Please Wait' page. I'd imagine I'd do
> something similar to the following::
>
> # please_wait.html
> ...
>  src="<a  rel="nofollow" href="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js</a>
> ">
> 
> if (If_come_from_pageA) {
> $.get('{% url run_DHM %}', function(data) {
>if (data == 'OK') {
>  window.location.href = '{% url display_DHM %}';
>} else {
>  alert(data);
>}
>}
> else if (If_come_from_pageB) {
>$.get('{% url run_analysis %}', function(data) {
>if (data == 'OK') {
>  window.location.href = '{% url display_analysis %}';
>} else {
>  alert(data);
>}
>}
>});
> 
>
> an of course configure url.py and view.py as explained previously. Is
> there an easy way to do this? In other words, what are the
> If_come_from_pageA and If_come_from_pageB conditions? Can I access the
> context dictionary that I passed to please_wait.html?
>
> On Thu, Sep 9, 2010 at 11:23 AM, Bradley Hintze
>  wrote:
> > Yeah, I just tried out what I wrote in my last and it worked!
> >
> > Thanks for all your help!!!
> >
> > Bradley
> >
> > On Thu, Sep 9, 2010 at 11:17 AM, Alec Shaner 
> wrote:
> >> That's really a design issue up to you, i.e., how you get data from your
> >> view to your template. Since I don't know the format or how much data
> you're
> >> storing in the session it's hard to say. I was just assuming you'd use
> >> context variable(s) to pass the data to the template. I'm not intimately
> >> familiar with the Session API, but isn't it just a dictionary?
> >>
> >> On Thu, Sep 9, 2010 at 11:05 AM, Bradley Hintze
> >>  wrote:
> >>>
> >>> Thanks Alec,
> >>>
> >>> That finally makes sense. However, I do have a question here:
> >>>
> >>> def display_DHM(request):
> >>># Get results from session
> >>>return render_to_response('ran_DHM.html', ...)
> >>>
> >>> '# Get results from session' Would I not just do this:
> >>>
> >>> def display_DHM(request):
> >>>return render_to_response('DHM_ran.html', request.session, ...)
> >>>
> >>> Or do I have to explicitly get the session data? If so, how?
> >>>
> >>>
> >>> On Thu, Sep 9, 201

Re: Please wait page trouble

2010-09-09 Thread Alec Shaner
That's really a design issue up to you, i.e., how you get data from your
view to your template. Since I don't know the format or how much data you're
storing in the session it's hard to say. I was just assuming you'd use
context variable(s) to pass the data to the template. I'm not intimately
familiar with the Session API, but isn't it just a dictionary?

On Thu, Sep 9, 2010 at 11:05 AM, Bradley Hintze  wrote:

> Thanks Alec,
>
> That finally makes sense. However, I do have a question here:
>
> def display_DHM(request):
># Get results from session
>return render_to_response('ran_DHM.html', ...)
>
> '# Get results from session' Would I not just do this:
>
> def display_DHM(request):
>return render_to_response('DHM_ran.html', request.session, ...)
>
> Or do I have to explicitly get the session data? If so, how?
>
>
> On Thu, Sep 9, 2010 at 10:37 AM, Alec Shaner 
> wrote:
> > I feel your pain - javascript has always been a pain for me, but
> libraries
> > like jQuery make it more bearable!
> >
> > AJAX calls are made in the background (usually asynchronously), so they
> > don't directly change the page you're currently viewing in your browser.
> The
> > browser is responsible for dispatching the response returned from your
> AJAX
> > call, typically by invoking a callback function you specified when the
> AJAX
> > request was initiated. So you don't do a redirect from the server, rather
> > you can do it using client side javascript in your callback function.
> >
> > Here is how it basically works:
> > 1. Please Wait page makes AJAX request to run_DHM, specifies callback
> > function when request completes.
> > 2. run_DHM performs calculations, stores results in session, returns an
> "OK"
> > response.
> > 3. Browser invokes the callback function specified in step 1, which
> should
> > change the page to display_DHM view.
> > 4. display_DHM retrieves calculation results from session and renders
> HTML
> > page.
> >
> > Your first problem is with the url template tag. You might try this:
> >
> > {% url MolProbity_Compare_test.views.run_DHM %}
> >
> > You can also use a named urls, e.g.,
> > ...
> > url(r'^DHM_run/$', run_DHM, name="run_DHM"),
> > ...
> > in which case {% url run_DHM %} should also work
> >
> > Or you can just call the url directly instead of using the url template
> tag,
> > e.g., '/run_DHM/'.
> >
> > The request argument is always passed to your views, you don't have to do
> it
> > explicitly. So your run_DHM and display_DHM views will always have that
> > available. Just get the session out of the request object in each view
> you
> > need it.
> >
> > Basic skeleton:
> >
> > # please_wait.html
> > ...
> >  > src="<a  rel="nofollow" href="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js</a>
> ">
> > 
> > $.get('{% url run_DHM %}', function(data) {
> > if (data == 'OK') {
> >   window.location.href = '{% url display_DHM %}';
> > } else {
> >   alert(data);
> > }
> > });
> > 
> >
> > Note I've used the shorthand urls above, you could just use '/run_DHM/'
> and
> > '/display_DHM/' instead of the url template tags. You could also use the
> > full package path. Also note that the callback function I refer to is
> > defined inline - the function(data) ... part.
> >
> > # views.py
> > from django.http import HttpResponse
> >
> > def please_wait(request):
> > return render_to_response('please_wait.html', ...)
> >
> > def run_DHM(request):
> > # Do calculations, store results in request.session
> > ...
> > # If everything ok, return OK (otherwise return some error)
> > return HttpResponse('OK')
> >
> > def display_DHM(request):
> > # Get results from session
> > return render_to_response('ran_DHM.html', ...)
> >
> > This is over simplified, but should serve to get started if you want to
> use
> > this redirect approach.
> >
> > On Thu, Sep 9, 2010 at 9:59 AM, Bradley Hintze <
> bradle...@aggiemail.usu.edu>
> > wrote:
> >>
> >> Alec,
> >>
> >> Thanks for your patie

Re: Please wait page trouble

2010-09-09 Thread Alec Shaner
I feel your pain - javascript has always been a pain for me, but libraries
like jQuery make it more bearable!

AJAX calls are made in the background (usually asynchronously), so they
don't directly change the page you're currently viewing in your browser. The
browser is responsible for dispatching the response returned from your AJAX
call, typically by invoking a callback function you specified when the AJAX
request was initiated. So you don't do a redirect from the server, rather
you can do it using client side javascript in your callback function.

Here is how it basically works:
1. Please Wait page makes AJAX request to run_DHM, specifies callback
function when request completes.
2. run_DHM performs calculations, stores results in session, returns an "OK"
response.
3. Browser invokes the callback function specified in step 1, which should
change the page to display_DHM view.
4. display_DHM retrieves calculation results from session and renders HTML
page.

Your first problem is with the url template tag. You might try this:

{% url MolProbity_Compare_test.views.run_DHM %}

You can also use a named urls, e.g.,
...
url(r'^DHM_run/$', run_DHM, name="run_DHM"),
...
in which case {% url run_DHM %} should also work

Or you can just call the url directly instead of using the url template tag,
e.g., '/run_DHM/'.

The request argument is always passed to your views, you don't have to do it
explicitly. So your run_DHM and display_DHM views will always have that
available. Just get the session out of the request object in each view you
need it.

Basic skeleton:

# please_wait.html
...
http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"</a>;>

$.get('{% url run_DHM %}', function(data) {
if (data == 'OK') {
  window.location.href = '{% url display_DHM %}';
} else {
  alert(data);
}
});


Note I've used the shorthand urls above, you could just use '/run_DHM/' and
'/display_DHM/' instead of the url template tags. You could also use the
full package path. Also note that the callback function I refer to is
defined inline - the function(data) ... part.

# views.py
from django.http import HttpResponse

def please_wait(request):
return render_to_response('please_wait.html', ...)

def run_DHM(request):
# Do calculations, store results in request.session
...
# If everything ok, return OK (otherwise return some error)
return HttpResponse('OK')

def display_DHM(request):
# Get results from session
return render_to_response('ran_DHM.html', ...)

This is over simplified, but should serve to get started if you want to use
this redirect approach.

On Thu, Sep 9, 2010 at 9:59 AM, Bradley Hintze
wrote:

> Alec,
>
> Thanks for your patience. The jquery tutorials have been frustrating.
> Anyway, I do not have three 'views' as you suggested. I will try that.
> But I need to understand a few things before I try that. How to call
> run_DHM from my please_wait.html page. (I assume AJAX but I've tried
> and tries what have been suggested with no success, most likely due to
> my failed attempts at understanding AJAX) I assume after I run the
> run_DHM view function I will somehow have run_DHM redirect it to the
> display_DHM. My question is, how do I redirect AND pass the
> request.session arguments, which is where the data from run_DHM will
> be stored?
>
> As requested, here is my full url.py:
>
> from django.conf.urls.defaults import *
> from MolProbity_Compare_test.views import *
>
> # Uncomment the next two lines to enable the admin:
> # from django.contrib import admin
> # admin.autodiscover()
>
> urlpatterns = patterns('',
>(r'^home/$', home_view),#the 'index' or home or top page view
>(r'^about/$', about_view),
>(r'^log_out_confirm/$', log_out_confirm),
>(r'^log_out/$', log_out),
>(r'^upload/$', uploaded_PDBs),
>(r'^rotamer_diff/$', rotamer_dif_frame),
>(r'^side-by-side/$', side_by_side),
>(r'^side-by-side-key/$', side_by_side_key),
>(r'^side-by-side-frame/$', side_by_side_frame),
> (r'^DHM_run/$', run_DHM),
>(r'^please_wait/', please_wait),
> (r'^analyze/$', analyze_compare),
> )
>
>
> On Thu, Sep 9, 2010 at 9:22 AM, Alec Shaner  wrote:
> > Could you post the full url.py file?
> >
>
...

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



Re: Please wait page trouble

2010-09-09 Thread Alec Shaner
Could you post the full url.py file?

And as Brian mentioned your javascript block should be separated. Plus you
have an extra }); that's going to fail once you resolve this reverse error.
It's also not clear what you intend to happen when run_DHM returns its
response? It looks like your intent is to do a redirect and run_DHM will use
session data to retrieve calculation results.

Just to clarify, I think your plan is to:

1. Display a Please Wait page that fires off an AJAX call to some view that
performs calculations => run_DHM. The results of the calculations are stored
in the session.
2. run_DHM returns a simple response that will indicate sucess, e.g., "OK"
3. Redirect to a view to display the results, which are retrieved from the
session => display_DHM

I think you need three views here: please_wait, run_DHM, and display_DHM.

On Thu, Sep 9, 2010 at 8:45 AM, Bradley Hintze
wrote:

> #url.py
> ...
>(r'^please_wait/', please_wait),
>(r'^DHM_run/$', run_DHM),
> ...
>
> #please_wait.html
>
>  src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js";>
> $.getJSON('{% url run_DHM %}')
> });
> 
>
> #view.py
> def please_wait(request):
>c = {'we_r_home':'yes'}
>return render_to_response('please_wait.html', c)
>
> def run_DHM(request):
> //put calculated data in request.session
>return render_to_response('DHM_ran.html', request.session,
> context_instance=RequestContext(request))
>
>
> This is the django error
>
> Caught NoReverseMatch while rendering: Reverse for 'run_DHM' with
> arguments '()' and keyword arguments '{}' not found.
>
> run_DHM takes 'request' as an argument. How do I pass it the argument??
>
> Bradley
>
> On Wed, Sep 8, 2010 at 9:34 PM, Brian Neal  wrote:
> > On Sep 8, 5:56 pm, Bradley Hintze  wrote:
> >> This is what I have in my please_wait.html
> >>
> >>  >> src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js";>
> >> $.getJSON('{% url run_DHM %}')});
> >>
> >> 
> >
> > I don't think that is right, is it? At least I've never seen it done
> > that way. I think you need two script tags:
> >
> > http://ajax.googleapis.com/ajax/
> > libs/jquery/1.4/jquery.min.js">
> > 
> >   // Your javascript goes here...
> > 
> >
> >>
> >> This is the django error
> >>
> >> Caught NoReverseMatch while rendering: Reverse for 'run_DHM' with
> >> arguments '()' and keyword arguments '{}' not found.
> >>
> >> run_DHM takes 'request' as an argument. How do I pass it the argument??
> >>
> >
> > All views take request as a first argument. But that isn't the
> > problem. Please post your urls.py that has your run_DHM view in it.
> >
> > Regards,
> > BN
> >
> > --
> > You received this message because you are subscribed to the Google Groups
> "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> > For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
> >
> >
>
>
>
> --
> Bradley J. Hintze
> Graduate Student
> Duke University
> School of Medicine
> 801-712-8799
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Please wait page trouble

2010-09-07 Thread Alec Shaner
You need to include the jquery library script in your html page if you're
calling getJSON as in the previous emails (and note that getJSON isn't
necessarily the function you want - jquery provides many options for doing
AJAX). Either download it, or use one of the public repositories:

http://docs.jquery.com/Downloading_jQuery#CDN_Hosted_jQuery

In fact, just view the html source code for the link just referenced -
you'll see how jquery is included:

http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js</a>
<view-source:<a  rel="nofollow" href="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js</a>>">

Then I'd recommend one of the tutorials, e.g.,:

http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

The tutorials should serve as live examples.

On Tue, Sep 7, 2010 at 10:31 AM, Bradley Hintze  wrote:

> It seems as if this is the only solution but after a week of trying to
> implement it in a variety of ways it won't work. is there something I
> need to download (jquery)? More helpful would be a real HTML page as
> an example or a live example on the web. I am sorry for the trouble
> but I'd like to understand this and get it working.
>
> On Tue, Aug 31, 2010 at 7:37 PM, Alec Shaner 
> wrote:
> > $.getJSON should be embedded in your initial Page Wait response page. The
> > first argument isn't a view, rather a URL. So you might want to use the
> > django url template tag, e.g.,
> > $.getJSON('{% url whatever.run_DHM %}', ...)
> > The second argument is a callback function. The browser stores the
> callback
> > and subsequently calls it when the url requested returns a response. It
> also
> > might be confusing because the function is defined inline (anonymous),
> which
> > is a frequent shortcut used in javascript. But anyway, when the callback
> > function executes he just put console.log(result.data) as way to see what
> > gets returned.
> >  You say you want to send the user to another page with the results, but
> you
> > could return a rendered chunk of html code and replace the Please Wait
> > message using jquery to mainupulate the DOM (jquery documentation has
> > tutorials). Or if you want to redirect to a new page you could store the
> > calculation results in the session and redirect to a view that pulls from
> > that same session data (or use memcached). So maybe instead of
> > console.log(result.data), you could
> > use window.location="/some/url/to/show/calculations/";
> > His example returns a HttpResponse just to illustrate the concept of how
> to
> > return JSON data. You don't have to return JSON, but it's a good method
> if
> > you want to return structured data. In the above example of a redirect
> you
> > could just return anything I suppose, i.e., just an 'OK'.
> >
> > On Tue, Aug 31, 2010 at 5:11 PM, Bradley Hintze
> >  wrote:
> >>
> >> Ok, I'll try to elaborate. again java is foreign to me although I've
> >> spent all day trying to learn some.
> >>  Here's the code:
> >>
> >> def please_wait(request):
> >>   # ... setup context or something
> >>   return render_to_response("please_wait.html")
> >>
> >> def run_DHM(request)
> >>   # ... perform calculations and collect the result in a dict
> >>   data = {"result": something}
> >>   return HttpResponse(json.dumps(data), mimetype="application/json")
> >>
> >>
> >> # using jquery in your html
> >> 
> >> $.getJSON("/run_DHM/", function(data) {
> >>   // do something with result
> >>   console.log(data.result);
> >> });
> >> 
> >>
> >> def run_DHM(request) is straight forward then it falls apart.
> >>
> >> $.getJSON("/run_DHM/", function(data) {
> >>   // do something with result
> >>   console.log(data.result);
> >> });
> >>
> >> I presume that '$.getJSON("/run_DHM/", function(data)' somehow runs
> >> the run_DHM function? How can it even find the function since it lives
> >> in view.py? '// do something with result' I want to send another
> >> page to the client with the results but do I do this here? If not,
> >> what do I do here? What does 'console.log(data.result);' do? Why does
> >> def run_DHM(request) return a HttpResponse? I have a template I want
> >> it to return so shouldn't I use

Re: Discrepancy between model formset and the queryset it's based on

2010-09-01 Thread Alec Shaner
Perhaps see:

http://docs.djangoproject.com/en/1.2/topics/forms/formsets/

where it talks about the "extra" keyword that controls how many blank forms
to add, the default is 1


On Wed, Sep 1, 2010 at 5:31 PM, ses1984  wrote:

> Basically I have a queryset with N items in it, which I use to create
> a model formset, which then has N+1 items in it. I'm not sure why this
> is happening.
>
> Here is a summary of the problem. Please forgive my crude methods for
> gathering information (if anyone has feedback on that topic, I would
> like to hear it)
>
> http://dpaste.com/hold/237587/
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Please wait page trouble

2010-08-31 Thread Alec Shaner
$.getJSON should be embedded in your initial Page Wait response page. The
first argument isn't a view, rather a URL. So you might want to use the
django url template tag, e.g.,

$.getJSON('{% url whatever.run_DHM %}', ...)

The second argument is a callback function. The browser stores the callback
and subsequently calls it when the url requested returns a response. It also
might be confusing because the function is defined inline (anonymous), which
is a frequent shortcut used in javascript. But anyway, when the callback
function executes he just put console.log(result.data) as way to see what
gets returned.

 You say you want to send the user to another page with the results, but you
could return a rendered chunk of html code and replace the Please Wait
message using jquery to mainupulate the DOM (jquery documentation has
tutorials). Or if you want to redirect to a new page you could store the
calculation results in the session and redirect to a view that pulls from
that same session data (or use memcached). So maybe instead of
console.log(result.data), you could use
window.location="/some/url/to/show/calculations/";

His example returns a HttpResponse just to illustrate the concept of how to
return JSON data. You don't have to return JSON, but it's a good method if
you want to return structured data. In the above example of a redirect you
could just return anything I suppose, i.e., just an 'OK'.

On Tue, Aug 31, 2010 at 5:11 PM, Bradley Hintze  wrote:

> Ok, I'll try to elaborate. again java is foreign to me although I've
> spent all day trying to learn some.
>  Here's the code:
>
> def please_wait(request):
>   # ... setup context or something
>   return render_to_response("please_wait.html")
>
> def run_DHM(request)
>   # ... perform calculations and collect the result in a dict
>   data = {"result": something}
>   return HttpResponse(json.dumps(data), mimetype="application/json")
>
>
> # using jquery in your html
> 
> $.getJSON("/run_DHM/", function(data) {
>   // do something with result
>   console.log(data.result);
> });
> 
>
> def run_DHM(request) is straight forward then it falls apart.
>
> $.getJSON("/run_DHM/", function(data) {
>   // do something with result
>   console.log(data.result);
> });
>
> I presume that '$.getJSON("/run_DHM/", function(data)' somehow runs
> the run_DHM function? How can it even find the function since it lives
> in view.py? '// do something with result' I want to send another
> page to the client with the results but do I do this here? If not,
> what do I do here? What does 'console.log(data.result);' do? Why does
> def run_DHM(request) return a HttpResponse? I have a template I want
> it to return so shouldn't I use render_to_response? Obviously, I am
> not getting how the javascript works so I have no idea how to set this
> up. I was hoping there was a pythonic solution :).
>
> I hope this explains my utter confusion sufficiently.
>
> Bradley
>
>
>

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



Re: Please wait page trouble

2010-08-31 Thread Alec Shaner
Rolando's suggestion is a pretty straight forward method to achieve what you
want. You probably need to elaborate where in the process you're having
trouble (although based on your response maybe it's the first step?). You
can indeed call a view.my function from your please wait template, but you
want to do it in the background, i.e., with an AJAX request in order to keep
the Please Wait message displayed while your server processes the request.

On Tue, Aug 31, 2010 at 2:46 PM, Bradley Hintze  wrote:

> I'm getting no where with this, are there any other suggestions on row
> to render a 'please wait' page while other python works? Can I call a
> view.my function to run from my 'please wait' template?
>
> Please be as elementary as possible as javascript, AJAX, jquery, and
> the like are brand new to me.
>
> Thanks,
> Bradley
>
> On Tue, Aug 31, 2010 at 10:38 AM, Bradley Hintze
>  wrote:
> > I'll look into this. I have no idea what you mean by 'ajax' or 'json'.
> > Thus your code doe'snt really make sense given my lack of knowlege. I
> > will do some googling to see if I can piece it together. Thanks for
> > the help!
> >
> > On Mon, Aug 30, 2010 at 10:37 PM, Rolando Espinoza La Fuente
> >  wrote:
> >> On Mon, Aug 30, 2010 at 7:18 PM, Bradley Hintze
> >>  wrote:
> >>> I am attempting to do a lengthe calculation that will require the user
> >>> to wait a bit. I want a 'Please wait page to come up while the lengthy
> >>> calculation is performed. I thought this might work:
> >>>
> >>> views.py
> >>>
> >>> def please_wait(request):
> >>>return HttpResponse('Please Wait..')
> >>>
> >>> def run_DHM(request):
> >>>please_wait(request)
> >>>lengthy calculations...
> >>>
> >>> This did not show the 'Please Wait' page. Is there a better way to do
> >>> what I am trying to do?
> >>>
> >>
> >> You are not returning the HttpResponse object from please_wait(). But
> anyway,
> >> doesn't work that way. At least with django.
> >>
> >> What you can do is render a normal html with the message "Please wait",
> >> then perform an ajax call to start the calculations and finally return
> >> a json response
> >> to display the result in the client-side.
> >>
> >> Roughly:
> >>
> >> def please_wait(request):
> >># ... setup context or something
> >>return render_to_response("please_wait.html")
> >>
> >> def run_DHM(request)
> >># ... perform calculations and collect the result in a dict
> >>data = {"result": something}
> >>return HttpResponse(json.dumps(data), mimetype="application/json")
> >>
> >>
> >> # using jquery in your html
> >> 
> >> $.getJSON("/run_DHM/", function(data) {
> >>// do something with result
> >>console.log(data.result);
> >> });
> >> 
> >>
> >>
> >> Rolando Espinoza La fuente
> >> www.insophia.com
> >>
> >>> --
> >>> Bradley J. Hintze
> >>> Graduate Student
> >>> Duke University
> >>> School of Medicine
> >>> 801-712-8799
> >>>
> >>> --
> >>> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> >>> To post to this group, send email to django-us...@googlegroups.com.
> >>> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> >>> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
> >>>
> >>>
> >>
> >> --
> >> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> >> To post to this group, send email to django-us...@googlegroups.com.
> >> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> >> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
> >>
> >>
> >
> >
> >
> > --
> > Bradley J. Hintze
> > Graduate Student
> > Duke University
> > School of Medicine
> > 801-712-8799
> >
>
>
>
> --
> Bradley J. Hintze
> Graduate Student
> Duke University
> School of Medicine
> 801-712-8799
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Finding current view url in template?

2010-08-24 Thread Alec Shaner
You could set a context variable, e.g., listing_operation = 'Edit' or
'Create'. Or you could use different templates, each inheriting a common
template and only doing minor tweaks.

On Tue, Aug 24, 2010 at 9:04 AM, reduxdj  wrote:

> I have some decisions i need to make in my template based on the view
> that has been rendered in the browser.
>
> For instance:
>
> I need to know if the user is on gather.view.create_listing or
> gather.view.edit_listing?
>
> How can I do this in django, it alludes me.
>
> Thanks,
> Patrick
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: flatpages and menu

2010-08-24 Thread Alec Shaner
You could use a context processor to read the flatpage table to build the
menu. If you want more control over the menu then create a Menu model and
store the flatpage links there and again build the menu in a context
processor. You would probably want to use some level of caching if you don't
want to hit the database for every page view.

On Tue, Aug 24, 2010 at 3:00 AM, OliverMarchand
wrote:

> Dear all,
>
> I am thinking of creating a website that displays "mostly" database
> content, but for special content I am using flatpages. Now somehow I
> must put a link to the flatpages somewhere, most likely in a menu. If
> I put the menu in my base template, then there is no way to insert
> this link by editing.
>
> Do you have a good design idea to make the menu editable as well?
>
> thanks and cheers,
> Oliver
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: select statements with specific fields across multiple tables...

2010-08-16 Thread Alec Shaner
1. What is your code for doing the filters?  If you want to start with
physical drives it would be something like:

RaidPhysicalDrive.objects.filter(in_array__in_storage__in_system__id=)

2. In your template you've referenced pd.in_array_id, but don't you just
want pd.in_array if you're wanting to follow the FK to get RaidArray fields,
e.g.,

{{ 
pd.in_array.in_storage.in_system.name}}


On Mon, Aug 16, 2010 at 8:04 PM, Cindy  wrote:

> I'm having some trouble constructing a filter that's intended to work
> across multiple tables with selected fields.  Here's a simplified
> outline of my models:
>
> class System(models.Model):
>name = models.CharField(max_length=16)
>domain = models.CharField(max_length=255, default='example.com')
>
> class RaidStorage(models.Model):
>in_system = models.ForeignKey(System)
>name = models.CharField(max_length=25)
>
> class RaidArray(models.Model):
>in_storage = models.ForeignKey(RaidStorage)
>name = models.CharField(max_length=25)
>
> class RaidPhysicalDrive(models.Model):
>in_array = models.ForeignKey(RaidArray)
>name = models.CharField(max_length=25)
>size = models.IntegerField(null=True, blank=True)
>serial = models.CharField(max_length=25)
>model = models.CharField(max_length=25)
>
> Now, given a system id, I want to list all the physical drives from it
> along with info from the related tables.  I would like something like
>
> select System.name, RaidStorage.name, RaidArray.name,
> RaidPhysicalDrive.name, RaidPhysicalDrive.serial,
> RaidPhysicalDrive.model from System, RaidStorage, RaidArray,
> RaidPhysicalDrive where RaidPhysicalDrive.in_array=RaidAarray.id and
> RaidArray.in_storaage = RaidStorage.id and RaidStorage.in_system=id
> (etc)
>
> I'm having a good deal of trouble coming up with the filters for
> this.  I'm thinking that .values() and possibly .select_related() are
> key here, but so far I've failed at putting together anything that
> gives me the results I want (a list of physical drives associated with
> the selected system).   The filter examples through the tutorials and
> such seem to all assume select *, and there's very little on dealing
> with grouping selective fields from multiple tables that I've found.
>
> Part of the issue might be in the template as well; If I cheat and
> send it the correct list, I can't access part of the information I
> want:
>
> {% for pd in pd_list %}
> 
>{{ pd.in_array_id.storage.in_system.name }}
>{{ pd.in_array_id.in_storage.name }}
>{{ pd.in_array_id.name }}
>{{ pd.name }}
>{{ pd.serial }}
>{{ pd.model }}
> 
> {% endfor %}
>
> results in the first three columns of the table being empty...
> templates don't seem to "follow" back the way they do in views.py,
> etc.  So I'm sure I need to create a dictionary or list from the
> original views.py def to pass to the template but as I say, I'm not
> sure of how to use .values or .select_related (or whatever else item
> I'm overlooking).
>
> I did search through the group a bit, but didn't find anything
> directly helpful.
>
> Thanks!
> --Cindy
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: query evaluation problem

2010-08-16 Thread Alec Shaner
Regarding your issue with get_next, could be because you're invoking the
method when you define default=get_next(). Try it with just the bare method
name get_next.

You could also use the aggregate function instead of creating a new model:

http://docs.djangoproject.com/en/1.2/topics/db/aggregation/#topics-db-aggregation

Just define get_next to call the Max aggregate on your Newspaper model's
number field.

On Mon, Aug 16, 2010 at 12:39 PM, bagheera  wrote:

> Hi, i have "number" field in "newspaper" model.  I want assign to it
> dynamically a default value, witch would be a incremented by 1 highest value
> so far.
> So i managed to make a little workaround, since i can't query for last
> value of "number" field of model from model itself.
>
> I have created new model, witch has only 1 field any 1 record, witch stores
> current highest value.
> I wrote two functions:
>
>
> #-*- coding: utf-8 -*-
> from nml.options.models import Wydanie_opt
>
> def set_next(value):
>try:
>option = Wydanie_opt.objects.all()[0]
>if value > option.nr_wydania_next:
>option.nr_wydania_next = value
>option.save()
>except:
>option = Wydanie_opt(nr_wydania_next = value)
>option.save()
>
> def get_next():
>try:
>option = Wydanie_opt.objects.all()[0]
>value = option.nr_wydania_next
>except:
>return 0
>else:
>return value + 1
>
> Here's code of "newspaper" model:
>
>
> from nml.options.utils import get_next
>
>
> class Wydanie(models.Model):
>nr_wydania = models.PositiveIntegerField(verbose_name = "Numer wydania",
> unique = True, default = get_next(),
>help_text = "Unikalny numer wydania.")
>
> The problem is, set_next is working as intended, but get_next() does NOT,
>  default value stays the same until i restart dev server. Why? Query isn't
> evaluated? get_next() function isn't called at all?
> Mb there is a better way to implement auto-incrementation.
> Keep in mind that, "nr_wydania" field must be visible and editable, since
> first entered value is unknown, some values may be skipped, and there is no
> order of adding it.
> --
> Linux user
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: confusing query involving time ranges

2010-08-12 Thread Alec Shaner
Hopefully some django sql guru will give you a better answer, but I'll take
a stab at it.

What you describe does sound pretty tricky. Is this something that has to be
done in a single query statement? If you just need to build a list of
objects you could do it in steps, e.g.:

# Get all State objects that span the requested dt
q1 = State.objects.filter(first_dt__lte=dt, last_dt__gte=dt)

# Get all State objects where foo is not already in q1, but have a last_dt
prior to requested dt
q1_foo = q1.values_list('foo')
q2 =
State.objects.exclude(foo__in=q1_foo).filter(last_dt__lt=dt).order_by('-last_dt')

But q2 would not have unique foo entries, so some additional logic would
need to be applied to get the first occurrence of each distinct foo value in
q2.

Probably not the best solution, but maybe it could give you some hints to
get started.

On Thu, Aug 12, 2010 at 12:51 PM, Emily Rodgers <
emily.kate.rodg...@gmail.com> wrote:

> Hi,
>
> I am a bit stuck on this and can't seem to figure out what to do.
>
> I have a model that (stripped down for this question) looks a bit like
> this:
>
> class State(models.Model):
>first_dt = models.DateTimeField(null=True)
>last_dt = models.DateTimeField(null=True)
>foo = models.CharField(FooModel)
>bar = models.ForeignKey(BarModel, null=True)
>meh = models.ForeignKey(MehModel, null=True)
>
> This is modeling / logging state of various things in time (more
> specifically a mapping of foo to various other bits of data). The data
> is coming from multiple sources, and what information those sources
> provide varies a lot, but all of them provide foo and a date plus some
> other information.
>
> What I want to do, is given a point in time, return all the 'states'
> that span that point in time. This seems trivial except for one thing
> - a state for a particular 'foo' may still be persisting after the
> last_dt until the next 'state' for that 'foo' starts. This means that
> if there are no other 'states' between the point in time and the start
> of the next state for a given foo, I want to return that state.
>
> I have built a query that kindof explains what I want to do (but
> obviously isn't possible in its current form):
>
> dt = '2010-08-12 15:00:00'
>
> lookups = State.objects.filter(
>Q(
>Q(first_dt__lte=dt) & Q(last_dt__gte=dt) |
>Q(first_dt__lte=dt) &
>
> Q(last_dt=State.objects.filter(foo=F('foo')).filter(first_dt__lte=dt).latest('last_dt'))
>)
> )
>
> I know this doesn't work, but I think it illustrates what I am trying
> to do better than words do.
>
> Does anyone have any advice? Should I be using annotate or something
> to show what the last_dt for each foo is? I might be being really
> stupid and completely missing something but I have been trying to
> figure this out for too long!
>
> Cheers,
> Emily
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: queryset field order

2010-08-06 Thread Alec Shaner
You can't use a dictionary if you expect a certain order of key/value pairs.

Given model A you could get a list of field objects in the same order (I
think) as defined in the model class

A._meta.fields

At least with that information you could programatically produce a list of
data in matching order with a little code.

On Fri, Aug 6, 2010 at 1:34 PM, owidjaya  wrote:

> is there a way that i can get the a list of dictionaries as a result
> with the dictionary having the same field order as the table?
>
> On Aug 6, 10:18 am, Daniel Roseman  wrote:
> > On Aug 6, 6:08 pm, owidjaya  wrote:
> >
> > > I checked it and the field order still not the same.
> > > Just to clarify. I want the to do this A.objects.all().values()
> > > and still get the each list in the result to have the same "field
> > > order" as the database table defined.
> >
> > `values()` returns a set of dictionaries. Dictionaries are unordered
> > by definition.
> >
> > `values_list()` returns a set of tuples, which should be in the same
> > order as the model definition, however you don't get the fieldnames.
> > --
> > 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-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: overriding model.save()

2010-08-05 Thread Alec Shaner
The "new" values are what you just set: in your example, self.a=3 and
self.b=4 if you're inside your custom save method. Then you can get the
current values from the database from inside your custom save with something
like:

current = Foo.objects.get(pk=self.pk)

and inspect current.b for special values.

On Thu, Aug 5, 2010 at 2:54 PM, Sells, Fred wrote:

> That part makes sense, but where would I find the "new" values that have
> been set but not saved when my custom save() method is called? Like
>
> X.a=3
> X.b=4
> X.save()
>
> I want to see if b is a special value before saving.
>
> -Original Message-
> From: django-users@googlegroups.com [mailto:django-us...@googlegroups.com]
> On Behalf Of Sam Lai
> Sent: Thursday, August 05, 2010 7:58 AM
> To: django-users@googlegroups.com
> Subject: Re: overriding model.save()
>
> On 5 August 2010 03:05, Sells, Fred  wrote:
> > I would like to prevent saving a new value if the database contains a
> > specific value.  This is on a per field, per record basis.
> >
> > If I override the save() method; is there a way to find the existing (in
> > the DB) values and the new (to be stored) values?
>
> Just perform database queries as per normal inside the save() method.
>
> You have access to the object to be stored as well, see
>
> http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods
>
> > --
> > You received this message because you are subscribed to the Google Groups
> "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> > For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
> >
> >
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: TypeError: decoding Unicode is not supported

2010-08-04 Thread Alec Shaner
Ah, maybe that makes more sense then. It does indeed sound like locale issue
with your apache + mod_python envrionment. I see an old django ticket that
sounds pretty similar:

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

Sounds like you're still getting ASCII as the default encoding despite the
env settings in apache?

Out of curiosity I created a view to dump the encoding in my django dev app
by calling locale.getpreferredencoding(). In both apache+mod_wsgi and django
development server it returns UTF-8. My linux box is configured with UTF-8
as the default, so I haven't done anything special with apache. If you put
that in your code and it has UTF-8 in both cases then this issue is beyond
me.

On Wed, Aug 4, 2010 at 4:10 PM, sohesado  wrote:

>
>
>
> On Aug 4, 6:48 pm, Alec Shaner  wrote:
> > I'm no expert on encodings so I can only suggest some alternatives that
> > might get around the issue:
> >
>
> > First, maybe you can find something here:
> http://docs.python.org/howto/unicode
>
> i've read , pretty much everything,  available at docs.python.org
> regarding unicode.
>
> > You could try the literal method of generating a unicode string:
> >
> > path = u'%s%s' % (ROOT, name)
> tried it. The problem persists
> > Where exactly do you get the UnicodeEncodeError exception when you remove
> > the unicode calls?
>
> I get the the exception at this line -> shutil.copytree(ROOT +
> 'matrix', path)
>
> And the traceback...
>
> Traceback:
> File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/
> base.py" in get_response
>  100. response = callback(request,
> *callback_args, **callback_kwargs)
> File "/usr/local/lib/python2.6/dist-packages/django/contrib/auth/
> decorators.py" in _wrapped_view
>  25. return view_func(request, *args, **kwargs)
> File "/home/sohesado/codein/wikitool/creators/views.py" in create_wiki
>  42.   doku_script.create_wiki(w.name, tmpl,
> request.POST['access_policy'], reg)
> File "/home/sohesado/codein/wikitool/creators/doku_script.py" in
> create_wiki
>  10.   create_base(name, reg)
> File "/home/sohesado/codein/wikitool/creators/doku_script.py" in
> create_base
>  16.   shutil.copytree(ROOT + u'matrix', path)
> File "/usr/lib/python2.6/shutil.py" in copytree
>  146. os.makedirs(dst)
> File "/usr/lib/python2.6/os.py" in makedirs
>  157. mkdir(name, mode)
>
> Exception Type: UnicodeEncodeError at /wikitool/creators/create_wiki/
> Exception Value: 'ascii' codec can't encode characters in position
> 19-25: ordinal not in range(128)
>
>
> >
> > On Wed, Aug 4, 2010 at 11:00 AM, sohesado  wrote:
> > > Well your example clarifies the problem. I removed the unicode calls.
> >
> > > The initial problem was an  UnicodeEncodeError exception. I tried to
> > > solve it by encoding the strings to utf-8. It seems that's not the
> > > case.
> > > So i'm at square one.
> >
> > > Note that..
> > > -with python manage.py runserver the app runs flawlessly.
> > > -With apache+mod-python i get an UnicodeEncodeError.
> >
> > > So , it is an apache localization issue?
> >
> > > My /etc/apache2/envvars contains
> >
> > >
> ---
> -
> > > export APACHE_RUN_USER=www-data
> > > export APACHE_RUN_GROUP=www-data
> > > export APACHE_PID_FILE=/var/run/apache2.pid
> >
> > > ## The locale used by some modules like mod_dav
> > > export LANG='el_GR.UTF8'<- also tried el_GR.UTF-8 variation
> > > export LC_ALL='el_GR.UTF8'
> > > ## Uncomment the following line to use the system default locale
> > > instead:
> > > #. /etc/default/locale
> >
> > > export LANG
> >
> > >
> ---
> --
> >
> > > Have you got any clues what may cause the problem?
> >
> > > Thank you for your help.
> >
> > > On Aug 3, 11:31 pm, Alec Shaner  wrote:
> > > > unicode gives me nightmares.
> >
> > > > Taking django out of the picture for a moment:>>> unicode('foo',
> 'utf-8')
> > > > u'foo'
> > > > >>> unicode(u'

Re: TypeError: decoding Unicode is not supported

2010-08-04 Thread Alec Shaner
I'm no expert on encodings so I can only suggest some alternatives that
might get around the issue:

First, maybe you can find something here:
http://docs.python.org/howto/unicode

You could try the literal method of generating a unicode string:

path = u'%s%s' % (ROOT, name)

Where exactly do you get the UnicodeEncodeError exception when you remove
the unicode calls?

On Wed, Aug 4, 2010 at 11:00 AM, sohesado  wrote:

> Well your example clarifies the problem. I removed the unicode calls.
>
> The initial problem was an  UnicodeEncodeError exception. I tried to
> solve it by encoding the strings to utf-8. It seems that's not the
> case.
> So i'm at square one.
>
> Note that..
> -with python manage.py runserver the app runs flawlessly.
> -With apache+mod-python i get an UnicodeEncodeError.
>
> So , it is an apache localization issue?
>
> My /etc/apache2/envvars contains
>
>
> 
> export APACHE_RUN_USER=www-data
> export APACHE_RUN_GROUP=www-data
> export APACHE_PID_FILE=/var/run/apache2.pid
>
> ## The locale used by some modules like mod_dav
> export LANG='el_GR.UTF8'<- also tried el_GR.UTF-8 variation
> export LC_ALL='el_GR.UTF8'
> ## Uncomment the following line to use the system default locale
> instead:
> #. /etc/default/locale
>
> export LANG
>
> -----
>
> Have you got any clues what may cause the problem?
>
> Thank you for your help.
>
> On Aug 3, 11:31 pm, Alec Shaner  wrote:
> > unicode gives me nightmares.
> >
> > Taking django out of the picture for a moment:>>> unicode('foo', 'utf-8')
> > u'foo'
> > >>> unicode(u'foo', 'utf-8')
> >
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > TypeError: decoding Unicode is not supported
> >
> > So I would assume when you run it inside django you're already using a
> > unicode string. Do you need to pass the encoding argument ('utf-8') to
> > unicode?
> >
> > On Tue, Aug 3, 2010 at 3:30 PM, sohesado  wrote:
> > > Hi
> >
> > > I'm currently developing a django project and i've encountered a
> > > problem regarding Unicode string manipulation.
> >
> > > There is a backend python module in my project that perform's mainly
> > > shutil (shell utilities) tasks.
> >
> > > I get an TypeError: "decoding Unicode is not supported" exception
> > > while running the following method
> >
> > >
> -
> > > def create_base(name, reg):
> > >path = unicode(ROOT + name, 'utf-8') <<<< error at this line
> > >shutil.copytree(ROOT + 'matrix', path)
> > >shutil.copystat(ROOT + 'matrix', path)
> >
> > >f = codecs.open(path + '/conf/local.php', "w", "UTF-8")
> > >tmp = unicode(" > >f.write(tmp)
> > >if not reg:
> > >f.write("$conf['disableactions'] = 'register';\n")
> >
> > >
> ---
> >
> > > The weird thing that puzzles me is that when i test the module in a
> > > python shell , the method runs flawlessly which yields me to the
> > > assumption that it's a django thing.
> > > By the way i use apache+mod-python as a web-server
> >
> > > I can't get adequate information regarding this type of exception. I'm
> > > stuck , please help.
> >
> > > --
> > > You received this message because you are subscribed to the Google
> Groups
> > > "Django users" group.
> > > To post to this group, send email to django-us...@googlegroups.com.
> > > To unsubscribe from this group, send email to
> > > django-users+unsubscr...@googlegroups.com
> 
> >
> > > .
> > > For more options, visit this group at
> > >http://groups.google.com/group/django-users?hl=en.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: TypeError: decoding Unicode is not supported

2010-08-03 Thread Alec Shaner
unicode gives me nightmares.

Taking django out of the picture for a moment:
>>> unicode('foo', 'utf-8')
u'foo'
>>> unicode(u'foo', 'utf-8')
Traceback (most recent call last):
  File "", line 1, in 
TypeError: decoding Unicode is not supported

So I would assume when you run it inside django you're already using a
unicode string. Do you need to pass the encoding argument ('utf-8') to
unicode?

On Tue, Aug 3, 2010 at 3:30 PM, sohesado  wrote:

> Hi
>
> I'm currently developing a django project and i've encountered a
> problem regarding Unicode string manipulation.
>
> There is a backend python module in my project that perform's mainly
> shutil (shell utilities) tasks.
>
> I get an TypeError: "decoding Unicode is not supported" exception
> while running the following method
>
>
> -
> def create_base(name, reg):
>path = unicode(ROOT + name, 'utf-8')  error at this line
>shutil.copytree(ROOT + 'matrix', path)
>shutil.copystat(ROOT + 'matrix', path)
>
>f = codecs.open(path + '/conf/local.php', "w", "UTF-8")
>tmp = unicode("f.write(tmp)
>if not reg:
>f.write("$conf['disableactions'] = 'register';\n")
>
> ---
>
> The weird thing that puzzles me is that when i test the module in a
> python shell , the method runs flawlessly which yields me to the
> assumption that it's a django thing.
> By the way i use apache+mod-python as a web-server
>
> I can't get adequate information regarding this type of exception. I'm
> stuck , please help.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: is it possible to pass a dynamic list of choices to a select widget?

2010-08-03 Thread Alec Shaner
Based on what you described as your intent, have you looked at
ModelChoiceField?  You could create a new table, e.g. ProductOptions, that
has a foreign key to your Product table. In your form class you can then
pass a queryset into the ModelChoiceField that selects only the options for
that product, and if necessary even filter out any options that aren't
available  - assuming your ProductOption table had a quantity field.

If you have many products that share a common set of options (e.g., all
shirts have S, M, L, XL, etc.) you might design the tables a little
differently, but ultimately a ModelChoiceField can be passed any queryset
that filters the correct options.

If you prefer to store each product's options as a comma separated field,
you can still do what was suggested previously and just pass the choices
into the init method of the form.

Regarding your issue of needing an iterable - as was stated by Steve Holden
if you have a method that produces the choices, then you want to call that
method, e.g., choices=foo.create_choices(), not choices=foo.create_choices.

On Tue, Aug 3, 2010 at 2:29 PM, shofty  wrote:

> cheers for reading Steve.
>
> I've been through the documentation again and it definitely states
> that the widget wants an iterable. so i dont think im going to be able
> to do what i wanted to do, need another approach.
>
> Matt
>
> On 3 Aug, 16:15, Steve Holden  wrote:
> > On 8/3/2010 11:12 AM, shofty wrote:
> >
> > > Steve,
> >
> > > the choices are different for each product in the shop.
> > > some choices are clothing sizes, some physical sizes etc.
> >
> > > So with that in mind i could go with a bunch of choices hooked up to a
> > > choices field if i can tell the form which choice field to use based
> > > around the product attribute stored.
> >
> > > but what if im not the shop admin?
> > > in that case i'd have to amend the code every time something goes out
> > > of stock in a certain size.
> >
> > > so i came upon the plan to have a boolean denote whether or not the
> > > object has a size option and if so store the options in the model so
> > > that it could be amended in the admin pages. then draw a select at
> > > runtime with the right options in it.
> >
> > > thanks for the other pointers, i had an idea the function wasn't right
> > > and indeed it isn't going to work at all since the widget won't allow
> > > a callable.
> >
> > > i'll try turning that function into a method on the form and see if it
> > > won't work that way
> >
> > Good stuff. This is a pretty helpful group, so do post again when you
> > have further issues. Nobody gets it right the first time ...
> >
> > regards
> >  Steve
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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