3

I want to output 'hello,XXX' (XXX=request.session['user']) at the top every page, so I write the below code in base.html:

hello {{ request.session['user'] }}

and there have TemplateSyntaxError:

Could not parse the remainder: '['user']' from 'request.session['user']'

This is a similar question but I really don't understand: Dynamic variables in Django base.html

If XXX is a function return value, where to write this function and how to render this value?

3 Answers 3

2

This has nothing to do with being in base.html. Neither does it have anything to do with functions, as you are not calling a function. The issue is simply that you have not read the documentation on template syntax. In a template, both attribute access and dictionary lookup are done with ".".

{{ request.session.user }} 

Although I don't know why you want to use the session for this anyway, since the user is in request.user.

Sign up to request clarification or add additional context in comments.

1 Comment

my app is a simple website and not use django auth. the SESSION['user'] will be created when user login ,request.session['user']={'uid':uid,'nickname':nickname},and there have hello XXX on the top of every page. and i write {{ request.session.user.nickname }} in base.html,it does't work but the session really created
2

In Django you don't use list indexes in template code (like request.session['user']), instead you type it as a "sort of" function like: request.session.user to get it. This is just how the template system works.

In your use-case it might be worth noting that Django has an alias for request.session.user that is merely called user. So if you e.g. wanted to get the username you would do: user.username or user.first_name for their first name. You can of course achieve the same with request.session.user.username

1 Comment

if XXX is a function return value,how to render the value to base.html :)
1

as far as i remember, there already is a {{ user }} available in Django templates, if you use the Django user auth system, so you could try to use {{ user.username }}.

You may also look at this thread. Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.