[Django]-Django display a page title based on a variable stored in a view

5๐Ÿ‘

โœ…

You need to pass the variable to the context :

def sport_landing(request):
    page_title = 'Sport'
    cat_landing = Article.objects.filter(status='published', category='sport', published_date__lte=timezone.now()
        ).order_by('-published_date')
    return render(request, "categorylanding.html", {'cat_landing': cat_landing, 'page_title':page_title }

and use double braces { in the template ({% %} is used for template tags):

{{page_title}}

To answer about the whole pattern, you can avoid to repeat the code for each category by using a parameter inside the url pattern :

Add and adapt this line in the file urls.py, this will allow you to pass the category as a parameter to your view :

url(r'^category/(?P<category>\w+)', views.cat_landing) # i.e : mysite/category/sport

You need to declare a generic view like :

def cat_landing(request, category=None):
    if category:
        cat_landing = Article.objects.filter(status='published', category=category, 
                                             published_date__lte=timezone.now()
                                      ).order_by('-published_date')

        return render(request, "categorylanding.html", 
                      {'cat_landing': cat_landing, 'page_title':category.title() }
    else:
        return [...redirect to main menu... ]
๐Ÿ‘คPRMoureu

1๐Ÿ‘

Pass title as context

def sport_landing(request):
    page_title = 'Sport'
    cat_landing=Article.objects.filter(tatus='published',category='sport',published_date__lte=timezone.now()
    ).order_by('-published_date')
    return render(request, "categorylanding.html", {'cat_landing': cat_landing,'page_title':page_title}



        {% extends 'base.html' %}
        {% load humanize %}
        {% block content %}
        <div class="row category-landing-title">
        <div class="col-xs-12">
        {{ page_title }}
        </div>
        </div>
๐Ÿ‘คBasant Rules

Leave a comment