Re: Ticket 8764 (Mixing args and **kwargs in reverse() function)

2009-01-06 Thread Malcolm Tredinnick

On Tue, 2009-01-06 at 15:38 -0800, Killarny wrote:
> The above ticket was opened a while back concerning the inability to
> define views that use both positional arguments and keyword arguments
> when expecting to use reverse() to match urls tied to those views.
> 
> I don't understand the rational here for not fixing this issue. The
> decision not to allow mixing args and kwargs seems like a lazy way to
> avoid coming up with a real solution. Forcing the use of one or the
> other but not both is simply not pythonic, and without some sort of
> discussion, seems silly. When a python framework does not allow valid
> python syntax to function properly, that sounds like a fundamental
> flaw in design to me.

Could you please be slightly less dismissive of the implementation
efforts? "Lazy", "silly", "not pythonic", "fundamental flaw" tend to
disregard the enormous efforts a number of people have put into making
that functionality work. We don't actually just make stuff up after a
few beers and commit the first thing that runs, you know. I don't think
it's unreasonable to ask you to assume the best of intentions on the
part of people implementing the code. 

For the record, initially we tried very hard to allow mixed arguments.
SmileyChris and I had a lot of back and forth about it, since it would
have been potentially useful functionality. But it also wasn't critical
functionality. The reversing functionality is still fully usable without
that particular extra and, in the end, it turned out to be pretty
inefficient and made the code a lot more complex.

There's already a lot of processing and memory usage that goes into
making reversing work and increasing it further to allow for all the
possible mixed combinations of keyword and positional arguments (the
combinations grow at quite an alarming rate with a few optional
parameters involved) wasn't encouraging. Things were measurably slower
and reversing is already slow enough for that to be a concern. Plus,
everybody was having to pay the penalty, not just those using that
particular piece of functionality. Being able to split into only two
direct cases -- dictionary substitution or positional argument
substitution -- simplified a lot of things and removed a bunch of bugs
that were lurking in the edge cases.

I did have a version that almost worked with mixed argument types, but
even trying to document the behaviour so that people could predict which
of two patterns with differently named parameters that contained
optional pieces would be selected was brain-meltingly hard (some cases
led to basically arbitrary choices having to be made, which wasn't
predictable unless you knew how things were stored in an internal
dictionary and wouldn't have been portable). It wasn't doing any favours
to either the people who would have to use the function or those of us
who would have to field the bug reports and maintain it.

> There are many instances where, in a complicated implementation of
> views, one might want to have a combination of required args and
> optional kwargs, and the inability to mix them introduces all sorts of
> complexities to the logic of the views that shouldn't have to be dealt
> with.

I'll disagree with this. Whilst it's easy when one is faced with a
particular problem to imagine that it must be a common case, in reality
there aren't really that many instances where mixing is required (in
fact, I can't think of *any* where it could be compulsory -- it's purely
an alternative representation, so rewrites are always possible). There
are cases where it can be used, as you witness, but it's not *required*.

Porting isn't really that hard, either. It might well take a little
time, which is unfortunate, but it's not rocket surgery and it's a
one-off exercise. If you find you're needing to mix things, the most
straightforward change is to give all your parameters names and use
keyword arguments always.

> Due to the abruptness with which I was referred to this list, I feel
> like I must be missing some obvious piece of logic in this decision,

All that you're missing when you reopened the ticket is that we ask
people not to reopen tickets that have been closed as wontfix. In our
contributing document it asks you to come to the django-developers list
if you have further discussion. Otherwise things descend rapidly into a
seuqence of wontfix/reopen/wontfix/reopen just because people don't
agree on the decision. To be able to draw a close to that sort of
sequence, we ask that when a core developer closes a ticket as wontfix,
it doesn't get reopened. It's common on public bug tracking systems to
ask people not to just reopen tickets for precisely those reasons. Okay,
you didn't know that initially, which is why that sort of thing gets
cleared up pretty quickly. No problems there.

> as many of the other tickets have well defined responses and rational
> for the decisions related to them, while this ticket has almost none.

