[Answer]-How to combine two similar view into one

1👍

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>
👤Selcuk

Leave a comment