Glueon
Glueon

Reputation: 4017

A way to render content to a base template

I have a base template which contains header, footer and a block "content" which then I override in different CBVs.

There is little "user-space" divinside a header where I want to keep user's info in case he is logged in and a login form if he is a guest.

Right now the only way that comes in mind is to create a django app and use it as a tag. But I think there is a better solution. Because as far as I know tags can slow down django project in future.

Also I think that maybe I would like to manipulate this div from a view which renders a child template. For example I calculate and display some value on a page but also I want to display it in a "user-space" div as well. I think this can be achieved by pushing data to the user's session and then using this while rendering "user-space" div from another code.

Upvotes: 0

Views: 171

Answers (1)

austinheiman
austinheiman

Reputation: 1009

Assuming you have django.contrib.auth.user in your INSTALLED_APPS, you can access the user's login status using user.is_authenticated():

{% if user.is_authenticated %}
    <div>Welcome back, {{ user.username }} | <a href='/logout/'>Logout</a></div>
{% else %}
    <div>
    <form action='/login/' method='POST'>
    {{ csrf_token }}
    {{ login_form }}
    <input type='submit'>
    </form>
    </div>
{% endif %}

Edit:

In response to your comment:

Let's suppose client does a POST request by which we calculate some number - total price. And I need to display it in that div.

As documented

Define your view:

from django.shortcuts import render
from .forms import MyForm

def simple_view(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = MyForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            result = form.cleaned_data['some_input'] * 50
            return render(request, 'my_template.html', {'result': result})

    # if a GET (or any other method) we'll create a blank form
    else:
        form = MyForm()

    return render(request, 'my_other_template.html', {'form': form})

Display result in your template:

<!-- my_template.html -->
<div>{{ result }}</div>

Maybe you need to be more specific with your question, this is what I think you are looking for though. You should put logic like you are describing into a view, not a template.

Upvotes: 3

Related Questions