Maybe go back and reread the 

Ticket 8764 (Mixing args and **kwargs in reverse() function)

2009-01-06 Thread Killarny

The above ticket was opened a while back concerning the inability to
define views that use both positional arguments and keyword arguments
when expecting to use reverse() to match urls tied to those views.

I don't understand the rational here for not fixing this issue. The
decision not to allow mixing args and kwargs seems like a lazy way to
avoid coming up with a real solution. Forcing the use of one or the
other but not both is simply not pythonic, and without some sort of
discussion, seems silly. When a python framework does not allow valid
python syntax to function properly, that sounds like a fundamental
flaw in design to me.

There are many instances where, in a complicated implementation of
views, one might want to have a combination of required args and
optional kwargs, and the inability to mix them introduces all sorts of
complexities to the logic of the views that shouldn't have to be dealt
with.

Due to the abruptness with which I was referred to this list, I feel
like I must be missing some obvious piece of logic in this decision,
as many of the other tickets have well defined responses and rational
for the decisions related to them, while this ticket has almost none.

My personal stake in this issue has to do with one of my applications
which relies heavily on a required argument on every view - an
employee slug. I've built multiple decorators around this, and much of
my functionality depends on that argument. On one of my views, I want
to allow some filtering keywords to be optionally included on the
view, and due to this bug I am simply unable to do that without (A)
radically rewriting my application, or (B) writing two identical views
which have different required arguments and defining a url for each.
Option A is simply not feasible, and option B is just a silly thing to
have to do, when if this bug were not an issue, I could simply use the
syntax that any python method definition allows me to use.

I imagine that an argument will be made that I should have developed
my application from the start with this limitation in mind (which is
what mtredinnick suggests in a comment on that ticket) but this
limitation is not mentioned in the documentation anywhere that I could
find, so I don't see how I could have known this until encountering
it. And again, why would anyone expect this sort of a limitation,
considering that it flies in the face of what python syntax allows
everywhere else?

Futher confusing the issue is the text at
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url where
apparently the url tag supports mixing args and kwargs just fine. I
have not tested this yet, but the example given in the documentation
there does exactly that: {% url path.to.some_view
arg1,arg2,name1=value1 %} Is there an inconsistency between reverse()
and {% url %}?

I hope I have not come across badly in this post; I am trying to
remain patient, but this is quite frustrating to come across such a
perceived closed door regarding this bug.

