Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Allow user to submit valid HTML in form field

With Django, is it possible for users to submit HTML in a form field, save it, and then render the HTML in the template?

An example is a user adding a link within a textfield that should then be rendered as an a tag within the rest of the text.

The user would input something like :

this is a site called <a href="http://stackoverflow.com">SO</a>.

The SO link would be a link instead of rendering it as text.

like image 857
Emile Avatar asked Jun 03 '12 17:06

Emile


People also ask

How does Django validate form data?

Django provides built-in methods to validate form data automatically. Django forms submit only if it contains CSRF tokens. It uses uses a clean and easy approach to validate data. The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class.

How do you make a field non editable in Django?

Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form.

What is form AS_P in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.

What is form cleaned_data in Django?

cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).


2 Answers

Django escapes by default. You can mark a string as safe via a filter or tag to prevent the auto escaping behavior.

{{ my_text_with_html|safe }}

{% autoescape off %}
    {{ my_test_with_html }}
{% endautoescape %}

If you accept user inputted html, you'll want to sanitize it so they can't write scripts and such.. for that, just search python html sanitizing and apply it before sending the data to the template.

Python HTML sanitizer / scrubber / filter

like image 105
Yuji 'Tomita' Tomita Avatar answered Sep 24 '22 03:09

Yuji 'Tomita' Tomita


You can tell Django the HTML is safe by marking it with the appropriate filter:

{{ variable|safe }}

You can also use the autoescape tag to disable the autoescaping:

{% autoescape off %}
    {{ variable }}
{% endautoescape %}

However, in case you are enabling this feature for other (unknown) users, I highly recommend using something else, since HTML can be quite a pain to properly sanitize from Javascript or other HTML-things you don't want (e.g., on*-arguments etc). Django actually ships with basic support for some markup languages you can provide to your users. I guess markdown is being the most popular.

like image 32
ralphje Avatar answered Sep 23 '22 03:09

ralphje