简体   繁体   中英

Passing variables to django template from view

In my base.html, i have the following code

{% if user_anon == "true" %}
    {% block login_with_fb %}{% endblock %}
{% else %}
    SOMETHING ELSE

And in views.py , i have

t = get_template('login.html')
try:
    c = Context({ 'user_anon':"false" , 'STATIC_URL':'/stic'})
except ObjectDoesNotExist:
    c = Context({ 'user_anon':"true" , 'STATIC_URL':'/stic'})
r = t.render(c)
return HttpResponse(r)

but the base.html always responds with user_anon = "true" code... irrespective of the value of c being passed :/

Why not check the request directly in the template?

Example:

{% if user.is_authenticated %}

Secondly, why are you casting it to a string? It would be easier to just use true/false in Python I would think.

Lastly, why are you injecting your static url? You should be setting this in your configuration, then you can just use it directly via template tag. See the official docs about this here .

Example:

 {% load staticfiles %}
 <img src="{% static "my_app/myexample.jpg" %}" alt="My image"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM