{"id":120253,"date":"2024-12-18T00:46:04","date_gmt":"2024-12-18T00:46:04","guid":{"rendered":"\/tutorials\/?p=120253"},"modified":"2024-12-20T12:09:38","modified_gmt":"2024-12-20T12:09:38","slug":"django-static-files","status":"publish","type":"post","link":"\/ph\/tutorials\/django-static-files","title":{"rendered":"How to handle static files in Django"},"content":{"rendered":"<p>Django provides a simple and efficient way to manage static files, such as CSS, JavaScript, and images, which are an important part of an application or a website.<\/p><p>In this tutorial, we will explain how to handle Django static files to ensure they are properly served and organized during development and deployment.<\/p><p>\n\n\n\n\n\n\n<\/p><h2 class=\"wp-block-heading\" id=\"h-setting-up-static-files-in-django\">Setting up static files in Django<\/h2><p>Below you&rsquo;ll find instructions on how you can set up and configure static files.<\/p><h3 class=\"wp-block-heading\" id=\"h-configuring-static-files-in-settings-py\">Configuring static files in settings.py<\/h3><p>To manage static files in Django, you need to configure your project to know where to look for and serve them. You can do so by specifying the <strong>Static URL<\/strong> and<strong> Directory<\/strong> in <strong>settings.py<\/strong>.<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># settings.py\nSTATIC_URL = '\/static\/'\nSTATICFILES_DIRS = [\n    BASE_DIR \/ \"static\",  # Optional: Add this if you want to store static files in a 'static' folder within your project\n]<\/pre><p>The <strong>STATIC_URL <\/strong>parameter defines the URL prefix Django will use when serving static files. Meanwhile, <strong>STATICFILES_DIRS<\/strong> specifies additional directories where Django will look for the files.<\/p><h3 class=\"wp-block-heading\" id=\"h-app-specific-static-files\">App-specific static files<\/h3><p>By default, Django will look for static files inside each app&rsquo;s <strong>static <\/strong>directory. For example, if you have an app named <strong>myapp<\/strong>, you can create a folder structure like this:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">myapp\/\n&#9474;\n&#9500;&#9472;&#9472; static\/\n&#9474;   &#9492;&#9472;&#9472; myapp\/\n&#9474;       &#9492;&#9472;&#9472; style.css\n&#9492;&#9472;&#9472; views.py<\/pre><p>Django will automatically recognize and serve these files during development.<\/p><h2 class=\"wp-block-heading\" id=\"h-linking-static-files-in-templates\">Linking static files in templates<\/h2><p>To use static files in your <a href=\"\/ph\/tutorials\/working-with-django-templates\">Django templates<\/a>, you must first load Django&rsquo;s <strong>{% static %}<\/strong> template tag. Then, you can reference your static files by their relative paths:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n    &lt;meta charset=\"UTF-8\"&gt;\n    &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n    &lt;title&gt;Home Page&lt;\/title&gt;\n    {% load static %}\n    &lt;link rel=\"stylesheet\" href=\"{% static 'myapp\/style.css' %}\"&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n    &lt;h1&gt;Welcome to My Django App&lt;\/h1&gt;\n    &lt;img src=\"{% static 'myapp\/images\/logo.png' %}\" alt=\"Logo\"&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;<\/pre><p>Here&rsquo;s the explanation of the static tags:<\/p><ul class=\"wp-block-list\">\n<li><strong>{% load static %}<\/strong>: Loads the static files template tag.<\/li>\n\n\n\n<li><strong>{% static &lsquo;myapp\/style.css&rsquo; %}<\/strong>: Resolves the path to the <strong>style.css<\/strong> file in the <strong>static\/myapp<\/strong> directory.<\/li>\n\n\n\n<li><strong>{% static &lsquo;myapp\/images\/logo.png&rsquo; %}<\/strong>: Resolves the path to an image file.<\/li>\n<\/ul><h2 class=\"wp-block-heading\" id=\"h-collecting-static-files-for-deployment\">Collecting static files for deployment<\/h2><p>During development, Django serves static files automatically when <strong>DEBUG = True<\/strong>. In production, however, you must collect all static files from various locations and store them in a single directory that your web server can find.<\/p><h3 class=\"wp-block-heading\" id=\"h-configuring-static-root-directory\">Configuring static root directory<\/h3><p>To configure the static root directory, Django provides the <strong>collectstatic <\/strong>management command.<\/p><p>Before using it, make sure you have included <strong>django.contrib.staticfiles<\/strong> in the<strong> INSTALLED_APPS <\/strong>setting of <strong>settings.py<\/strong>:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">INSTALLED_APPS = [\n    # Other installed apps\n    'django.contrib.staticfiles',\n]<\/pre><p>Now, configure the <strong>Static Root Directory<\/strong> in <strong>settings.py<\/strong>. This is the folder Django will use to collect static files for deployment.<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">STATIC_ROOT = BASE_DIR \/ 'staticfiles'<\/pre><p>During deployment, Django won&rsquo;t serve the static files anymore and your web server will take over. If we use the default<strong> static<\/strong> directory in the Django app.<\/p><h3 class=\"wp-block-heading\" id=\"h-running-the-collectstatic-command\">Running the collectstatic Command<\/h3><p>The <strong>collestatic<\/strong> command collects all static files from each app&rsquo;s <strong>static <\/strong>directory and any additional locations specified in <strong>STATICFILES_DIRS<\/strong>.Then, it stores them in the <strong>STATIC_ROOT<\/strong> directory.<\/p><p>Here&rsquo;s how to run the <strong>collectstatic<\/strong> command:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">python manage.py collectstatic<\/pre><h2 class=\"wp-block-heading\" id=\"h-serving-static-files-during-development\">Serving static files during development<\/h2><p>After setting up the root static directory and collecting all the files, configure your web server to serve them. Depending on your web server, the configuration might differ.<\/p><p>For example, here&rsquo;s how the configuration might look for NGINX:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">erver {\n    listen 80;\n    server_name yourdomain.com;\n\n    location \/static\/ {\n        alias \/path\/to\/your\/project\/staticfiles\/;  # The path to STATIC_ROOT\n    }\n\n    location \/ {\n        proxy_pass http:\/\/127.0.0.1:8000;  # Pass requests to Django app\n    }\n}<\/pre><p>In this configuration, NGINX serves static files directly from the<strong> \/static\/<\/strong> directory while forwarding all other requests to the Django application.<\/p><p>By properly managing static files in Django, you ensure that your application not only looks good with styles and images but also performs efficiently when deployed.<\/p><h2 class=\"wp-block-heading\" id=\"h-caching-static-files\">Caching static files<\/h2><p>Since static files look the same whenever users access them, caching them is a great strategy for improving your website&rsquo;s loading speed. However, you must configure it on your web browser since Django can&rsquo;t serve those files directly.<\/p><p>To enable caching, we must add the <strong>cache-control <\/strong>header to tell users&rsquo; web browser that they can store the static content for reuse.<\/p><p>For NGINX, you can enable it by adding the following code into your configuration file. Make sure to add this after the <strong>alias<\/strong>:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"> expires 30d;  # Cache for 30 days\n        add_header Cache-Control \"public, max-age=2592000, immutable\"; <\/pre><p>To further optimize your caching, you can use Django&rsquo;s <strong>ManifestStaticFilesStorage<\/strong>. It hashes your static files, meaning their name will change automatically after you modify their content.<\/p><p>Hashing enables users&rsquo; web browsers to store the cache as long as possible until it reaches the maximum age to maintain optimal loading time. Browsers will only download the new files when their name changes.<\/p><p>You can enable <strong>ManifestStaticFilesStorage <\/strong>by adding the following code in your<strong> settings.py file:<\/strong><\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'<\/pre><h2 class=\"wp-block-heading\" id=\"h-integrating-third-party-static-libraries\">Integrating third-party static libraries<\/h2><p>To improve your development efficiency, Django lets you include static files from third-party libraries. For example, you can integrate<strong> Bootstrap <\/strong>to add CSS or<strong> JQuery<\/strong> for JavaScript.<\/p><p>There are different ways to do so, but manually adding the library files to your Django project is the most common. Moreover, the steps are the same regardless of the library.<\/p><p>For example, here&rsquo;s how to install Bootstrap in your Django project:<\/p><ol class=\"wp-block-list\">\n<li>Download the <a href=\"https:\/\/getbootstrap.com\/docs\/4.0\/getting-started\/download\/\" target=\"_blank\" rel=\"noopener\">compiled CSS and JS version<\/a> of Bootstrap:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">wget https:\/\/github.com\/twbs\/bootstrap\/releases\/download\/v4.0.0\/bootstrap-4.0.0-dist.zip<\/pre><ol start=\"2\" class=\"wp-block-list\">\n<li>Extract the downloaded archive file using this command:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">unzip bootstrap-4.0.0-dist.zip<\/pre><ol start=\"3\" class=\"wp-block-list\">\n<li>Create a <strong>static <\/strong>folder inside your Django project&rsquo;s root directory in the same location as <strong>manage.py<\/strong>. Skip this step if you have the folder already.<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">mkdir myapp\/static<\/pre><ol start=\"4\" class=\"wp-block-list\">\n<li>The archive we extracted earlier yielded two folders called<strong> css<\/strong> and <strong>js<\/strong>. Move them to the static folder using these commands:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">mv css myapp\/static\nmv js myapp\/static<\/pre><ol start=\"5\" class=\"wp-block-list\">\n<li>Open <strong>settings.py<\/strong> using a text or code editor.<\/li>\n\n\n\n<li>Change the <strong>STATIC_URL<\/strong> value to <strong>\/static\/<\/strong>. If you can&rsquo;t find the parameter, add it manually:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">STATIC_URL = '\/static\/'<\/pre><ol start=\"7\" class=\"wp-block-list\">\n<li>Save the changes. <\/li>\n<\/ol><p>Now you can load static files from your library by calling them using the<strong> {% static %} <\/strong>tag like the following example:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;head&gt;\n    &lt;title&gt;My Django Project&lt;\/title&gt;\n    &lt;link rel=\"stylesheet\" href=\"{% static 'css\/bootstrap.min.css' %}\"&gt;\n&lt;\/head&gt;<\/pre><h2 class=\"wp-block-heading\" id=\"h-conclusion\">Conclusion<\/h2><p>Static files like CSS, JavaScript, and images are important elements in a web application. In Django, you can manage it efficiently using the built-in features and command utility.<\/p><p>In development, Django static files are located inside your app&rsquo;s <strong>static<\/strong> folder. By editing the <strong>settings.py<\/strong> file, you can specify additional folders for storage and set URLs that will serve them. To load static files, use the <strong>{% static %}<\/strong> tag in your template.<\/p><p>During deployment, collect the files into the <strong>root <\/strong>folder using the <strong>collectstatic<\/strong> command, so your web browser can serve them. You can also integrate third-party libraries like <strong>JQuery<\/strong> and enable Django&rsquo;s built-in caching feature to optimize your static content.<\/p><h2 class=\"wp-block-heading\" id=\"h-how-to-handle-django-static-files-faqs\">How to handle Django static files FAQs<\/h2><div class=\"schema-faq wp-block-yoast-faq-block\"><div class=\"schema-faq-section\" id=\"faq-question-1734482127487\"><h3 class=\"schema-faq-question\">What are static files in Django?<\/h3> <p class=\"schema-faq-answer\">In Django, static files are assets like CSS, JavaScript, and images that are not dynamically generated by the backend but are essential for the front end of a web application. They don&rsquo;t change with each request, so they&rsquo;re &ldquo;static&rdquo; and are usually served as-is to users. <\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1734482138385\"><h3 class=\"schema-faq-question\">How to serve static files in Django?<\/h3> <p class=\"schema-faq-answer\">To serve static files in Django, set <strong>STATIC_URL<\/strong> and <strong>STATICFILES_DIRS<\/strong> in <strong>settings.py<\/strong>, which will serve and store the CSS, JavaScript, and images. During development, Django serves these files automatically. In production, run<strong> python manage.py collectstatic<\/strong> to collect all static files in <strong>STATIC_ROOT<\/strong> for your web server.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1734482150098\"><h3 class=\"schema-faq-question\">Can I use CDN for Django static files?<\/h3> <p class=\"schema-faq-answer\">Yes, you can use a CDN for Django static files by setting <strong>STATIC_URL<\/strong> to the <strong>CDN URL<\/strong> in <strong>settings.py<\/strong>. After running<strong> collectstatic<\/strong> to gather files, upload them to the CDN. This approach improves load times and reduces server load by delivering assets through a global network.<\/p> <\/div> <\/div>\n","protected":false},"excerpt":{"rendered":"<p>Django provides a simple and efficient way to manage static files, such as CSS, JavaScript, and images, which are an important part of an application or a website. In this tutorial, we will explain how to handle Django static files to ensure they are properly served and organized during development and deployment. Setting up static [&#8230;]<\/p>\n<p><a class=\"btn btn-secondary understrap-read-more-link\" href=\"\/ph\/tutorials\/django-static-files\">Read More&#8230;<\/a><\/p>\n","protected":false},"author":185,"featured_media":87036,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"How to handle static files in Django","rank_math_description":"Static files, like CSS, JavaScript, and images, are important for web apps. Learn how to manage them effectively in Django with this guide.","rank_math_focus_keyword":"django static files","footnotes":""},"categories":[22641,22639],"tags":[],"class_list":["post-120253","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-pre-installed-applications","category-vps"],"hreflangs":[{"locale":"en-US","link":"https:\/\/www.hostinger.com\/tutorials\/django-static-files","default":0},{"locale":"en-UK","link":"https:\/\/www.hostinger.com\/uk\/tutorials\/django-static-files","default":0},{"locale":"en-MY","link":"https:\/\/www.hostinger.com\/my\/tutorials\/django-static-files","default":0},{"locale":"en-PH","link":"https:\/\/www.hostinger.com\/ph\/tutorials\/django-static-files","default":0},{"locale":"en-IN","link":"https:\/\/www.hostinger.com\/in\/tutorials\/django-static-files","default":0},{"locale":"en-CA","link":"https:\/\/www.hostinger.com\/ca\/tutorials\/django-static-files","default":0},{"locale":"en-AU","link":"https:\/\/www.hostinger.com\/au\/tutorials\/django-static-files","default":0},{"locale":"en-NG","link":"https:\/\/www.hostinger.com\/ng\/tutorials\/django-static-files","default":0}],"_links":{"self":[{"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/posts\/120253","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/users\/185"}],"replies":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/comments?post=120253"}],"version-history":[{"count":4,"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/posts\/120253\/revisions"}],"predecessor-version":[{"id":120602,"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/posts\/120253\/revisions\/120602"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/media\/87036"}],"wp:attachment":[{"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/media?parent=120253"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/categories?post=120253"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.hostinger.com\/ph\/tutorials\/wp-json\/wp\/v2\/tags?post=120253"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}