S_alj
S_alj

Reputation: 447

Django- CSRF and POSTing an Html form

In a Django view, I'm placing an Html form (actual string with some Html, from my DB) into an Html template, with a tag: {{ injected_form|safe }}. This succeeds in showing the form, but I've got an issue POSTing it:

Forbidden (...) CSRF token missing or incorrect.

(Which I know is appropriate Django behaviour, as I have no CSRF token tag/field inside the form itself. Btw the reason for the custom Html form strings in the DB is that they can be produced by the actual user)

A solution I could implement is TheBronx's answer to a question here. This seems to be a case where just doing

<form method="post">
    {% csrf_token %}
    ......
</form>

is not possible! Are there solutions for this issue?

I've figured out how to handle/receive POSTs without a related Django model, but I didn't foresee this CSRF problem submitting them :( Any help would be greatly appreciated

Upvotes: 1

Views: 1047

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

I'm not sure why it isn't possible. Surely the form stored in the database doesn't need to include the <form> tags themselves, so you could easily use those yourself and add the CSRF token. That seems safer anyway, since you should really ensure the destination of the form POST yourself.

But I must say, this whole approach seems wrong. It's never really going to be safe to allow users to add raw HTML to your database and output it directly, unescaped, to the template. And allowing them to specify form fields in HTML seems like a recipe for all sorts of injection attacks.

Instead consider allowing them to choose from a selection of fields, and build up the form yourself from those.

Upvotes: 2

Related Questions