Django Form Media Unification

I have several Django templates, some of which have different forms. Some forms use custom widgets that need their own JS and CSS resources. These resources are correctly specified in each form.media

The correct place I found to place all the media links is in the <head> , right above my own css file. This will allow me to override the appearance of custom widgets if I want. So there is something like in my templates:

 {% block form_media %} {{ form1.media }} {{ form2.media }} {% endblock %} 

(some templates have more than one shape)

Now, if both forms use the same widget, the same JS and CSS files will be referenced twice. It may not be good. Is there any reasonable way to combine all the links to the media?

It simply calls the special tag {% context_form_media %} , which will display media of all forms in the context of the request.

+4
source share
1 answer

You can do this with blocks and inheritance.

base.html:

 <head> {% block form_css %} {# base css #} {% endblock form_css %} {# rest of head #} </head> {# rest of html #} 

any form.html:

 {% extends "base.html" %} {% block form_css %} {# your form css #} {% endblock form_css %} {# your form #} 

Thus, you can enter only css / js applicable for this page. If you also want to include everything at the top for the block, you can start it with {{block.super}}.

-1
source

All Articles