views:

28

answers:

1

I have the following model and url routes. There is one Post model that I want to route to different URLs based on the category. Is there a way to do this by passing in extra information in app/urls.py?

In app/posts/models.py

class Post(models.Model):
    author = ...
    title = ...
    body = ...
    category = models.CharField()

In app/urls.py

urlpatterns = patterns(
    '',
    (r'^blog/', include('posts.urls'), {'category': 'blog'}),
    (r'^school/', include('posts.urls'), {'category': 'school'}),
)

My understanding is that the extra info from app/urls.py is included in each url route in app/posts/urls.py. Is there a way to use that information? What can I put in place of the exclamation points below?

In app/posts/urls.py

from models import Post

queryset = Post.objects.order_by('-pub_date')

urlpatterns = patterns(
    'django.views.generic.list_detail',
    url(r'^$', 'object_list',
        {'queryset': queryset.filter(category=!!!!!!)}
        name="postRoot"),

    url(r'^(?P<slug>[-\w]+)/$', 'object_detail',
        {'queryset': queryset.filter(category=!!!!!!)},
        name="postDetail")
    )

Thanks, joe

+1  A: 

I am not aware of a way to use the URL parameters the way you have indicated. If anyone knows better, do correct me.

I faced a similar situation some time ago and made do with a thin wrapper over the list_detail view.

# views.py
from django.views.generic.list_detail import object_list

def object_list_wrapper(*args, **kwargs):
    category = kwargs.pop('category')
    queryset = Post.objects.filter(category = category)
    kwargs['queryset'] = queryset
    return object_list(*args, **kwargs)

#urls.py
urlpatterns = patterns('myapp.views',
    url(r'^$', 'object_list_wrapper', {}, name="postRoot"),        
...
Manoj Govindan
Pretty sure this is the answer. In my experience parameters captured by urlpatterns can only be retrieved from a view function.
Jordan Reiter
Yea, I think so too but figured I'd ask. Anyway it worked so many thanks to you.
JoeS