V
V
Vladimir Kuts2016-02-03 23:22:31
Django
Vladimir Kuts, 2016-02-03 23:22:31

How to properly design a custom widget in Django?

Faced a problem when writing widgets. Let me explain with an example. There is a certain color selector for fields. I'm adding a few of these selectors on a form. I initialize each with this piece of code:

...
$('#id_color_selector1').colorselector();
$('#id_color_selector2').colorselector();
$('#id_color_selector3').colorselector();
...

I usually write a piece of code in a separate .js file and include it through the Media class.
...
    class Media:
        js = (
            '/static/colorwidget/js/my_color_widget.js',
        )
...

Here I run into two problems:
Firstly, when adding a widget, I have to go into the *.js file every time and add almost repetitive code to initialize the widget.
Secondly - the order of loading files. For example, I need the widget script in the standard admin panel to be loaded at the end of the page, and not at the beginning, otherwise my widget does not work. Now I just copy and edit standard templates, which is also not very convenient....
Thus, adding another widget, you need to edit several files and litter the project with repetitive code, which is not good. Who can suggest a more flexible solution? Thanks in advance.
In fact, we need automatic generation of javascript code for each added widget with the ability to specify the order in which it is loaded in the template.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question