(reposting because first message didn't post properly)

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



Re: ticket 8764 (Mixing args and **kwargs in reverse() function)

2009-01-06 Thread Killarny

The above ticket was opened a while back concerning the inability to
define views that use both positional arguments and keyword arguments
when expecting to use reverse() to match urls tied to those views.

I don't understand the rational here for not fixing this issue. The
decision not to allow mixing args and kwargs seems like a lazy way to
avoid coming up with a real solution. Forcing the use of one or the
other but not both is simply not pythonic, and without some sort of
discussion, seems silly. When a python framework does not allow valid
python syntax to function properly, that sounds like a fundamental
flaw in design to me.

There are many instances where, in a complicated implementation of
views, one might want to have a combination of required args and
optional kwargs, and the inability to mix them introduces all sorts of
complexities to the logic of the views that shouldn't have to be dealt
with.

Due to the abruptness with which I was referred to this list, I feel
like I must be missing some obvious piece of logic in this decision,
as many of the other tickets have well defined responses and rational
for the decisions related to them, while this ticket has almost none.

My personal stake in this issue has to do with one of my applications
which relies heavily on a required argument on every view - an
employee slug. I've built multiple decorators around this, and much of
my functionality depends on that argument. On one of my views, I want
to allow some filtering keywords to be optionally included on the
view, and due to this bug I am simply unable to do that without (A)
radically rewriting my application, or (B) writing two identical views
which have different required arguments and defining a url for each.
Option A is simply not feasible, and option B is just a silly thing to
have to do, when if this bug were not an issue, I could simply use the
syntax that any python method definition allows me to use.

I imagine that an argument will be made that I should have developed
my application from the start with this limitation in mind (which is
what mtredinnick suggests in a comment on that ticket) but this
limitation is not mentioned in the documentation anywhere that I could
find, so I don't see how I could have known this until encountering
it. And again, why would anyone expect this sort of a limitation,
considering that it flies in the face of what python syntax allows
everywhere else?

Futher confusing the issue is the text at
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url where
apparently the url tag supports mixing args and kwargs just fine. I
have not tested this yet, but the example given in the documentation
there does exactly that: {% url path.to.some_view
arg1,arg2,name1=value1 %} Is there an inconsistency between reverse()
and {% url %}?

I hope I have not come across badly in this post; I am trying to
remain patient, but this is quite frustrating to come across such a
perceived closed door regarding this bug.

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



Re: making some generic views more generic

2009-01-06 Thread Malcolm Tredinnick

On Tue, 2009-01-06 at 11:01 -0800, Gabe wrote:
> Hello,
> 
> I really like the generic view feature of Django. It's been a handy
> way to save a lot of work. Lately though, I've been finding myself
> often wanting to display a list of objects filtered by some field. The
> documentation suggests handling this by writing a small view that
> filters the objects and then calling the generic view from within
> that. This works fine of course, but it seems that in a lot of cases
> one can end up writing a large number of small views that all simply
> display a filtered list of objects. I figured it might be helpful to
> abstract this behavior into a couple of additional generic
> views. These will automatically filter based on a keyword captured in
> the URL and a field specified in the urls.py file. I've called these
> new views object_list_field and object_list_foreign_field. 

>From the description you've provided here, this sounds like a few lines
to filter the queryset appropriately and then call an existing generic
view. That's the normal approach when you need more filtering: filter
the queryset and then pass of the existing view, perhaps after also
updating extra_context. Your code seems quite long and has wrapped
fairly horribly in the email, so my eyes were watering a bit too much to
read it all (if you really, really have to provide code of that length,
either an attachment or a link to something like dpaste would be great).

I don't think this should be added to Django. If it scratches your itch,
then that's ideal. I think you could look at the wrapper approach for
simpler code, but that's entirely up to you for your purposes. However,
since the wrapper approach in conjunction with existing views does solve
this, it's a strong argument against needing to include it in core.
There are a million and one different use-cases that could be abstracted
in various forms. Django shouldn't include functions for all of them,
even if there's more than one user for it, since it would make the
codebase huge and adds stuff we have to maintain forever. We're working
with something that's closer to a library than a framework in many ways
(code is built on top of it, rather than within it) and so people should
be encouraged to build their enhancements externally.

Please, please don't take this the wrong way. It always looks a bit
horrible when somebody posts a bunch of code and a problem description
(you get bonus points for at least mostly describing the problem you're
trying to solve here -- something that is often missing in proposals
that leap straight to solutions) and then some bozo like me comes along
and says they're not enthused. Remember that (a) it's only my opinion,
although that does carry some weight with some people and (b) I'm
answering from the perspective of "this is django-dev and you're asking
about including it in core", not evaluating whether the idea has any
validity at all in the wild.

Best wishes,
Malcolm



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



Re: making some generic views more generic

2009-01-06 Thread cipher

Sorry, here is an example of item_list

urlpatterns = patterns('',
(r'^products/$',
item_list,{
'template_object_name' : 'product',
'queryset' : Product.objects.all()
}),
(r'^products/(?P\d+)/$',
item_list,{
'template_object_name' : 'product',
'queryset' : Product.objects.all()
}),
(r'^products/(?P[\w-]+)/$',
views.item_list,{
'template_object_name' : 'product',
'queryset' : Product.objects.all()
}),
)

On Jan 6, 2:43 pm, cipher  wrote:
> I also would like to request another view.
>
> def item_list(request,queryset,extra_context={},
>                           item_template=None,template_name=None,
>                           
> template_object_name='object',template_content_name='items',
>                           page=None,paginate_by=None,
>                           mimetype=None,allow_empty=True,
>                           template_loader=loader,context_processors=None,
>                           **filters):
>         queryset = queryset._clone()
>         if filters:
>                 for k,v in filters.items():
>                         if k.startswith('_'):
>                                 del filters[k]
>                                 filters[k[1:]]=v
>                 queryset=queryset.filter(**filters)
>
>         if paginate_by:
>                 paginator = Paginator(queryset, paginate_by,
> allow_empty_first_page=allow_empty)
>                 if not page:
>                         page = request.GET.get('page', 1)
>                 try:
>                         page_number = int(page)
>                 except ValueError:
>                         if page == 'last':
>                                 page_number = paginator.num_pages
>                         else:
>                                 # Page is not 'last', nor can it be converted 
> to an int.
>                                 raise Http404
>                 try:
>                         page_obj = paginator.page(page_number)
>                 except InvalidPage:
>                         raise Http404
>
>                 c = RequestContext(request, {
>                         '{0}_list'.format(template_object_name): 
> page_obj.object_list,
>                         'paginator': paginator,
>                         'page': page_obj,
>                         'results_per_page': paginator.per_page,
>                         'pages': paginator.num_pages,
>                         'hits': paginator.count,
>                         'page_range': paginator.page_range,
>                         }, context_processors)
>                 queryset=page_obj.object_list
>         else:
>                 c = RequestContext(request, {
>                         '%s_list' % template_object_name: queryset,
>                         'paginator': None,
>                         'page_obj': None,
>                         'is_paginated': False,
>                         }, context_processors)
>                 if not allow_empty and len(queryset) == 0:
>                         raise Http404
>         for key, value in extra_context.items():
>                 if callable(value):
>                         c[key] = value()
>                 else:
>                         c[key] = value
>
>         modelMeta=queryset.model()._meta
>         directory,name=modelMeta.app_label,modelMeta.object_name.lower()
>
>         if item_template is None:
>                 item_template='{0}/{1}_list_item.html'.format(directory,name)
>         if template_name is None:
>                 template_name='{0}/{1}_list.html'.format(directory,name)
>         item_template = template_loader.get_template(item_template)
>         responses=[]
>         c.push()
>         for item in queryset:
>                 c[template_object_name]=item
>                 item_result=item_template.render(c)
>                 responses.append(item_result)
>         c.pop()
>         template=template_loader.get_template(template_name)
>         c[template_content_name]=mark_safe(''.join(responses))
>         return HttpResponse(template.render(c), mimetype=mimetype)
>
> basically that will take keyword args and filter based on them like
> Gabes methods,
> but it also abstracts the item template in to another file.
>
> On Jan 6, 11:01 am, Gabe  wrote:
>
> > Hello,
>
> > I really like the generic view feature of Django. It's been a handy
> > way to save a lot of work. Lately though, I've been finding myself
> > often wanting to display a list of objects filtered by some field. The
> > documentation suggests handling this by writing a small view that
> > filters the objects and then calling the generic view from within
> > that. This works fine of course, but it seems that in a lot of cases
> > one can end up writing a large number of small views that 

Re: Some tickets that should perhaps get looked at before 1.1

2009-01-06 Thread Malcolm Tredinnick

On Tue, 2009-01-06 at 09:05 -0800, mrts wrote:
> As the list seems to be resuming from holiday hibernation, I risk
> causing another "don't you dare to push us" flame-bombing :) by
> proposing that the following get looked at before 1.1:
> 
> * `__import__(mod, {}, {}, [''])` causes double import of modules [1]

