使用variaDjango表单本地呈现模板

2024-04-25 23:05:29 发布

您现在位置:Python中文网/ 问答频道 /正文

https://docs.djangoproject.com/en/1.6/topics/forms/中的示例演示了form的用法,并包含以下代码:

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,})

以及联系人.html模板是

^{pr2}$

我想知道是否可以在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,})

如果有可能,这种方法的缺点和风险是什么?在

提前谢谢!在


Tags: theform模板returnifrequesthtmlcontact
1条回答
网友
1楼 · 发布于 2024-04-25 23:05:29

而不是使用render,这是加载模板、呈现模板并返回响应的快捷方式。但您可以通过单独的呼叫来完成:

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

python的主要缺点是混合了HTML文件。例如,您可以使用此技术从数据库或api加载模板。在

相关问题 更多 >