[Fixed]-Django: Best Way to Add Javascript to Custom Widgets

15👍

4👍

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.

Leave a comment