It's already being looked at. It's assigned to me for that reason. As I
mentioned in the last substantive comment on the ticket, solving it has
revealed some other problems with imports that I'm slowly working
through as time permits.

Regards,
Malcolm


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



Re: #3566 Aggregations: Call for testing

2009-01-06 Thread Russell Keith-Magee

On Wed, Jan 7, 2009 at 4:19 AM, Ian Kelly  wrote:
>
> On Tue, Jan 6, 2009 at 12:14 AM, Ian Kelly  wrote:
>> On Mon, Jan 5, 2009 at 9:21 AM, Alex Gaynor  wrote:
>>> The SQL command not properly ended appears to be the result of an annotate
>>> call followed by a call to aggregate().  I don't have a clue what causes
>>> that as I've used Oracle in my life :) .
>>
>> I'll take a look at the queries tomorrow and see if I can straighten them 
>> out.
>
> The "ORA-00972: identifier is too long" error is caused by the column
> alias names not being truncated to an acceptable length
> ("book__publisher__num_awards__min" in this case).  The call to
> perform the truncation is django.db.backends.util.truncate_name(alias,
> connection.ops.max_name_length()).
>
> The "ORA-00923: FROM keyword not found where expected" is caused by
> one of the column alias names being an unquoted keyword ("number" in
> this case).  Quoting the column alias names with
> connection.ops.quote_name(alias) will fix it.
>
> The "ORA-00933: SQL command not properly ended" errors are caused by
> queries of the form "SELECT foo FROM (SELECT bar) AS subquery".  The
> "AS" keyword needs to be removed, because Oracle doesn't accept it for
> subquery aliases.
>
> I'll run the full Oracle test suite and see if anything else pops up.

