[Answered ]-Is it safe to render URLField directly in a Django template?

2👍

An URLField is just a CharField with some regex validation that ensures the input resembles an URL, so your form will reject any non-URL-like strings.

Furthermore, when outputting the URL to a template, Django performs escaping on template variables by default:

By default in Django, every template automatically escapes the output of every variable tag. 

That said, there’s nothing stopping people posting valid links to malicious sites or spam sites, or adding GET parameters to the URL etc. so you still can’t be sure that the site it safe.


As an aside, before Django 1.5, there was a verify_exists=True/False parameter that you could instantiate your URLField with which would perform an actual web request to the URL during validation, to see if it existed, but this was depreciated:

django.db.models.fields.URLField.verify_exists will be removed. The feature was deprecated in 1.3.1 due to intractable security and performance issues and will follow a slightly accelerated deprecation timeframe.

Leave a comment