Django: Best Way to Add Javascript to Custom Widgets

Take a look at form media http://docs.djangoproject.com/en/dev/topics/forms/media/#topics-forms-media


If you're looking at adding some inline JavaScript below your Django form field you can add overwrite the render method on a form field. Below I've created a custom input field, grabbed the rendered HTML and appended a new <script>...</script> to the output.

from django import forms
from django.utils.safestring import mark_safe

class CustomInputField(forms.TextInput):

    def render(self, name, value, attrs=None, renderer=None):
        html = super().render(name, value, attrs)
        inline_code = mark_safe(
            "<script>jQuery('#date').datepicker()</script>"
        )
        return html + inline_code

This will put the right below your form field in the HTML.

Tags:

Django

Widget