Thanks Ian.

Russ %-)

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



Re: making some generic views more generic

2009-01-06 Thread cipher

I also would like to request another view.

def item_list(request,queryset,extra_context={},
  item_template=None,template_name=None,
  
template_object_name='object',template_content_name='items',
  page=None,paginate_by=None,
  mimetype=None,allow_empty=True,
  template_loader=loader,context_processors=None,
  **filters):
queryset = queryset._clone()
if filters:
for k,v in filters.items():
if k.startswith('_'):
del filters[k]
filters[k[1:]]=v
queryset=queryset.filter(**filters)

if paginate_by:
paginator = Paginator(queryset, paginate_by,
allow_empty_first_page=allow_empty)
if not page:
page = request.GET.get('page', 1)
try:
page_number = int(page)
except ValueError:
if page == 'last':
page_number = paginator.num_pages
else:
# Page is not 'last', nor can it be converted 
to an int.
raise Http404
try:
page_obj = paginator.page(page_number)
except InvalidPage:
raise Http404

c = RequestContext(request, {
'{0}_list'.format(template_object_name): 
page_obj.object_list,
'paginator': paginator,
'page': page_obj,
'results_per_page': paginator.per_page,
'pages': paginator.num_pages,
'hits': paginator.count,
'page_range': paginator.page_range,
}, context_processors)
queryset=page_obj.object_list
else:
c = RequestContext(request, {
'%s_list' % template_object_name: queryset,
'paginator': None,
'page_obj': None,
'is_paginated': False,
}, context_processors)
if not allow_empty and len(queryset) == 0:
raise Http404
for key, value in extra_context.items():
if callable(value):
c[key] = value()
else:
c[key] = value

modelMeta=queryset.model()._meta
directory,name=modelMeta.app_label,modelMeta.object_name.lower()

if item_template is None:
item_template='{0}/{1}_list_item.html'.format(directory,name)
if template_name is None:
template_name='{0}/{1}_list.html'.format(directory,name)
item_template = template_loader.get_template(item_template)
responses=[]
c.push()
for item in queryset:
c[template_object_name]=item
item_result=item_template.render(c)
responses.append(item_result)
c.pop()
template=template_loader.get_template(template_name)
c[template_content_name]=mark_safe(''.join(responses))
return HttpResponse(template.render(c), mimetype=mimetype)

basically that will take keyword args and filter based on them like
Gabes methods,
but it also abstracts the item template in to another file.

