0

I would like to know how to properly attach a media files (css / js) for different subpages.

I have a dilemma between: Using {% block %}<script type="text/javascript" src="{% static 'js/script.js' %}"></script>{% endblock %} in template files. Or register function like attach_media(type, url) and use it in views.py.

There is still a class "Media" for forms, where I can:

associate different files – like stylesheets and scripts – with the forms and widgets that require those assets

But at the moment I'm not sure in every view I'll use the form.

Which solution is best?

user3041764
  • 817
  • 10
  • 35

2 Answers2

1

The first solution (to add static files in templates) is the most commonly used.

utkbansal
  • 2,787
  • 2
  • 26
  • 47
1

You need to distinguish between what you're trying to do, If your trying to reference static assets in a template then you need to use the static template tag.

The form's media class is there to specify files that are required in order for your form instances to function as you expect.

Sayse
  • 42,633
  • 14
  • 77
  • 146
  • I will use an example: I would like include **client.js** only on **client.html**, so it does not load any on other subpages. I would do it in such a way as easy and convenient. What do you think about register function `attach_media` and specify media in views.py? – user3041764 Dec 11 '15 at 12:09
  • @user3041764 - That sounds like it has nothing to do with a form so you won't even be able to use the media class – Sayse Dec 11 '15 at 12:11
  • @user3041764 - Further more, your view on the most part shouldn't care about how its displayed – Sayse Dec 11 '15 at 12:11
  • class Media seemed to me simple, already implemented solution, so I wanted to use them. Subpage clients.html will table where I was running operations (I will manage records), so we have a form. – user3041764 Dec 11 '15 at 12:15
  • @user3041764 - The way you're describing it the js file is related to the html page, rather than the form. – Sayse Dec 11 '15 at 12:16
  • 1
    You're right, so I was not convinced to this solution. Thank you for the discussion. – user3041764 Dec 11 '15 at 12:18