开发者

Django: routing same model but different category field to separate URLs

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


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"),        
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