On Jan 6, 11:01 am, Gabe  wrote:
> Hello,
>
> I really like the generic view feature of Django. It's been a handy
> way to save a lot of work. Lately though, I've been finding myself
> often wanting to display a list of objects filtered by some field. The
> documentation suggests handling this by writing a small view that
> filters the objects and then calling the generic view from within
> that. This works fine of course, but it seems that in a lot of cases
> one can end up writing a large number of small views that all simply
> display a filtered list of objects. I figured it might be helpful to
> abstract this behavior into a couple of additional generic
> views. These will automatically filter based on a keyword captured in
> the URL and a field specified in the urls.py file. I've called these
> new views object_list_field and object_list_foreign_field. They are
> included below:
>
> def object_list_field(request, model, field, value, paginate_by=None,
> page=None,
>                       fv_dict=None, allow_empty=True,
> template_name=None,
>                       template_loader=loader, extra_context=None,
> context_processors=None,
>                       template_object_name='object', mimetype=None):
>     """Extends generic view object_list to display a list of objects
> filtered
>     by an arbitrary field.
>     Works only for 

Re: #3566 Aggregations: Call for testing

2009-01-06 Thread Ian Kelly

On Tue, Jan 6, 2009 at 12:14 AM, Ian Kelly  wrote:
> On Mon, Jan 5, 2009 at 9:21 AM, Alex Gaynor  wrote:
>> The SQL command not properly ended appears to be the result of an annotate
>> call followed by a call to aggregate().  I don't have a clue what causes
>> that as I've used Oracle in my life :) .
>
> I'll take a look at the queries tomorrow and see if I can straighten them out.

The "ORA-00972: identifier is too long" error is caused by the column
alias names not being truncated to an acceptable length
("book__publisher__num_awards__min" in this case).  The call to
perform the truncation is django.db.backends.util.truncate_name(alias,
connection.ops.max_name_length()).

The "ORA-00923: FROM keyword not found where expected" is caused by
one of the column alias names being an unquoted keyword ("number" in
this case).  Quoting the column alias names with
connection.ops.quote_name(alias) will fix it.

The "ORA-00933: SQL command not properly ended" errors are caused by
queries of the form "SELECT foo FROM (SELECT bar) AS subquery".  The
"AS" keyword needs to be removed, because Oracle doesn't accept it for
subquery aliases.

I'll run the full Oracle test suite and see if anything else pops up.

Ian

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



Re: CSRF / SafeForm

2009-01-06 Thread Bob Thomas

I added a ticket (with patch) for implementing the template tag:
http://code.djangoproject.com/ticket/9977
It also adds a CSRF context processor, which is used by the tag.

The diff doesn't look quite right. There obviously needs to be an
empty __init__.py file added to the templatetags folder for it to
work.

-bob

On Jan 5, 12:17 pm, Luke Plant  wrote:
> I wrote:
> > If you want to implement any of this, I'm not planning on working
> > on it for this next week, I'll get in touch when I start in case
> > you've made some progress.
>
> I'm now not going to be able to implement this for the 1.1 deadline.  
> I could review and commit if someone else implemented it, but
> remember that Jacob also wanted to see the patch complete with docs
> etc. before then, so I'm guessing this will not make 1.1 now.
>
> We would need to also ensure that all apps in contrib use the template
> tag, otherwise we wouldn't be able to make the new method a
> recommendation.  This in turn will require
> TEMPLATE_CONTEXT_PROCESSORS to
> contain 'django.core.context_processors.request' (or some other
> method for the template tag to get hold of session id/cookies).
>
> Finally, most importantly:
>
> I think we really need CSRF protection for the admin by default for
> 1.1.  The CSRF middleware in its current state, while not perfect, is
> mature enough to be on by default IMO (as you can now manually add
> exceptions where needed, and AJAX is automatically excluded).  So I'd
> recommend adding it to the default MIDDLEWARE_CLASSES in
> global_settings, or at least the skeleton settings file created
> by 'manage.py startproject'.
>
> Luke
>
> --
> Noise proves nothing.  Often a hen who has merely laid an egg cackles
> as if she laid an asteroid.
>         -- Mark Twain
>
> Luke Plant ||http://lukeplant.me.uk/
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to django-developers@googlegroups.com
To unsubscribe from this group, send email to 
django-developers+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en
-~--~~~~--~~--~--~---



making some generic views more generic

2009-01-06 Thread Gabe

Hello,

I really like the generic view feature of Django. It's been a handy
way to save a lot of work. Lately though, I've been finding myself
often wanting to display a list of objects filtered by some field. The
documentation suggests handling this by writing a small view that
filters the objects and then calling the generic view from within
that. This works fine of course, but it seems that in a lot of cases
one can end up writing a large number of small views that all simply
display a filtered list of objects. I figured it might be helpful to
abstract this behavior into a couple of additional generic
views. These will automatically filter based on a keyword captured in
the URL and a field specified in the urls.py file. I've called these
new views object_list_field and object_list_foreign_field. They are
included below:

def object_list_field(request, model, field, value, paginate_by=None,
page=None,
  fv_dict=None, allow_empty=True,
template_name=None,
  template_loader=loader, extra_context=None,
context_processors=None,
  template_object_name='object', mimetype=None):
"""Extends generic view object_list to display a list of objects
filtered
by an arbitrary field.
Works only for fields that are not ForeignKey or ManyToMany.
See object_list_foreign_field for ForeignKey fields"""

if not fv_dict:
fv_dict = {}
fv_dict[field] = value
obj_list = model.objects.filter(**fv_dict)

# calculate the number of the first object on this page
# in case the objects are paginated and want to be displayed as
# a numbered list
extra_context = {'start': calc_start(page, paginate_by,
obj_list.count())}

return list_detail.object_list(request=request,
queryset=obj_list,
   paginate_by=paginate_by,
page=page,
   allow_empty=allow_empty,
template_name=template_name,
   template_loader=template_loader,
extra_context=extra_context,
 
context_processors=context_processors,
 
template_object_name=template_object_name,
   mimetype=mimetype)

def object_list_foreign_field(request, model, field, value,
foreign_model,
  foreign_field, fv_dict=None,
  paginate_by=None, page=None,
allow_empty=True,
  template_name=None,
template_loader=loader,
  extra_context=None,
context_processors=None,
  template_object_name='object',
mimetype=None):
"""Generic view to display a list of objects filtered by an
arbitary foreign key field"""

if not fv_dict:
fv_dict = {}
foreign_obj = get_object_or_404(foreign_model, **{foreign_field:
value})
fv_dict[field] = foreign_obj.id
obj_list = model.objects.filter(**fv_dict)

# calculate the number of the first object on this page
# in case the objects are paginated and want to be displayed as
# a numbered list
extra_context = {'start': calc_start(page, paginate_by,
obj_list.count())}

return list_detail.object_list(request=request,
queryset=obj_list,
   extra_context={foreign_field:
foreign_obj},
   paginate_by=paginate_by,
page=page,
   allow_empty=allow_empty,
template_name=template_name,
   template_loader=template_loader,
 
context_processors=context_processors,
 
template_object_name=template_object_name,
   mimetype=mimetype)

Both views expect to capture a variable called "value" from the
URL. They also both accept all arguments that object_list
accepts. These can be specified within urls.py and are passed on to
object_list when it is called by object_list_field or
object_list_foreign_field.

To use the canonical book website as an example, suppose we wanted to
use these views to make a couple of different lists. For instance, we
might want to have an alpabetical listing of authors, with one page
for each letter that their last name could begin with. With
object_list_field, we wouldn't have to write a new view for this, just
add the following to urlpatterns

urlpatterns = patterns('',
...other url patterns...,
(r'^authors/(?P[A-Z]+)/$', object_list_field', 
{'model':
Author,
   
'field': 'lastname__startswith'}),
...other url patterns...,
  )

Of course, this assumes that the template_name and
template_object_name are set to the defaults expected by
list_detail.object_list. If not, these values can also be added to the
dictionary above. As another example, suppose we wanted a view that
showed all books by a particular publisher. Assuming publisher has 

Re: Session-based messages (Contrib-05, #4604)

2009-01-06 Thread Jacob Kaplan-Moss

On Mon, Jan 5, 2009 at 5:50 AM, Ramiro Morales  wrote:
> What directions do [the rest of the] core devs think should this
> take?. I could try to work on getting things in shape
> so it can approach a ready state for 1.1 a intially
> planned.

I'd like to see this moved into an external app so that we can
de-couple it from the 1.1 release. If it proves to be popular and
stable, we could then consider it for 1.2.

Jacob

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



Re: #3566 Aggregations: Call for testing

2009-01-06 Thread Russell Keith-Magee

On Tue, Jan 6, 2009 at 7:52 PM, zvoase  wrote:
>
> Just a question - how, if at all, is aggregation going to be supported
> or worked around on custom field types?

Do you have any particular fields in mind? Any custom field deriving
from the basic Django numeric and date/time types shouldn't require
any special handling, but I'd appreciate any bug report to the
contrary. If you have a use case for non numeric/date/time types, I'd
be interested to see what we can do to accomodate your needs.

Yours,
Russ Magee %-)

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



Re: #3566 Aggregations: Call for testing

2009-01-06 Thread Alex Gaynor
Well the queries themselves will execute fine, and then you will just back
whatever type your database returned, you'll need to do some coercion
yourself.

Alex

On Tue, Jan 6, 2009 at 4:52 AM, zvoase  wrote:

>
> Just a question - how, if at all, is aggregation going to be supported
> or worked around on custom field types?
>
> On Jan 6, 8:14 am, "Ian Kelly"  wrote:
> > On Mon, Jan 5, 2009 at 9:21 AM, Alex Gaynor 
> wrote:
> > > The one's that are a result of Oracle not returning a Decimal can be
> solved
> > > be inserting "..." before and after the number, in placeess of
> explicitly
> > > saying Decimal(unless of course this is actually a typecasting issue in
> > > Django itself, in which case that should be fixed) this is done a few
> other
> > > places in aggregates regress.
> >
> > The Decimal conversion might fail to happen if the corresponding field
> > passed to resolve_columns is not a DecimalField.  This happens for
> > instance when using extra selects, where no field object is available.
> >  My guess is that the fields for the aggregate columns are getting
> > excluded or misaligned somehow.  This could also be the cause of the
> > datetime/time issue.
> >
> > > The SQL command not properly ended appears to be the result of an
> annotate
> > > call followed by a call to aggregate().  I don't have a clue what
> causes
> > > that as I've used Oracle in my life :) .
> >
> > I'll take a look at the queries tomorrow and see if I can straighten them
> out.
> >
> > Ian
> >
>


-- 
"I disapprove of what you say, but I will defend to the death your right to
say it." --Voltaire
"The people's good is the highest law."--Cicero

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



Re: #3566 Aggregations: Call for testing

2009-01-06 Thread zvoase

Just a question - how, if at all, is aggregation going to be supported
or worked around on custom field types?

On Jan 6, 8:14 am, "Ian Kelly"  wrote:
> On Mon, Jan 5, 2009 at 9:21 AM, Alex Gaynor  wrote:
> > The one's that are a result of Oracle not returning a Decimal can be solved
> > be inserting "..." before and after the number, in placeess of explicitly
> > saying Decimal(unless of course this is actually a typecasting issue in
> > Django itself, in which case that should be fixed) this is done a few other
> > places in aggregates regress.
>
> The Decimal conversion might fail to happen if the corresponding field
> passed to resolve_columns is not a DecimalField.  This happens for
> instance when using extra selects, where no field object is available.
>  My guess is that the fields for the aggregate columns are getting
> excluded or misaligned somehow.  This could also be the cause of the
> datetime/time issue.
>
> > The SQL command not properly ended appears to be the result of an annotate
> > call followed by a call to aggregate().  I don't have a clue what causes
> > that as I've used Oracle in my life :) .
>
> I'll take a look at the queries tomorrow and see if I can straighten them out.
>
> Ian
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to django-developers@googlegroups.com
To unsubscribe from this group, send email to 
django-developers+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en
-~--~~~~--~~--~--~---