Как подключить js к django

от admin

Django Adding JS file

Adding js files in Django project is done exactly the same way as adding css files in Django:

Static files, like css, js, and images, goes in the static folder. If you do not have one, create it in the same location as you created the templates folder:

Add a .js file in the static folder, name it myfirst.js :

Open the JS file and insert the following:

Modify the Template

Now you have a js file, with a JavaScript function. The next step will be to include this file in a HTML template:

Open the HTML file and add the following:

And, add a button with a onclick event that triggers the function:

Restart the server for the changes to take effect:

Example

Didn’t Work?

Make sure that DEBUG = True in the settings.py file, otherwise the example will fail in development.

Set the DEBUG property to True :

Handling Static Files

When your website is in production, and open for everyone, static files are handled differently than they are in development.

You will learn how to deploy the website to production later in this tutorial, and you will learn how to handle static files in production then.

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get certified
by completing
a course today!

Subscribe

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

django how to include javascript in template

I’m starting a project and following the documentation I didn’t succeed to include javascript.

Here is my settings:

So I have a static folder create in my project with a javascript file.

and in my template: this is myproject/templates/base.html:

My other template:

I have the «hello world» on

but i do not have my image or script.

I tried so many different things but I never succeed

5 Answers 5

urls.py

settings.py

base.html

Your title tag was not closed.

Charlesthk's user avatar

Your template should say <% load staticfiles %>instead of

Also, os.path.join(BASE_DIR, «static»), only looks for static files in your apps, as in app/static/app/static.js . If you have static files that do not belong to any specific app, but rather to the project, you need to add the folder explicitly. See point 4 of ‘Configuring static files’ on the docs page I mentioned.

Jorick Spitzen's user avatar

From my understanding, the STATICFILES_DIRS should be in the settings.py and defined like this:

I am new at programing thus take my points with a pinch of salt. There i go. maybe you have more apps meaning you gotta check your tree as it should go as the django documentations points. meaning that you should have your_app/static/your_app/in here you must put three more folders corresponding to css, images and js all with their respective files.

Also notice that your static url should be named diferent than your static root. Once you have done this you must tell django where to find the statics for each app thus you gotta state it within the STATICFILES_DIRS.

After all this then you gotta run the collectstatic command.

I´m still missing the part in which you connect the js files of each app to the template.. so I cannot further help you dude. hope it helps a little bit

How to manage static files (e.g. images, JavaScript, CSS)¶

Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”. Django provides django.contrib.staticfiles to help you manage them.

This page describes how you can serve these static files.

Configuring static files¶

Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS .

In your settings file, define STATIC_URL , for example:

In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE .

Store your static files in a folder called static in your app. For example my_app/static/my_app/example.jpg .

Serving the files

In addition to these configuration steps, you’ll also need to actually serve the static files.

During development, if you use django.contrib.staticfiles , this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve() ).

This method is grossly inefficient and probably insecure, so it is unsuitable for production.

See How to deploy static files for proper strategies to serve static files in production environments.

Your project will probably also have static assets that aren’t tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories ( STATICFILES_DIRS ) in your settings file where Django will also look for static files. For example:

See the documentation for the STATICFILES_FINDERS setting for details on how staticfiles finds your files.

Static file namespacing

Now we might be able to get away with putting our static files directly in my_app/static/ (rather than creating another my_app subdirectory), but it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the best way to ensure this is by namespacing them. That is, by putting those static files inside another directory named for the application itself.

You can namespace static assets in STATICFILES_DIRS by specifying prefixes .

Serving static files during development¶

If you use django.contrib.staticfiles as explained above, runserver will do this automatically when DEBUG is set to True . If you don’t have django.contrib.staticfiles in INSTALLED_APPS , you can still manually serve static files using the django.views.static.serve() view.

This is not suitable for production use! For some common deployment strategies, see How to deploy static files .

For example, if your STATIC_URL is defined as static/ , you can do this by adding the following snippet to your urls.py :

