Reputation: 558
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:
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?
Upvotes: 0
Views: 98
Reputation: 59444
You can accomplish this through some url rerouting magic. This is your view:
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
:
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:
<a href="{% url 'posts_by_type' 'tag' slug %}">...</a>
or
<a href="{% url 'posts_by_type' 'category' slug %}">...</a>
Upvotes: 1