Django:将相同模型但不同类别字段路由到单独的URL
我有以下模型和 url 路线。我想根据类别将一个 Post 模型路由到不同的 URL。有没有办法通过在 app/urls.py
中传递额外信息来做到这一点?
在 app/posts/models.py
class Post(models.Model):
author = ...
title = ...
body = ...
category = models.CharField()
在 app/urls.py
urlpatterns = patterns(
'',
(r'^blog/', include('posts.urls'), {'category': 'blog'}),
(r'^school/', include('posts.urls'), {'category': 'school'}),
)
我的理解是包含来自 app/urls.py
的额外信息在 app/posts/urls.py
中的每个 url 路由中。有没有办法使用这些信息?下面的感叹号可以用什么来代替?
在 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")
)
谢谢,乔
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'^
Thanks, joe
, 'object_list',
{'queryset': queryset.filter(category=!!!!!!)}
name="postRoot"),
url(r'^(?P<slug>[-\w]+)/
Thanks, joe
, 'object_detail',
{'queryset': queryset.filter(category=!!!!!!)},
name="postDetail")
)
Thanks, joe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道如何按照您指示的方式使用 URL 参数。如果有人知道更好,请纠正我。
我前段时间遇到过类似的情况,并在
list_detail
视图上使用了一个薄包装器。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.