Django CustomTags Using Session

45 Views Asked by At

I'm trying to use Django to output an HTML page based on whether the session is set or not.

when I submit my Django Form (via my view) I set the session like this:


def index(request):
    users = Users.objects.all()
    totalUsers = len(users)
    form = CreateUserForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        form = CreateUserForm()
    context = {
        "form": form,
        'users': users,
        "totalUsers": totalUsers,
    }
    request.session.set_expiry(300)
    request.session['loggedIn'] = True
    return render(request, 'SmartCity/index.html', context)

I know this is successful because I can see the value set in the DB.

In my CustomTags.py file, I want to more or less check the session variable "loggedIn" is set, and if it is, return one thing, otherwise, return something else. This is how I thought to achieve it, but it's not working:


from Django import template

register = template.Library()

@register.inclusion_tag('SmartCity/index.html', takes_context=True)
    def hello_world(context):
        request = context['request']
        loggedInStatus = request.session.get('logged_in', 'False')
        if loggedInStatus == True:
            return "Hello world"

The error I receive is: https://preview.ibb.co/dqAe8k/2017_09_19_18_06_57.png

I could totally be on the wrong track... I would appreciate any advice you might be able to give a Django beginner :)

0

There are 0 best solutions below