pythondjangodjango-viewsdjango-templatesdynamic-url

Is it possible to customize individual pages associated with the same template? dynamic URL django


I am working on a blog website and have set up dynamic URLs in Django for each blog article. Is it possible to change the layout of paragraphs and images of specific pages so that there are slight differences between each page?


Solution

  • Yes it is possible to have different layout for the same template rendered in Django. You can pass some variable in context to achieve this goal like this :

    views.py

    def detail(request, id):
        object = Model.objects.get(pk=id)
        context = {'layout': f"layout_for_{id}"}
        return render(request, 'template.html', context)
    

    template.html

    {% if layout == 'layout_for_2' %}
    Layout for 2 here
    {% endif %}
    

    You can add more condition as you want, but it can become hard to for too much {% if %} block.