Django模板中使用局部变量渲染表单
这个例子来自于https://docs.djangoproject.com/en/1.6/topics/forms/,展示了如何使用表单,代码如下:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {'form': form,})
而contact.html模板是
<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
我在想,在render(request,...,{'form':form,})
中,是否可以不指定模板文件contact.html
,而是传递一个包含模板内容的变量,像这样:
html = """
<html>
<head> bla bla bla</head>
<body>
<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
</body>
"""
return render(request, html, {'form': form,})
如果可以这样做,会有什么缺点和风险呢?
提前谢谢你!
1 个回答
2
不能用render
,因为它是一个快捷方式,用来加载模板、渲染它并返回一个响应。不过你可以通过分开调用来实现:
from django.template import RequestContext, Template
tpl = Template(html)
rendered = tpl.render(RequestContext(request, {'form': form}))
return HttpResponse(rendered)
主要的问题是你把HTML代码和Python代码混在一起,这样会让代码变得难以阅读。不过你可以用这种方法从数据库或API加载模板,比如说。