#慎用|safe 和 mark_safe,如果要用,一定要过滤关键字
from django.shortcuts import render lis = [] def content(request): if request.method == 'GET': return render(request,'form.html') else: content = request.POST.get('content') #因为html里面写了{{ i|safe }},如果i是<script>alert('abc')</script>, #那么浏览器就执行这个代码,就受到xss攻击。所以在这里要过滤掉script。 if 'script' in content: return render(request, 'form.html',{'error':'傻逼,想黑我'}) else: lis.append(content) return render(request, 'form.html') def comment(request): return render(request,'comment.html',{'lis':lis}) #模板替换前,标签要使用mark_safe标记,否则在浏览器显示的是字符串,而不是该标签。 #如果不标记,在html里面把{{ temp }}修改为{{ temp|safe }} def test(request): from django.utils.safestring import mark_safe temp = '<a href="http://www.baidu.com">百度</a>' temp = mark_safe(temp) return render(request,'test.html',{'temp':temp})
form.html <body> <form method="POST" action="/content/"> <p>评论: <input type="text" name="content"> </p> <p> <input type="submit" value="提交"> <span style="color:red;">{{ error }}</span> </p> </form> </body>
comment.html <body> <h1>评论</h1> {% for i in lis %} <div>{{ i|safe }}</div> {% endfor %} </body>
test.html <body> {{ temp }} </body>
urls.py from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('content/', views.content), path('comment/', views.comment), path('test/', views.test), ]