I have two views, one is for tags, the other one is for categories. That is tags field has ManyToManyField, and categories has ForeginKey relationship with my post model. My two views are here:
我有两个视图,一个是标签,另一个是类别。那就是tags字段有ManyToManyField,并且类别与我的帖子模型有ForeginKey关系。我的两个观点在这里:
def tag_posts(request, slug):
tag = get_object_or_404(Tags, slug=slug)
posts = tag.post_set.all()
return render(request, 'blog/cat_and_tag.html', {'posts': posts})
def category_posts(request, slug):
category = get_object_or_404(Category, slug=slug)
posts = category.post_set.all()
return render(request, 'blog/cat_and_tag.html', {'posts': posts})
I want this :
我要这个 :
def new_view(request, slug):
instance = get_object_or_404([I want model name dynamic], slug=slug)
posts = instance.post_set.all()
return render(request, 'blog/cat_and_tag.html', {'posts': posts})
is there a way of combining these two views into one view? I read about contenttypes framework. is it possible to do what I want with this?
有没有办法将这两个视图合并为一个视图?我读到了关于contenttypes框架的内容。我可以用这个做我想做的事吗?
1 个解决方案
#1
1
You can accomplish this through some url rerouting magic. This is your view:
你可以通过一些url重新路由魔法来实现这一点。这是你的观点:
def new_view(request, type, slug):
if type == 'tag':
instance = get_object_or_404(Tags, slug=slug)
elif type == 'category':
instance = get_object_or_404(Category, slug=slug)
else:
return Http404()
posts = instance.post_set.all()
return render(request, 'blog/cat_and_tag.html', {'posts': posts})
Then, in your urls.py
:
然后,在你的urls.py中:
url(r'^(?P<type>\w+)/(?P<slug>\d\w_+)$', 'project.views.project_edit', name='posts_by_type')
Now you can use the new URL in your template code like this:
现在,您可以在模板代码中使用新URL,如下所示:
<a href="{% url 'posts_by_type' 'tag' slug %}">...</a>
or
要么
<a href="{% url 'posts_by_type' 'category' slug %}">...</a>
#1
1
You can accomplish this through some url rerouting magic. This is your view:
你可以通过一些url重新路由魔法来实现这一点。这是你的观点:
def new_view(request, type, slug):
if type == 'tag':
instance = get_object_or_404(Tags, slug=slug)
elif type == 'category':
instance = get_object_or_404(Category, slug=slug)
else:
return Http404()
posts = instance.post_set.all()
return render(request, 'blog/cat_and_tag.html', {'posts': posts})
Then, in your urls.py
:
然后,在你的urls.py中:
url(r'^(?P<type>\w+)/(?P<slug>\d\w_+)$', 'project.views.project_edit', name='posts_by_type')
Now you can use the new URL in your template code like this:
现在,您可以在模板代码中使用新URL,如下所示:
<a href="{% url 'posts_by_type' 'tag' slug %}">...</a>
or
要么
<a href="{% url 'posts_by_type' 'category' slug %}">...</a>