Question

The example in https://docs.djangoproject.com/en/1.6/topics/forms/ demonstrates usage of form and has the following code:

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

<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:

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!

Was it helpful?

Solution

Not with render, which is a shortcut for loading a template, rendering it and returning a response. 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. Buy you could use this technique to load templates from the database or an api, for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top