This helper function works only in debug mode and only if the given prefix is local (e.g. static/ ) and not a URL (e.g. http://static.example.com/ ).

Also this helper function only serves the actual STATIC_ROOT folder; it doesn’t perform static files discovery like django.contrib.staticfiles .

Finally, static files are served via a wrapper at the WSGI application layer. As a consequence, static files requests do not pass through the normal middleware chain .

Читать:
Блютуз наушники не определяются как звуковое устройство

Serving files uploaded by a user during development¶

During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.views.static.serve() view.

This is not suitable for production use! For some common deployment strategies, see How to deploy static files .

For example, if your MEDIA_URL is defined as media/ , you can do this by adding the following snippet to your ROOT_URLCONF :

This helper function works only in debug mode and only if the given prefix is local (e.g. media/ ) and not a URL (e.g. http://media.example.com/ ).

Testing¶

When running tests that use actual HTTP requests instead of the built-in testing client (i.e. when using the built-in LiveServerTestCase ) the static assets need to be served along the rest of the content so the test environment reproduces the real one as faithfully as possible, but LiveServerTestCase has only very basic static file-serving functionality: It doesn’t know about the finders feature of the staticfiles application and assumes the static content has already been collected under STATIC_ROOT .

Because of this, staticfiles ships its own django.contrib.staticfiles.testing.StaticLiveServerTestCase , a subclass of the built-in one that has the ability to transparently serve all the assets during execution of these tests in a way very similar to what we get at development time with DEBUG = True , i.e. without having to collect them using collectstatic first.

Deployment¶

django.contrib.staticfiles provides a convenience management command for gathering static files in a single directory so you can serve them easily.

Set the STATIC_ROOT setting to the directory from which you’d like to serve these files, for example:

Run the collectstatic management command:

This will copy all files from your static folders into the STATIC_ROOT directory.

Use a web server of your choice to serve the files. How to deploy static files covers some common deployment strategies for static files.

Making Django and Javascript work nicely together

Backend and frontend cooperation may not be an easy task. For example in javascript code you may need some URLs to views or to icons required for some widgets. You can hardcode it or cleverly pass required data from backend to frontend. Also AJAX requests often want batches of data in JSON format. There is a way to make it quickly and clean. In this article I’ll show some Django applications and solutions for much easier backend — frontend cooperation.

django-javascript-settings

Next add ‘javascript_settings’, to INSTALLED_APPS.

In your main HTML template add:

We got a «configuration» variable with an empty array.

To add something to that array you need to define a javascript_settings function in urls.py of your django application. This function has to return a dictionary:

django-javascript-settings can be used to pass view URLs (using reverse function), urls to needed graphics, or rendered templates and so on.

AJAX Requests

In the «static» folder of my application I created scripts.js file in which I’ll write some jQuery code that will make an AJAX request to a given view.

The views look like so:

This covers all the elements. The request should now work and you can check it in Firebug or other browser developers console. The request should return «ok» from the view.

This simple code makes a GET request. Quite often POST requests are needed — like when some data is sent. jQuery part is very easy:

In «AjaxView» we change «get» to «post» and reload the page. The AJAX request should fail — 403, «CSRF verification failed. Request aborted.». We made a POST request without the csrf token (what we put in forms). You could use csrf_exempt on the view but that isn’t the best solution for this problem.

In csrf Django documentation we can find a solution. We have to set X-CSRFToken header with the csrf cookie value. Using jQuery Cookie it will be easy:

We have a fully working AJAX request. Now it’s time to use JSON to get a batch of data from the view.

Just import «json» module and modify the view to:

Django-annoying

django-annoying is a set of decorators and helpers shortening some common tasks. We can use the ajax_request decorator to improve our view. If we use this decorator on a view it has to return a dictionary. The decorator will encode it to JSON and will return a JsonResponse (like HttpResponse but with correct JSON mimetype).

We can instal django-annoying the usuall way:

Basics of Ember.js application development

After setting up the base of our ember application we can start doing something more with it. For my tutorials I’ve picked AdminLTE template to make a admin panel alike application.

Ember application structure

Ember.js applications are divided into multiple files and folders. All of which makes sense when we get to know what is where, so lets take a look on Ember application structure.

Setting up ember-cli development environment with ember 2.1

In a series of tutorials starting with this one I’ll try to showcase ember.js framework for building fronted web applications. As a backend there will be Django Rest Frameowork and more.

As times change and JavaScript frameworks don’t just download to your static folder I’ll start with setting up Ember.js development environment with ember-cli.

Check out PyCon PL 2015 agenda

The PyCon PL 2015 will be held in Hotel Ossa Congress & Spa located in Ossa on October 15th through October 18th. The conference is held in Poland but consists of two blocks of talks — English and Polish, so non-Polish speaking attendees can benefit from it too.

The agenda and other details can be found on the conference website.

Squashing and optimizing migrations in Django

With Django 1.7 we got built in migrations and a management command to squash a set of existing migrations into one optimized migration — for faster test database building and to remove some legacy code/history. Squashing works, but it still has some rough edges and requires some manual work to get the best of a squashed migration. Here are few tips for squashing and optimizing squashed migrations.

Simple Django applications for writing Facebook applications and authentication

Creating Facebook applications or integrating websites with Facebook isn’t complex or very time consuming. In case of Django there is for example very big django-facebook package that provides a lot of Facebook related features.

Pozytywnie.pl, a company I work with released a set of small applications that were used internally to make Facebook applications as well as Facebook authentication integrations. In this article I’ll showcase those applications.

RkBlog — riklaunim@gmail.com. Hosting megiteam.pl.

Site uses third party cookies and traffic analytics. No login or registration is required. Site uses Disqus third party widget for comments.

Related Posts