[Answered ]-How to include js and css only once

2๐Ÿ‘

โœ…

I am a bit curious as to why you use includes. Although they do have some use cases, you should not be using them a lot. Anyway.

Django forms happen to have a feature that enables collecting assets
Basically, you should define form-specific media directly on the form, like this:

class MyForm(ModelForm):
    # whatever you have there, then
    class Media:
        css = {
            'screen': ('foo.css', 'bar.css'),
        }
        js = ('jquery.js', 'myform.js')

The point is they are collected by Django, and you can manipulate them in your view or your templatetag, or wherever you have access to all your forms. Suppose you have MyForm and MyOtherForm, you can do:

context['form_media'] = my_form.media + my_other_form.media

And the, in your root template, you can just do:

<head>
    {{ form_media }}
</head>

As long as you stick to this convention in all your views.

๐Ÿ‘คspectras

0๐Ÿ‘

django-sekizai should do the trick. With the tags provided by this app you can dynamically add script or media-resources to your document. Be sure to check the docs, too.

๐Ÿ‘คMischback

Leave a comment