简体   繁体   English

django模板表单使用局部变量进行渲染

[英]django template form render with local variable

The example in https://docs.djangoproject.com/en/1.6/topics/forms/ demonstrates usage of form and has the following code: 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,})

and contact.html template is 和contact.html模板是

<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

I am wondering if it's possible in render(request,...,{'form':form,}) instead of specifying template file contact.html to pass variable with the contents of template, something like this: 我想知道是否有可能在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,})

If it's possible what could be the drawbacks and risks associated with such approach? 如果可能出现这种方法的缺点和风险?

Thanks in advance! 提前致谢!

Not with render , which is a shortcut for loading a template, rendering it and returning a response. 不是render ,这是加载模板,渲染模板和返回响应的快捷方式。 But you can do it with separate calls: 但你可以通过单独的电话来完成:

from django.template import RequestContext, Template
tpl = Template(html)
rendered = tpl.render(RequestContext(request, {'form': form}))
return HttpResponse(rendered)

The main drawback is that you're mixing the HTML in the python file, which makes it hard to read. 主要的缺点是你在python文件中混合HTML,这使得它很难阅读。 Buy you could use this technique to load templates from the database or an api, for example. 例如,购买时可以使用此技术从数据库或api加载模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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