Django / Python:views.py和传递文本字符串

时间:2013-08-08 20:52:27

标签: html django django-templates django-views

所以在我的template中,我有以下代码:

<span class="state-txt">{{ state }}</span>

在我的views.py中,使用以下if / else循环处理它:

if user is not None:
            if user.is_active:
                login(request, user)            
                state = "You're successfully logged in!"
                return render_to_response('uc/portal/index.html', {'state':state, 'username':username}, context_instance=RequestContext(request))
            else:
                state = "Your account is not active, please contact UC admin."
        else:
            state = "Your username and/or password were incorrect."

基本上,它目前工作正常,但我希望每个state能够包含不同的&lt; img&gt;标签,但是当我输入state = "<img src="some.jpg"> Your username and/or password were incorrect."时,html无法正确呈现。有没有办法做我在Django尝试做的事情,或者我在咆哮错误的树?

3 个答案:

答案 0 :(得分:2)

我只是从视图中传递上下文中的图像URL,并在模板中使用它。像这样:

if user:
    if user.is_active:
        login(request, user)            
        state = "You're successfully logged in!"
        state_img = success_image_url
        return render_to_response('uc/portal/index.html', 
                 {'state': state, 
                  'state_img': state_img, 
                  'username':username
                 }, context_instance=RequestContext(request))
    else:
        state_img = inactive_image_url
        state = "Your account is not active, please contact UC admin."
else:
    state_img = invalid_credentials_url
    state = "Your username and/or password were incorrect."

并在模板中

<span class="state-txt">
    <img src="{{state_img}}" />{{ state }}
</span>

答案 1 :(得分:1)

为了完整起见,karthikr已经发布了一个很好的解决方案:

html无法正确呈现的原因是因为Django模板语言自动假设{{ ... }}的所有输出都不安全,所有HTML中具有特殊含义的符号都将被转义({{1变成<等。

要将字符串呈现为纯HTML代码,请使用&lt;过滤器。

views.py:

safe

的index.html:

state = "<img src="some.jpg" /> Your username and/or password were incorrect."

答案 2 :(得分:0)

不要渲染图像。试试if else

view.py

if user is not None:
        if user.is_active:
            login(request, user)            
            state = True
            return render_to_response('uc/portal/index.html', {'state':state, 'username':username}, context_instance=RequestContext(request))
        else:
            state = False
    else:
        state = False
模板中的

{%if state %}  
   <img></img>
   you are successfully logged in.
{%endif%}