<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hojiakbar Barotov on Medium]]></title>
        <description><![CDATA[Stories by Hojiakbar Barotov on Medium]]></description>
        <link>https://medium.com/@hmbarotov?source=rss-1e36d397faf9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Cyl7mo0l9H9nCgDwMaRk0Q.png</url>
            <title>Stories by Hojiakbar Barotov on Medium</title>
            <link>https://medium.com/@hmbarotov?source=rss-1e36d397faf9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:07:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hmbarotov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Speed Up Your Django Tests: From 200 Seconds to 31]]></title>
            <link>https://medium.com/@hmbarotov/speeding-your-django-tests-quick-wins-234179c4cd39?source=rss-1e36d397faf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/234179c4cd39</guid>
            <category><![CDATA[quick-wins]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[speed-up]]></category>
            <category><![CDATA[django-tests]]></category>
            <dc:creator><![CDATA[Hojiakbar Barotov]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 16:05:55 GMT</pubDate>
            <atom:updated>2026-06-26T05:36:24.543Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical benchmark of test-only settings, database reuse, and parallel execution on a 634-test Django project.</p><figure><img alt="Speed Up Your Django Tests: From 200 Seconds to 31" src="https://cdn-images-1.medium.com/max/1024/1*oy-KfGy-wNpea18kATTPbg.png" /><figcaption>Speed Up Your Django Tests: From 200 Seconds to 31</figcaption></figure><p>Slow tests weaken the feedback loop. When a full suite takes several minutes, developers run it less often and discover regressions later.</p><p>Sinxron, my Django-based ERP for education centers, currently has 634 tests. On my laptop, a full run took about 200 seconds. With a dedicated test settings module and Django’s built-in runner options, I reduced that to 31 seconds — roughly 6.4× faster.</p><p>This article walks through the quick, easy changes, shows what each one did on my project, and separates genuine speedups from changes that made little or no difference. The numbers are specific to my codebase and machine, but the techniques are straightforward to benchmark in most Django projects.</p><p>The approach is based mostly on <a href="https://adamj.eu/">Adam Johnson’</a>s <a href="https://adamchainz.gumroad.com/l/suydt"><em>Speed Up Your Django</em></a><em> Tests</em>. His book goes beyond these quick wins into profiling, mocking, test design (AAA), and reducing unnecessary database work.</p><p>For a complete understanding and info, please invest in <a href="https://adamchainz.gumroad.com/l/suydt">his book</a>.</p><h3>Test setup and baseline</h3><p>Sinxron uses Django, HTMX, Alpine.js, PostgreSQL, and Docker. The suite runs with Django’s built-in, unittest-based test runner. My dev environment is Linux Mint.</p><p>For testing, I use Django’s own test framework. It is purely because of my experience and comfort with it.</p><p>At this time of writing, it has 634 <strong>unit tests</strong> in total. Without any optimizations, it run in 200 seconds:</p><figure><img alt="The full test run with no optimizations" src="https://cdn-images-1.medium.com/max/1024/1*Buu_RW2_3sUqDVHYKfGatw.png" /><figcaption>The full test run with no optimizations</figcaption></figure><p>On average, 200 seconds. Not bad, but in a bigger codebase this could easily have been 20 minutes.</p><p>We are focusing on quick wins, can be split into two: <strong>configuration</strong> and <strong>Django’s test-runner options</strong>. Let’s focus on the first.</p><h3><strong>Configuration</strong></h3><p>Configuration refers to the settings you modify for testing so that your Django runs tests faster. Production, default Django is very secure and performant; you want to modify some settings for faster test runs.</p><p>These include password hashers, dummy cache, storages, and others.</p><p>Create settings_test.py next to the project’s normal settings file. A separate module keeps test-only compromises out of production and gives the suite one predictable configuration.</p><pre># django_project/settings_test.py<br><br>from .settings import *<br><br>DEBUG = False</pre><p>Why setting DEBUG to False? Django already runs tests with <a href="https://docs.djangoproject.com/en/6.0/topics/testing/overview/#other-test-conditions">DEBUG=False</a>, regardless of the value in the normal settings file. You can set it explicitly for clarity, but it does not materially change the runtime.</p><p>DEBUG is turned off because we do not need additional loggers, tracebacks, or detailed information useful for development. Additionally, by turning DEBUG off, you will be testing close to production Django.</p><p>Now, let’s get to the optimizations:</p><h4>Use a faster password hasher</h4><p>Django’s default hasher for passwords, PBKDF2 is very secure, but has no benefits to a sandboxed testing environment. We can significantly increase the speed by switching to MD5 . It means Django now becomes significantly faster for creating and hashing users and their passwords.</p><pre># django_project/settings_test.py<br><br>from .settings import *<br><br>DEBUG = False<br><br>PASSWORD_HASHERS = [<br>    &quot;django.contrib.auth.hashers.MD5PasswordHasher&quot;, # new<br>]</pre><p>After adding the faster hasher:</p><pre>$ docker compose exec web python manage.py test \<br>--settings=django_project.settings_test<br>Found 634 test(s).<br>Creating test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>........................................................................<br>........................................................................<br>........................................................................<br>........................................................................<br>........................................................................<br>........................................................................<br>........................................................................<br>........................................................................<br>..........................................................<br>----------------------------------------------------------------------<br>Ran 634 tests in 130.546s<br><br>OK<br>Destroying test database for alias &#39;default&#39;...</pre><p>2 simple configurations and now our test suite is 35% (or 70 seconds) faster. Quick win, isn’t it?</p><p>However, keep two caveats in mind:</p><ul><li>Do not use this setting in production.</li><li>If fixtures contain passwords encoded with another algorithm, keep that hasher in PASSWORD_HASHERS as well.</li></ul><p>Additionally, when a test only needs an authenticated user and does not need to exercise the login flow, self.client.force_login(user) can avoid password hashing altogether.</p><h4>Replace a remote cache with local memory</h4><p>Instead of setting up, connecting, and managing Redis or Memcached, you can use Django’s default in-memory cache. Note that if you are using the django-redis package, you will have to handle it differently.</p><pre># django_project/settings_test.py<br><br>from .settings import *<br><br>DEBUG = False<br><br>PASSWORD_HASHERS = [<br>    &quot;django.contrib.auth.hashers.MD5PasswordHasher&quot;,<br>]<br><br>CACHES = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;django.core.cache.backends.locmem.LocMemCache&quot;,<br>        &quot;LOCATION&quot;: &quot;test-cache&quot;,<br>    }<br>} # new</pre><p>Although I do not use caching yet for my platform, I nevertheless added it as it is a common and sensible configuration for a default Django project.</p><pre>$ docker compose exec web python manage.py test \<br>--settings=django_project.settings_test<br>Found 634 test(s).<br>Creating test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>...........................................................................<br>...........................................................................<br>...........................................................................<br>...........................................................................<br>...........................................................................<br>...........................................................................<br>...........................................................................<br>...........................................................................<br>..................................<br>----------------------------------------------------------------------<br>Ran 634 tests in 130.257s<br><br>OK<br>Destroying test database for alias &#39;default&#39;...</pre><p>Unsurprisingly, this had no effect on my test suite because I do not have any use of caching yet.</p><p>Note that Django does not create a separate cache for tests or clear the cache after every test. Tests that mutate cache state should clean it up <strong>explicitly</strong>.</p><h4>Keep uploaded files in memory</h4><pre># django_project/settings_test.py<br><br>from .settings import *<br><br>DEBUG = False<br><br>PASSWORD_HASHERS = [<br>    &quot;django.contrib.auth.hashers.MD5PasswordHasher&quot;,<br>]<br><br>CACHES = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;django.core.cache.backends.locmem.LocMemCache&quot;,<br>    }<br>}<br><br>STORAGES = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;django.core.files.storage.InMemoryStorage&quot;,<br>    },<br>    &quot;staticfiles&quot;: {<br>        &quot;BACKEND&quot;: &quot;django.contrib.staticfiles.storage.StaticFilesStorage&quot;,<br>    },<br>} # new</pre><p>Why? You want to use in-memory <em>“everything” </em>so that<em> </em>Django can run it in RAM, in memory. The default file storage is now in memory with DEFAULT_FILE_STORAGE .</p><p>I also included STORAGES config because production Django typically uses ManifestStaticFilesStorage for static files, which added hash to the end of the files, making it essentially infinitely new and cached. But it requires collecting static files. That’s why we use StaticFilesStorage for testing and development.</p><pre>$ docker compose exec web python manage.py test \<br>--settings=django_project.settings_test<br>Found 634 test(s).<br>Creating test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>..................<br>----------------------------------------------------------------------<br>Ran 634 tests in 119.999s<br><br>OK<br>Destroying test database for alias &#39;default&#39;...</pre><p>A small improvement of 10s. Nice. A project without much static or uploaded media will likely not see an improvement.</p><p>5. <strong>Use in-memory email backend:</strong></p><pre># django_project/settings_test.py<br><br>from .settings import *<br><br>DEBUG = False<br><br>PASSWORD_HASHERS = [<br>    &quot;django.contrib.auth.hashers.MD5PasswordHasher&quot;,<br>]<br><br>CACHES = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;django.core.cache.backends.locmem.LocMemCache&quot;,<br>    }<br>}<br><br>DEFAULT_FILE_STORAGE = &quot;django.core.files.storage.InMemoryStorage&quot;<br>STORAGES[&quot;staticfiles&quot;] = {<br>    &quot;BACKEND&quot;: &quot;django.contrib.staticfiles.storage.StaticFilesStorage&quot;,<br>}<br><br>EMAIL_BACKEND = &quot;django.core.mail.backends.locmem.EmailBackend&quot; # new</pre><p>Spoiler alert: Django test runner already does this <a href="https://docs.djangoproject.com/en/6.0/topics/testing/tools/#email-services">behind the scenes</a>, so it won’t have any effect on the speed. But it is better explicit than implicit, especially when you use a test framework other than Django’s own.</p><h4><strong>Use in-memory queue</strong></h4><p>Be careful about this because this has many gotchas and is still a work-in-progress.</p><pre># django_project/settings_test.py<br><br>from .settings import *<br><br>DEBUG = False<br><br>PASSWORD_HASHERS = [<br>    &quot;django.contrib.auth.hashers.MD5PasswordHasher&quot;,<br>]<br><br>CACHES = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;django.core.cache.backends.locmem.LocMemCache&quot;,<br>    }<br>}<br><br>DEFAULT_FILE_STORAGE = &quot;django.core.files.storage.InMemoryStorage&quot;<br>STORAGES[&quot;staticfiles&quot;] = {<br>    &quot;BACKEND&quot;: &quot;django.contrib.staticfiles.storage.StaticFilesStorage&quot;,<br>}<br><br>EMAIL_BACKEND = &quot;django.core.mail.backends.locmem.EmailBackend&quot;<br><br>CELERY_ALWAYS_EAGER = True # new<br>CELERY_EAGER_PROPAGATES_EXCEPTIONS = True # new<br>CELERY_BROKER = &quot;memory://&quot; # new</pre><p>Why? This makes your Celery faster and its broker use memory. However, this is not a free, quick win. You have to use transaction.on_commit() with TestCase for this to work corretly.</p><p>In my case, because I have a very little usage of Celery (only for emails so far), it does not make much of a difference. But in a larger codebase, this would speed up your test time noticeably.</p><pre>$ docker compose exec web python manage.py test \ <br>--settings=django_project.settings_test<br>Found 634 test(s).<br>Creating test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>............................................................................<br>............................................................................<br>............................................................................<br>............................................................................<br>............................................................................<br>............................................................................<br>............................................................................<br>............................................................................<br>..........................<br>----------------------------------------------------------------------<br>Ran 634 tests in 113.248s<br><br>OK<br>Destroying test database for alias &#39;default&#39;...</pre><p>So, with these simple, fast configurations, we could decrease the testing time from 200s to 110s. 45% increase in speed. Mind-blowing.</p><p>There are some more specific wins that you can opt for. But not every quick win is applicable to everyone.</p><h3>Use Django’s test-runner options</h3><p>This relates to using CLI commands. Essentially, it boils down to keep <em>reusing the same database </em>and <em>using more of your CPU for parallel testing</em>. These are achieved by passing flags to the test runner command, such as</p><p>--keepdb and --parallel .</p><p>But, what about uv? It is a fast replacement for many Pythonic tools in most cases. You can absolutely use it. I actually run everything with uv appended for speed without complexity. But in the test case, it does not help for my case. Maybe in a larger codebase, uv might be the way.</p><p>Running with uv:</p><pre>$ docker compose exec web uv run manage.py test \<br>--settings=django_project.settings_test<br>Found 634 test(s).<br>Creating test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>............................................................................<br>............................................................................<br>............................................................................<br>............................................................................<br>............................................................................<br>............................................................................<br>............................................................................<br>............................................................................<br>..........................<br>----------------------------------------------------------------------<br>Ran 634 tests in 122.241s<br><br>OK<br>Destroying test database for alias &#39;default&#39;...</pre><p>Actually, this was slower than Python itself. It is most likely that the initial overhead of setting up uv was more than the benefits. This makes sense; testing is different than pip.</p><p>Still, in a larger codebase, you might find uv to be a speed gain.</p><h4>Preserve the test database between runs</h4><p>--keepdb preserves the test database <strong>between test-suite runs</strong>. It does not reuse data between individual tests; Django still provides test isolation.</p><pre>$ docker compose exec python manage.py test \<br>--settings=django_project.settings_test --keepdb<br>Found 634 test(s).<br>Using existing test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>..................<br>----------------------------------------------------------------------<br>Ran 634 tests in 116.475s<br><br>OK<br>Preserving test database for alias &#39;default&#39;...</pre><p>We are witnessing a diminishing returns curve. We have extracted the easy gains already. Reusing the database does not result in a big benefit for my platform because I only have 634 tests and a very small database compared to a mature codebase.</p><p>There was no measurable improvement in this project because the schema and migration setup were relatively small, and ordinary run-to-run variation was larger than the saving. On a mature project with a long migration history, skipping database creation and destruction can be much more valuable.</p><p>Django will apply unapplied migrations to the preserved database. If the database becomes inconsistent, delete it and let the runner recreate it.</p><h4>Check isolation before enabling parallel execution</h4><p>Parallel testing sounds so good, but it is actually quite difficult. Your unit tests should be isolated and independent of each other. Also, parallel testing did not work on Windows until Django 4.0. You have to install tblib for catching exceptions. Also, you cannot achieve a perfect N-time improvement because of overheads.</p><p>So, first of all, let’s run our tests in reverse to check for any parallel testing issues with the --reverse flag:</p><pre>$ docker compose exec python manage.py test \<br>--settings=django_project.settings_test \<br>--keepdb --reverse<br>Found 634 test(s).<br>Using existing test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>..................<br>----------------------------------------------------------------------<br>Ran 634 tests in 115.592s<br><br>OK<br>Preserving test database for alias &#39;default&#39;...</pre><p>Then, let’s shuffle our tests with --shuffle:</p><pre>$ docker compose exec python manage.py test \<br>--settings=django_project.settings_test \<br>--keepdb --shuffle<br>Using shuffle seed: 2125503403 (generated)<br>Found 634 test(s).<br>Using existing test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>.............................................................................<br>..................<br>----------------------------------------------------------------------<br>Ran 634 tests in 133.262s<br><br>OK<br>Used shuffle seed: 2125503403 (generated)<br>Preserving test database for alias &#39;default&#39;...</pre><p>I had already fixed parallel issues due to Adam Johnson’s book. But in your case, fix order-dependent failures before running the suite across multiple processes. A parallel suite magnifies hidden coupling around files, caches, global state, and shared external services.</p><h4>Run test cases in parallel</h4><p>Now, finally onto --parallel flag. By default, it uses all the available cores available. You can specify the number of cores to be used by passing--parallel=n . In my case, the Docker container is using 8 cores of my laptop.</p><p>First, we re-create our database for parallel testing to avoid any issues. Install tblib to see any exceptions raised during parallel testing. Fix them before running your tests.</p><p>Finally, run the test suite:</p><pre>$ docker compose exec web python manage.py test \ <br>--settings=django_project.settings_test \<br>--parallel --keepdb<br>Found 634 test(s).<br>Using existing test database for alias &#39;default&#39;...<br>Using existing clone for alias &#39;default&#39;...<br>Using existing clone for alias &#39;default&#39;...<br>Using existing clone for alias &#39;default&#39;...<br>Using existing clone for alias &#39;default&#39;...<br>Using existing clone for alias &#39;default&#39;...<br>Using existing clone for alias &#39;default&#39;...<br>Using existing clone for alias &#39;default&#39;...<br>Using existing clone for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>.........................................................................<br>.........................................................................<br>.........................................................................<br>.........................................................................<br>.........................................................................<br>.........................................................................<br>.........................................................................<br>.........................................................................<br>..................................................<br>----------------------------------------------------------------------<br>Ran 634 tests in 31.109s<br><br>OK<br>Preserving test database for alias &#39;default&#39;...<br>Preserving test database for alias &#39;default&#39;...<br>Preserving test database for alias &#39;default&#39;...<br>Preserving test database for alias &#39;default&#39;...<br>Preserving test database for alias &#39;default&#39;...<br>Preserving test database for alias &#39;default&#39;...<br>Preserving test database for alias &#39;default&#39;...<br>Preserving test database for alias &#39;default&#39;...<br>Preserving test database for alias &#39;default&#39;...</pre><p>Elegant, innit? We went from 200s to 30s. A 65% decrease in testing time with 1 hour of easy work. Parallelization was the biggest impact factor alongside the password hasher.</p><p>To wrap up:</p><p>Three changes mattered most in this project: a faster password hasher, in-memory file storage, and parallel execution. The cache, email, Celery, and database-preservation changes were useful only to the extent that the suite exercised those systems or paid their setup costs.</p><p>That is the broader rule: measure first, replace expensive test dependencies one at a time, and keep only the changes that produce a repeatable gain. Use --reverse and --shuffle to expose state leaks, then enable --parallel once the suite is reliably isolated.</p><p>That reduced the full run from about 200 seconds to 31.109 seconds — an approximately <strong>84% reduction in runtime</strong>, or about <strong>6.4× faster. </strong>All without heavy code changes.</p><p>The final command for this project became:</p><pre>$ docker compose exec web python manage.py test \<br>    --settings=django_project.settings_test \<br>    --keepdb \<br>    --parallel</pre><p>And I made an alias for it, <strong>dtest.</strong></p><p>The improvement matters beyond the benchmark. A 31-second suite is short enough to remain part of the normal development loop instead of becoming an interruption that developers postpone.</p><p>These are still the easy wins. The next step is to profile the slowest tests, reduce unnecessary database work, improve test-data setup, and reconsider tests that cover too much behavior at once. Adam Johnson’s <em>Speed Up Your Django Tests</em> is a strong guide to that deeper work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=234179c4cd39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My 20 Favorite Django Chat Episodes]]></title>
            <link>https://medium.com/@hmbarotov/my-20-favorite-django-chat-episodes-6b93556d06ca?source=rss-1e36d397faf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b93556d06ca</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[podcast-recommendations]]></category>
            <category><![CDATA[django-podcast]]></category>
            <category><![CDATA[django-chat]]></category>
            <dc:creator><![CDATA[Hojiakbar Barotov]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 03:14:06 GMT</pubDate>
            <atom:updated>2026-03-31T03:14:06.419Z</atom:updated>
            <content:encoded><![CDATA[<p>My personal favorite Django Chat podcast episodes after listening to all episodes.</p><figure><img alt="Django Chat Podcast Cover Image — Generated by Gemini" src="https://cdn-images-1.medium.com/max/1024/1*GRCjWYXOiF_8PWHsX7u7Kw.png" /><figcaption>Django Chat Podcast Cover Image — Generated by Gemini</figcaption></figure><p>I <a href="https://medium.com/@hmbarotov/asynchronous-podcast-downloader-with-python-a26f2ffff98a">wrote my own Python podcast downloader</a> to download all podcast episodes of the <a href="https://djangochat.com/">Django Chat</a> podcast (yes, I am old school). Run by two Django superstars, <a href="https://wsvincent.com/">William Vincent</a> and <a href="https://github.com/carltongibson">Carlton Gibson</a>, now for 7 years, it has become the de facto podcast for all things Django. Now, I am going to list my favorite episodes in this story.</p><p>I am first going to explain my obsession with podcasts and my selection criteria.</p><figure><img alt="Django Chat Podcast Logo" src="https://cdn-images-1.medium.com/max/600/0*eTZcWGJm7VqSPWCZ.jpg" /><figcaption>Django Chat Podcast Logo</figcaption></figure><h3>Why I Listen to Podcasts</h3><p>The reason is simple: I regularly commute, and this stretch of time can be quite productive with podcasts, especially when I am still early in my career. The best benefit of a podcast for me is to provide high-quality, curated information in a highly engaging conversational format.</p><p>For example, I learned a lot about Django’s internals, community, open-source, conferences, key people, trends, cool third-party projects, and various events. As a novice competent, I would not be able to find, let alone curate, such a useful list of information myself.</p><p>The same goes for the current podcast I now listen to — <a href="https://runninginproduction.com/">Running in Production</a>. Despite being a little bit outdated, it provides new, novel ways of running websites in production — not only in Django, but also in Elixir, JS, Ruby, and others.</p><p>By listening to a podcast during the commute, I get so many benefits for free. That’d be why I listen to tech podcasts.</p><h3>Selection Criteria</h3><p>As of this date, there are 198 episodes of Django Chat, with the first being in February, 2019. With so many high-quality episodes available, it was difficult to single out the top twenty.</p><p>But I decided that no deep technical episode was chosen. There are around 40 episodes dedicated for Django’s internals: Deployments, Admin, URLs, Security, Middleware, etc. If I included them, the list would include almost all of them. These deep dives are pure gold.</p><p>Also, I chose podcasts that were interesting, beneficial, significant, and had a “wow” effect.</p><p>With that in mind, here is my favorite 20 Django Chat episodes in the chronological order.</p><h3>20 Favorite Episodes</h3><h4>#1: Episode 008 — <a href="https://djangochat.com/episodes/untitled">Contributing to Django</a></h4><p>This episode is about open-source: how Django is run, how open-source works in the context of Django, and why getting involved in the OS community is beneficial for your career growth as well.</p><p>Django is one of the most welcoming tech communities out there; you can be part of this, while getting an invaluable sense of community, goodwill, and career skills.</p><p>I also started contributing in my own way: localizing third-party Django packages (allauth, django-debug-toolbar, and others) into my native language, Uzbek and started hanging out in the <a href="https://forum.djangoproject.com/">Django Forum</a> from time to time.</p><p>This episode is really worth listening.</p><h4>#2: Episode 021 — <a href="https://djangochat.com/episodes/django-co-creator-simon-willison">Django Co-Creator — Simon Willison</a></h4><p><a href="https://simonwillison.net/">Simon Willison</a> is literally the Batman of Django: one of the original creators of Django, a successful Y Combinator founder, a superstar programmer, a famed open-source coder, an avid writer on all things coding and AI, and the author of <a href="https://datasette.io/">Datasette</a>. I feel inspired just writing this.</p><p>In this episode, Simon talks about the origins of Django, his contributions, his startup, his work in <a href="https://www.eventbrite.com/">Eventbrite</a>, and async. It was one of the most inspiring and interesting episodes.</p><h4>#3: Episode 032 — <a href="https://djangochat.com/episodes/rails-django-david-heinemeier-hansson">Ruby on Rails &amp; Django— David Heinemeier Hansson</a></h4><p>No matter the podcast, when there is <a href="https://dhh.dk/">DHH</a>, you know you are in for a treat. His views might seem controversial, but he always bases his ideas in reality and reason. This is so much interesting especially when he is a prolific author, a successful entrepreneur, a racer, and the author of another highly popular web-framework, <a href="https://rubyonrails.org/">Ruby on Rails</a>.</p><p>Django is very similar to Ruby on Rails in the ground that both are batteries-included, full-stack web-frameworks. Both influence and are influenced by each other.</p><p>Hearing DHH’s views on batteries-included web frameworks is really worth pondering: instead of building a Lego building with 2x2 lego pieces, he advocates 64x64 pieces of wisdom.</p><h4>#4: Episode 037 — <a href="https://djangochat.com/episodes/how-django-experts-think">How Django Experts Think</a></h4><p>Django experts reflecting on how they became experts, but still do not feel like experts. William Vincent and Carlton Gibson are both accomplished, very experienced Django developers. In this conversation, they reflect on their learning journeys, their current views after years of working with Django, and the change in their preferences.</p><p>Taken in 2019, this particular episode is especially useful to newcomers to coding because of LLMs. Yes, LLMs can help and speed up a lot, but it will be on you to decide and grow at the end of the day.</p><h4>#5: Episode 049 — <a href="https://djangochat.com/episodes/growing-old-gracefully-as-a-programmer">Growing Old Gracefully as a Programmer</a></h4><p>Based on Carlton Gibson’s <a href="https://youtu.be/7WUFWmyk-HY?si=4n00X0sXPCsgBJ_X">conference talk in DjangoCon Europe 2018</a>, they talk about building and maintaining a fulfilling career in programming. Both hosts were in their early 40s at the time of recording, so this was relevant for them as well.</p><p>Although it is not particularly relevant for me, it talks about maintaining a work-life balance, burnouts, and different working environments. A cautionary tale.</p><h4>#6: Episode 056 — <a href="https://djangochat.com/episodes/google-summer-of-code-sage-abdullah">Google Summer of Code — Sage Abdullah</a></h4><p><a href="https://github.com/laymonage">Sage Abdullah</a> is originally from Indonesia, and now works for <a href="https://torchbox.com/">Torchbox</a> as a core contributor to its flagship open-source product — <a href="https://wagtail.org/">Wagtail CMS</a>.</p><p>He participated in the 2019 Google Summer of Code, and worked on cross-db JSONField support, which was merged in Django 3.1. He shares his experience studying formal computer science, learning multiple programming languages, building projects with Django and Flask, and his experience in GSC 2019.</p><h4>#7: Episode 063 — <a href="https://djangochat.com/episodes/roll-your-own-tech-job-erin-mullaney">Roll Your Own Tech Job — Erin Mullaney</a></h4><p>This episode is very interesting because it details the journey of a Django developer from studying computer science at university to working for <a href="https://www.caktusgroup.com/">Caktus Group</a> to setting out on her own as a freelancer.</p><p>This is particularly interesting because Erin Mullaney documents everything she did to set up her legal entity in the US, with supporting documents and a conference talk. She also compares and contrasts working for an established company and being her own boss.</p><p>Carlton Gibson, a veteran software developer and freelancer, also shares his experience in running your own legal entity and business as a freelancer.</p><h4>#8: Episode 095 — <a href="https://djangochat.com/episodes/htmx-carson-gross">htmx — Carson Gross</a></h4><p>htmx is the first successful implementation of HTML over the wire, and it has been welcomed so warmly in the Django world. Django defaults to server-side rendered HTML pages out of the box, and htmx makes it so easy and elegant to add interactivity without having to resort to JS frameworks and APIs.</p><p>That’s why so many tutorials, video courses, and materials have been produced for Django and htmx. Indeed, I myself have written one on <a href="https://medium.com/@hmbarotov/integrate-htmx-2-0-with-django-e7825b3cfadd">integrating htmx with Django</a>.</p><p>Carson Gross gives the history behind htmx, his views on HTML over the wire, and JS landscape. A fun, historic episode.</p><h4>#9: Episode 096 — <a href="https://djangochat.com/episodes/docker-flask-nick-janetakis">Docker &amp; Flask — Nick Janetakis</a></h4><p>Docker has become the de facto containerization software in the real world. Nick Janetakis was one of the first to create a deep dive into Docker with Flask.</p><p>Flask is a sister framework to Django; both are immensely popular, but have different approaches to web development. While Django is a structured, batteries-included, MVC framework, Flask is a lightweight, very customizable, micro web framework.</p><p>Django Chat hosts and the guest have an interesting discussion on creating content websites, running podcasts, and async.</p><p>In fact, my listening to <a href="https://runninginproduction.com/">Running in Production</a>, was directly the result of this episode.</p><h4>#10: Episode 101 — <a href="https://djangochat.com/episodes/from-beginner-to-software-engineering-manager-raymond-traylor">From Beginner to Software Engineering Manager — Raymond Traylor</a></h4><p>An unusual origin story that almost looks like a movie script: a talented salesman-entrepreneur turned into a Django developer into a software engineering manager over the years. The story of the guest resembles someone who came to coding for practical reasons: running his own e-commerce arbitrage business with Python.</p><p>Raymond Taylor shares his learning experience relatively late for programmers. William Vincent, a best-seller author of three Django books, then shares his experience as well.</p><h4>#11: Episode 114 — <a href="https://djangochat.com/episodes/star-wars-and-django">Star Wars and Django</a></h4><p>This one was a shock to me; yes, Django is very popular and used everywhere: blogs, CMS (Wagtail), social media websites (Instagram &amp; Pinterest), scientific backend and APIs.</p><p>Seeing Django being used for creative film industries was quite unexpected. But listening to the episode, it became clear that any distributed complex system needs a reliable, scalable, and robust backend — an area where Django excels.</p><h4>#12: Episode 116 — <a href="https://djangochat.com/episodes/read-the-docs-eric-holscher">Read The Docs — Eric Holscher</a></h4><p><a href="https://about.readthedocs.com/">Read the Docs</a> is the website developers visit everyday. It is a documentation website that is free for open-source projects and has a pricing plan for enterprise systems.</p><p>Eric Holscher shares his journey of building the website originally with Django, funding this website, EthicalAds, and others. Another really interesting take on open-source projects and ethical ads that do not track users.</p><h4>#13: Episode 128 — <a href="https://djangochat.com/episodes/postgres-craig-kerstiens">Postgres — Craig Kerstiens</a></h4><p>Postgres is the de facto database for Django. The framework has a dedicated contrib module for Postgres that includes lots of Postgres-specific features for Django, such as full-text search and specialized indexes.</p><p>Most of the time for most websites, Postgres works just fine for Django projects. However, if you are willing to dedicate time, there are lots of optimizations and cool features that you can do with Postgres.</p><p>Craig Kerstiens, being a Postgres dev, discusses managed databases — something developers love paying for because your data is your most important asset, and managing a database properly (security, backups, and updates) is no easy task.</p><p>This episode is really beneficial for Django devs getting more into databases.</p><h4>#14: Episode 130 — <a href="https://djangochat.com/episodes/sentry-david-cramer">Sentry — David Cramer</a></h4><p>One peculiar thing stood out as I listened to the Django Chat podcast: founders and entrepreneurs are quite different from the rest, in a good way. The co-founder of <a href="https://sentry.io/welcome/">Sentry</a>, David Cramer, talks about the value of computer science education vs experience, building Sentry from Django, hosting platforms, and not reinventing the wheel, especially in frontend.</p><p>With the sheer amount of their unique experience of running internet-scale websites and businesses, these coder entrepreneurs are quite vocal and unconventional in a good way. Maybe, it is because of their innate nature or learned experience.</p><p>In either case, it is almost mesmerizing to listen to David Cramer share his opinions on web-development.</p><h4>#15: Episode 151 — <a href="https://djangochat.com/episodes/web-security-mackenzie-jackson">Web Security — Mackenzie Jackson</a></h4><p>Security. The backbone of your website that Django provides hard batteries to do most of the heavy lifting. Hosts have a dedicated episode on <a href="https://djangochat.com/episodes/security">Django Security</a>, and this episode is logically a continuation of that episode in 2023.</p><p>Mackenzie is a developer advocate at GitGuardian, and he shares his experience finding and fixing security concerns, leaked keys, and other bugs on GitHub, his preference for environment variables for their simplicity for middle-sized websites, and ChatGPT as a potential security concern as a practitioner.</p><p>His article on “<a href="https://blog.gitguardian.com/chatgpt-security-concern/">Why ChatGPT is a security concern</a>” was very popular when LLMs were first becoming a mainstream.</p><h4>#16: Episode 162 — <a href="https://djangochat.com/episodes/michael-kennedy">Self-Hosted Open Source — Michael Kennedy</a></h4><p>Michael Kennedy is a fellow Python podcaster that runs <a href="https://talkpython.fm/">TalkPython to Me Podcast</a> and <a href="https://pythonbytes.fm/">Python Bytes</a>. He also has his own website of <a href="https://training.talkpython.fm/courses/all">Python Courses</a>. An all-around prolific podcaster and teacher.</p><p>In this episode, Michael Kennedy details how he self-hosts various open-source tools in a DigitalOcean box to run his podcast and course websites. Being a pragmatic developer, he also compares the trade-off between monetary cost, time costs, and maintenance.</p><p>This gives a good clue to other developers; maybe, self-hosting is not so unconventional after all because we have Docker services. Definitely a good talk to think through.</p><h4>#17: Episode 164 — <a href="https://djangochat.com/episodes/buttondown-justin-duke">Buttondown — Justin Duke</a></h4><p><a href="https://www.jmduke.com/">Justin Duke</a> is another founder on the show — he runs a now-popular, developer-friendly email newsletter website, <a href="https://buttondown.com/">Buttondown</a>. I actually used Buttondown to run my (now defunct) newsletter last year after listening to the episode. Their intuitive platform, support for developers, and fair pricing make Buttondown a very strong alternative to other email newsletter providers.</p><p>Justin details how he came to build Buttondown, his previous working experience at Amazon and Stripe, and how he assembles and scales his engineering team. His philosophy on code, work-life balance, and the email landscape made this conversation a very interesting episode.</p><p>After trying Buttondown, you might find that it actually is the last email platform you’ll switch to.</p><h4>#18: Episode 172 — <a href="https://djangochat.com/episodes/pretix-raphael-michel">pretix — Raphael Michel</a></h4><p>I admit; I favor podcasts where founders and entrepreneurs come as guests. Raphael Michel is no exception; he is the founder of <a href="https://pretix.eu/about/en/">pretix</a>, a ticketing software similar to Ticketmaster. pretix is actually an open-source project morphed into a self-sustaining business.</p><p>Raphael talks about the early iterations of pretix, technical challenges behind ticketing, serving international customers, currencies, and concurrency. Surprisingly, the founder still gets to write code and gets involved in the technical side of the business.A rare episode that combines both technology and business. Definitely worth listening to.</p><h4>#19: Episode 176 — <a href="https://djangochat.com/episodes/official-django-mongodb-backend-jib-adegunloye">Official Django MongoDB Backend — Jib Adegunloye</a></h4><p>Django is primarily a web-framework for RDBMS: Postgres, MySQL, Oracle, MariaDB, and other alternatives due to Django ORM, a tool that converts Python code into SQL. No wonder why Postgres, all with its development and features, has become a first-class citizen in the Django world.</p><p>In this context, the guest, Jib, discusses the official Django MongoDB backend provided by MongoDB, a NoSQL database. They discuss the technical implications, how this works, and how it can be beneficial for Django developers.</p><p>Although it is still early in practice, adding support for NoSQL is surely an interesting trend.</p><h4>#20: Episode 189 — <a href="https://djangochat.com/episodes/django-20-years-later-adrian-holovaty-g7z78kc0">Django 20 Years Later — Adrian Holovaty</a></h4><p>Do you know why Django is named Django? It is named after <a href="https://en.wikipedia.org/wiki/Django_Reinhardt">Django Reinhardt</a>, a famous jazz musician. Its founders had a love for music, and the biggest fan was Adrian Holovaty. No wonder that he founded <a href="https://www.soundslice.com/">Soundslice</a>, a music learning and practicing website.</p><p>Like other founders, Adrian Holovaty is a genius: a superstar programmer, an entrepreneur, a musician, a writer, a journalist, and a tinkerer. He is simply awe-inspiring to coders and writers like me.</p><p>In the episode, they reflect back on Django’s early days, teaching music, jazz, and LLMs. A very fun and inspiring episode.</p><h3>Conclusion</h3><p>I do not necessarily do everything this or that podcast told me; the benefit of these podcasts is that I get awareness. For example, I do not have any plans for using a NoSQL database for my Django project in the foreseeable future, but I am aware that it exists and can be a good alternative to Postgres in certain cases.</p><p>This awareness informs my gaps in my own skills and knowledge, which I strive to fill over time.</p><p>I compiled my favorite list of Django Chat episodes so that you can listen to and gain awareness as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b93556d06ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Podcast Downloader with Python]]></title>
            <link>https://medium.com/@hmbarotov/asynchronous-podcast-downloader-with-python-a26f2ffff98a?source=rss-1e36d397faf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a26f2ffff98a</guid>
            <category><![CDATA[requests-library]]></category>
            <category><![CDATA[podcast-downloader]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[python-concurrency]]></category>
            <dc:creator><![CDATA[Hojiakbar Barotov]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 16:50:02 GMT</pubDate>
            <atom:updated>2026-03-01T02:13:43.907Z</atom:updated>
            <content:encoded><![CDATA[<p>A handy Python script to download all episodes of a podcast asynchronously.</p><figure><img alt="Python Snake next to headphones near download-in-progress laptop" src="https://cdn-images-1.medium.com/max/1024/1*Ao1LiTuNkycyi0txIbZdlA.png" /><figcaption>Python Snake next to headphones near download-in-progress laptop</figcaption></figure><p>I like to listen to tech podcasts during commutes. If you are reading this, there is a good chance you like it, too.</p><p>Being a Django dev, my favorite one is <a href="https://djangochat.com/">Django Chat</a>. Having listened to close to 200 podcasts, now I am going to listen to <a href="https://runninginproduction.com/">Running in Production</a>.</p><p>I am old school: I download podcasts to listen offline. The problem is, I don’t really like manually downloading episodes one by one, renaming them, putting them somewhere in one central directory. Looks like a problem to solve with Python!</p><h3>Logic</h3><p>If you think about it, how do central music providers like Spotify and iTunes find and manage thousands of podcasts with new episodes every day? It boils down to really awesome old-school technology, <a href="https://en.wikipedia.org/wiki/RSS">RSS</a>.</p><p>RSS (Really Simple Syndication) is a web feed that allows users and applications to access updates to websites in a standardized, computer-readable format. Podcasters generate RSS, which contain standardized metadata: authors, titles, duration, download link, etc.</p><p>So, to download podcast episodes in Python, we need 3 simple steps:</p><ol><li>Get and scrape the RSS feed;</li><li>Get all podcast episodes;</li><li>Download episodes with relevant titles.</li></ol><p><em>That’s it</em>. The logic is simple, but the implementation can be quite complicated and varied. For starters, you would want async to speed up downloads, helpful progress bar, and consistent naming.</p><p>Below, I present my code that I actually used to download all 108 episodes of Running in Production asynchronously.</p><h3>Code</h3><p><em>All code snippets are available in </em><a href="https://github.com/hmbarotov/coding-snippets/tree/main/podcast-downloader"><em>this repository</em></a><em>. All terminal commands work with both Unix-based systems and Windows. Where they don’t, notice is given.</em></p><h4>Initial Setup</h4><p>First, create a directory:</p><pre>$ mkdir podcast_downloader &amp;&amp; cd podcast_downloader</pre><p>Next, create a virtual environment and install <strong>requests, Beautiful Soup, lxml, tenacity, </strong>and<strong> tqdm</strong>. Then generate a requirements.txt file to record the Python packages installed in your project. Check tqdm version to check for successful installation.</p><pre># Windows<br>$ python -m venv .venv<br>$ .venv\Scripts\Activate.ps1<br>(.venv) $ python -m pip install requests beautifulsoup4 lxml tqdm tenacity<br>(.venv) $ python -m pip freeze &gt; requirements.txt<br>(.venv) $ python -m tqdm --version<br>4.67.3<br><br># MacOS/Linux<br>$ python3 -m venv .venv<br>$ source .venv/bin/activate<br>(.venv) $ python -m pip install requests beautifulsoup4 lxml tqdm tenacity<br>(.venv) $ python -m pip freeze &gt; requirements.txt<br>(.venv) $ python -m tqdm --version<br>4.67.3</pre><p>It’s also best practice to put sensitive or unnecessary files into .gitignore so they don’t get tracked by Git. Create a .gitignore file in your project root and add these lines:</p><pre># django_testing/.gitignore<br><br>__pycache__ # cached Python bytecode folders<br>*.pyc       # cached Python bytecode files<br>.venv       # virtual environment</pre><p>These files aren’t useful in version control because they aren’t part of your production code.</p><h4>Podcast Class</h4><p>Create main.py in your code editor and import necessary Python packages:</p><pre>import concurrent.futures<br>import os<br>import time<br><br>import requests<br>from bs4 import BeautifulSoup<br>from tenacity import retry, stop_after_attempt, wait_exponential<br>from tqdm import tqdm</pre><p>We need these packages for different purposes:</p><ul><li>concurrent.futures : for downloading episodes asynchronously.</li><li>os : for creating folders and valid filenames.</li><li>time : for measuring how long our code run; not strictly necessary, but a nice addition.</li><li>requests : for handling web requests to fetch episodes.</li><li>bs4 : for scraping .xml to extract episode metadata.</li><li>tenacity : for retrying downloads in case of network outage, timeout, etc.</li><li>tqdm : a command-line progress bar to indicate download progress.</li></ul><p>Strictly, time and tqdm are not necessary, but they are helpful packages.</p><p>We define a class named Podcast and document it along the way:</p><pre>class Podcast:<br>    &quot;&quot;&quot;<br>    Downloads podcast episodes from an RSS feed concurrently.<br><br>    Class attributes:<br>        PODCAST_URL: RSS feed URL to scrape.<br>        PODCAST_NAME: Used as the download folder name.<br>        PODCASTS_TO_DOWNLOAD: Number of episodes to fetch from the feed.<br>    &quot;&quot;&quot;<br><br>    PODCAST_URL = &quot;https://runninginproduction.com/podcast/feed.xml&quot;<br>    PODCAST_NAME = &quot;Running in Production&quot;<br>    PODCASTS_TO_DOWNLOAD = 108</pre><p>Our class has three constants: PODCAST_URL , PODCAST_NAME , and PODCASTS_TO_DOWNLOAD .</p><p>Then, we initialize our class that takes podcast url and podcast name as arguments.</p><pre>    def __init__(self, url, name):<br>        &quot;&quot;&quot;<br>        Args:<br>            url: RSS feed URL.<br>            name: Podcast name, used to create the download folder.<br>        &quot;&quot;&quot;<br>        self.url = url<br>        self.folder = os.path.join(os.getcwd(), name)</pre><p>We setup a folder named after our podcast that holds all podcast episodes:</p><pre>    def setup_folder(self, folder=PODCAST_NAME):<br>        &quot;&quot;&quot;Create the download folder if it doesn&#39;t already exist.&quot;&quot;&quot;<br>        os.makedirs(self.folder, exist_ok=True)</pre><p>We then use requests and BeautifulSoup4 to fetch all the podcast episodes. By default, it starts fetching from the latest episodes:</p><pre>    def get_episodes(self, limit=PODCASTS_TO_DOWNLOAD):<br>        &quot;&quot;&quot;<br>        Fetch and parse episodes from the RSS feed.<br><br>        Args:<br>            limit: Maximum number of episodes to retrieve.<br><br>        Returns:<br>            A list of BeautifulSoup Tag objects, one per episode.<br>        &quot;&quot;&quot;<br>        response = requests.get(self.url)<br>        response.raise_for_status()<br>        soup = BeautifulSoup(response.content, &quot;xml&quot;)<br>        return soup.find_all(&quot;item&quot;, limit=limit)</pre><p>This is worth looking at. If you look at our <a href="https://runninginproduction.com/podcast/feed.xml">podcast feed</a>, it is composed of <strong>&lt;item&gt;</strong> tags, each of which holds one episode info. The <em>“xml” </em>argument specifies which parser to use, which in our case is lxml .</p><p>The OS is very picky with filenames. Because we want our file name to be our episode title, we need to sanitize the title before saving it to our file system. We do so by using basic Python, which does not fully cover everything; but for our case, it should be enough.</p><pre>    def to_filename(self, string):<br>        &quot;&quot;&quot;<br>        Sanitize a string into a valid filename by stripping illegal characters.<br><br>        Args:<br>            string: Raw episode title string.<br><br>        Returns:<br>            A filename-safe string with only alphanumerics and &#39; -_.#&amp;&#39; allowed.<br>        &quot;&quot;&quot;<br>        return &quot;&quot;.join(c for c in string if c.isalnum() or c in &quot; -_.#&amp;&quot;).strip()</pre><p>Here comes our main logic:</p><pre>    def download_episode(self, item):<br>        &quot;&quot;&quot;<br>        Download a single episode and save it as an MP3.<br><br>        Intended to be called concurrently via ThreadPoolExecutor.<br><br>        Args:<br>            item: A BeautifulSoup Tag object representing an RSS &lt;item&gt;.<br><br>        Returns:<br>            A summary string with the filename and size, e.g. &#39;#001 - Title (45.2 MB)&#39;.<br>        &quot;&quot;&quot;<br><br>        @retry(<br>            stop=stop_after_attempt(5),<br>            wait=wait_exponential(multiplier=1, min=2, max=32),<br>        )<br>        def _download():<br>            with requests.get(mp3_url, stream=True, timeout=30) as r:<br>                r.raise_for_status()<br>                with open(file_path, &quot;wb&quot;) as f:<br>                    for chunk in r.iter_content(chunk_size=8192):<br>                        if chunk:<br>                            f.write(chunk)<br><br>        title = item.find(&quot;title&quot;).text<br>        episode = int(item.find(&quot;link&quot;).text.split(&quot;/&quot;)[-1].split(&quot;-&quot;)[0])<br>        mp3_url = item.find(&quot;enclosure&quot;)[&quot;url&quot;]<br>        mp3_size_mb = round(int(item.find(&quot;enclosure&quot;)[&quot;length&quot;]) / (1024**2), 2)<br>        file_name = self.to_filename(f&quot;#{episode:03d} - {title}&quot;)<br>        file_path = os.path.join(self.folder, f&quot;{file_name}.mp3&quot;)<br><br>        _download()<br><br>        return f&quot;{file_name} ({mp3_size_mb} MB)&quot;</pre><p>We use the @retry decorator to try downloading podcasts 5 times before our program crashes. It waits exponentially longer (2s, 4s, … 32s) before retrying each time. A very nice decorator for real-world projects.</p><p>To download files from the internet with Python, requests is the recommended way. Because our episodes are large (anywhere from 40MB to 100MB), we set the <em>stream</em> argument to True. This avoids loading the entire file into memory; instead, it uses byte-sized chunks. With asynchronous downloads, this is essential to keep memory working stable and performant.</p><p>Because we are downloading mp3, we write to our file in the wb format (stands for <em>Write Binary, (our music is in binary format)</em>). We are downloading episodes in chunk format, so we need to iterate over chunks. The common chunk size is 8192 bytes, or 8 kilobytes.</p><p>The item argument is a BeautifulSoup4 object that holds episode metadata. We extract the title, episode number, url, size in megabytes. We also create a valid filename with the episode number and the title. Then, we create a file path for our episode.</p><p>In the end, we call our private _download() method.</p><p>Our Podcast class is ready. You should have this code at this point:</p><pre>import concurrent.futures<br>import os<br>import time<br><br>import requests<br>from bs4 import BeautifulSoup<br>from tqdm import tqdm<br><br><br>class Podcast:<br>    &quot;&quot;&quot;<br>    Downloads podcast episodes from an RSS feed concurrently.<br><br>    Class attributes:<br>        PODCAST_URL: RSS feed URL to scrape.<br>        PODCAST_NAME: Used as the download folder name.<br>        PODCASTS_TO_DOWNLOAD: Number of episodes to fetch from the feed.<br>    &quot;&quot;&quot;<br><br>    PODCAST_URL = &quot;https://runninginproduction.com/podcast/feed.xml&quot;<br>    PODCAST_NAME = &quot;Running in Production&quot;<br>    PODCASTS_TO_DOWNLOAD = 108<br><br>    def __init__(self, url, name):<br>        &quot;&quot;&quot;<br>        Args:<br>            url: RSS feed URL.<br>            name: Podcast name, used to create the download folder.<br>        &quot;&quot;&quot;<br>        self.url = url<br>        self.folder = os.path.join(os.getcwd(), name)<br><br>    def setup_folder(self, folder=PODCAST_NAME):<br>        &quot;&quot;&quot;Create the download folder if it doesn&#39;t already exist.&quot;&quot;&quot;<br>        os.makedirs(self.folder, exist_ok=True)<br><br>    def get_episodes(self, limit=PODCASTS_TO_DOWNLOAD):<br>        &quot;&quot;&quot;<br>        Fetch and parse episodes from the RSS feed.<br><br>        Args:<br>            limit: Maximum number of episodes to retrieve.<br><br>        Returns:<br>            A list of BeautifulSoup Tag objects, one per episode.<br>        &quot;&quot;&quot;<br>        response = requests.get(self.url)<br>        response.raise_for_status()<br>        soup = BeautifulSoup(response.content, &quot;xml&quot;)<br>        return soup.find_all(&quot;item&quot;, limit=limit)<br><br>    def to_filename(self, string):<br>        &quot;&quot;&quot;<br>        Sanitize a string into a valid filename by stripping illegal characters.<br><br>        Args:<br>            string: Raw episode title string.<br><br>        Returns:<br>            A filename-safe string with only alphanumerics and &#39; -_.#&amp;&#39; allowed.<br>        &quot;&quot;&quot;<br>        return &quot;&quot;.join(c for c in string if c.isalnum() or c in &quot; -_.#&amp;&quot;).strip()<br><br>    def download_episode(self, item):<br>        &quot;&quot;&quot;<br>        Download a single episode and save it as an MP3.<br><br>        Intended to be called concurrently via ThreadPoolExecutor.<br><br>        Args:<br>            item: A BeautifulSoup Tag object representing an RSS &lt;item&gt;.<br><br>        Returns:<br>            A summary string with the filename and size, e.g. &#39;#001 - Title (45.2 MB)&#39;.<br>        &quot;&quot;&quot;<br><br>        @retry(<br>            stop=stop_after_attempt(5),<br>            wait=wait_exponential(multiplier=1, min=2, max=32),<br>        )<br>        def _download():<br>            with requests.get(mp3_url, stream=True, timeout=30) as r:<br>                r.raise_for_status()<br>                with open(file_path, &quot;wb&quot;) as f:<br>                    for chunk in r.iter_content(chunk_size=8192):<br>                        if chunk:<br>                            f.write(chunk)<br><br>        title = item.find(&quot;title&quot;).text<br>        episode = int(item.find(&quot;link&quot;).text.split(&quot;/&quot;)[-1].split(&quot;-&quot;)[0])<br>        mp3_url = item.find(&quot;enclosure&quot;)[&quot;url&quot;]<br>        mp3_size_mb = round(int(item.find(&quot;enclosure&quot;)[&quot;length&quot;]) / (1024**2), 2)<br>        file_name = self.to_filename(f&quot;#{episode:03d} - {title}&quot;)<br>        file_path = os.path.join(self.folder, f&quot;{file_name}.mp3&quot;)<br><br>        _download()<br><br>        return f&quot;{file_name} ({mp3_size_mb} MB)&quot;</pre><h3>Main Class</h3><p>If you have been around the block for some time, you have likely seen this:</p><pre>if __name__ == &quot;__main__&quot;:</pre><p>It is a conditional that checks if the program is being run directly. In our case, it does not matter much, but it is usually a good convention to follow unless you have reason to do otherwise.</p><p>We start the time counter, initialize the Podcast class, and set up the folder. Then, we provide helpful messages:</p><pre>if __name__ == &quot;__main__&quot;:<br>    start = time.perf_counter()<br><br>    podcast = Podcast(url=Podcast.PODCAST_URL, name=Podcast.PODCAST_NAME)<br>    podcast.setup_folder()<br><br>    print(&quot;Fetching episode list...&quot;)<br>    episodes = podcast.get_episodes()<br>    print(f&quot;Found {len(episodes)} episodes. Starting download...\n&quot;)</pre><p>Here comes the asynchronous part that speeds up our task by quite a margin. There are several ways to tackle async, but my implementation comes directly from Corey Schafer, specifically from his video on <a href="https://youtu.be/IEEhzQoKtQU?si=l-QV9gTHAiIemDKv">Python Threading</a>.</p><pre>    with concurrent.futures.ThreadPoolExecutor() as executor:<br>        futures = {executor.submit(podcast.download_episode, ep): ep for ep in episodes}<br>        with tqdm(total=len(futures), unit=&quot;episode&quot;) as progress:<br>            for future in concurrent.futures.as_completed(futures):<br>                result = future.result()<br>                progress.set_postfix_str(result)<br>                progress.update(1)</pre><p>Here we create a thread pool and submit each episode as a separate task, getting back a dictionary of Future objects. As each download completes — in whatever order they finish — as_completed hands us the result, which we use to update the tqdm progress bar with the episode name and size.</p><p>The key difference from a simple executor.map is that as_completed lets us react to each finished download immediately rather than waiting for all of them, which is what makes the live progress bar possible.</p><p>Finally, we finish our program:</p><pre>    elapsed = round(time.perf_counter() - start, 2)<br>    print(f&quot;\nFinished {len(episodes)} episodes in {elapsed}s&quot;)</pre><p>Your whole main statement should look like this:</p><pre>if __name__ == &quot;__main__&quot;:<br>    start = time.perf_counter()<br><br>    podcast = Podcast(url=Podcast.PODCAST_URL, name=Podcast.PODCAST_NAME)<br>    podcast.setup_folder()<br><br>    print(&quot;Fetching episode list...&quot;)<br>    episodes = podcast.get_episodes()<br>    print(f&quot;Found {len(episodes)} episodes. Starting download...\n&quot;)<br><br>    with concurrent.futures.ThreadPoolExecutor() as executor:<br>        futures = {executor.submit(podcast.download_episode, ep): ep for ep in episodes}<br>        with tqdm(total=len(futures), unit=&quot;episode&quot;) as progress:<br>            for future in concurrent.futures.as_completed(futures):<br>                result = future.result()<br>                progress.set_postfix_str(result)<br>                progress.update(1)<br><br>    elapsed = round(time.perf_counter() - start, 2)<br>    print(f&quot;\nFinished {len(episodes)} episodes in {elapsed}s&quot;)</pre><p>So, try it by setting PODCASTS_TO_DOWNLOAD to 5. In my case, it looked as follows:</p><pre>(.venv) hojiakbar@HMBarotov:~/Files/Coding/Projects/Django/coding-snippets/podcast-downloader$ python main.py <br>Fetching episode list...<br>Found 5 episodes. Starting download...<br><br>100%|█| 5/5 [04:47&lt;00:00, 57.58s/episode, #105 - TinyPilotKVM Lets You Remote Control Your Server from Your<br><br>Finished 5 episodes in 291.1s</pre><p>I could download 108 podcasts of 6.6 GB on the average speed Wi-fi in 16 minutes. A very good automation right? Now, I can forget about this script for 3 months.</p><p>If you need to download other tech podcasts, you can do so by changing PODCAST_URL and PODCAST_NAME . Also, some podcast feeds use &lt;itunes:title&gt; instead of &lt;title&gt;, so you may need to modify the download_episode() function.</p><p>Happy podcasting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a26f2ffff98a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-life Excel Automation with Python and Xlwings]]></title>
            <link>https://medium.com/@hmbarotov/real-life-excel-automation-with-python-and-xlwings-87fdf604d193?source=rss-1e36d397faf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/87fdf604d193</guid>
            <category><![CDATA[python-excel-library]]></category>
            <category><![CDATA[xlwing]]></category>
            <category><![CDATA[excel-automation]]></category>
            <dc:creator><![CDATA[Hojiakbar Barotov]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 15:38:21 GMT</pubDate>
            <atom:updated>2026-02-05T15:38:21.798Z</atom:updated>
            <content:encoded><![CDATA[<p>A real-life case study of Excel automation with Python and Xlwings in a big corporation.</p><figure><img alt="Xlwings Cover Image, generated by Gemini" src="https://cdn-images-1.medium.com/max/1024/1*DmgNohmbjoM4XDmQ3B3mIQ.png" /><figcaption>Xlwings Cover Image, generated by Gemini</figcaption></figure><p>After my junior year at university, I got into a summer internship at a big company, which shall stay nameless, in Tashkent, Uzbekistan. With my bachelor’s in Finance, I joined their Financial Planning and Analysis (FP&amp;A) team as a full-time finance intern that knew how to code. Apparently, my finance education <strong><em>and</em></strong> programming skills were the reason why I was selected out of other bright students.</p><p>So, here we go. I knew how to create Django websites, not how to automate financial operations. I had to quickly learn Pandas for data manipulation and analysis, Power BI for visualization (the company was fully on Microsoft), and finally <a href="https://www.xlwings.org/">Xlwings</a> for using Python with Excel.</p><p>Towards the end of my internship, I started automating Excel with Python. In this article, I am going to show you how I automated fetching and updating foreign exchange rates in our local Excel file. Although this task is very simple and easy for an experienced dev, it nicely illustrates Xlwings, as well as a point or two about working in a corporation.</p><p>Before going deep into Xlwings, let’s answer the elephant in the room: why Python in Finance?</p><h3>Python in Finance</h3><p>Python is the one language to write it all, period. Because of its easy syntax, awesome libraries for working with data (<a href="https://pandas.pydata.org/">Pandas</a>, <a href="https://matplotlib.org/">Matplotlib</a>), and domain-specific packages (Xlwings), Python has become a standard coding language in business, especially in <a href="https://corporatefinanceinstitute.com/resources/data-science/python-in-finance/">finance</a>.</p><p>You want Excel automation? Boom, here is Xlwings. Need to create a small, fast API endpoint? Here is <a href="https://flask.palletsprojects.com/en/stable/">Flask</a>. Have massive datasets that Excel even cannot open? Try Pandas. With its ready-to-use libraries, excellent tutorials and documentation, and easy syntax, it makes a ton of sense to use Python fast and cheap.</p><h3>What is Xlwings?</h3><p>Finance has much to automate with Python (invoice, payroll, data cleaning and standardization, etc.), but the number one place finance professionals want to improve is Excel. As wonderful and useful as it is, Excel has its own limitations and pain points, like pretty much any software.</p><p>For once, Excel’s row count is capped at approximately 1 million and encounters serious performance issues on most office laptops; Python is essentially limitless for most automation tasks. For another, VBA and macros are only for Excel; if you need automation outside it, you will anyway reach another tool, i.e. Python.</p><p>So, how to automate Excel with Python? Several options exist:</p><ol><li><strong>Built-in Python in Excel</strong>: Microsoft 365 provides cloud-based Python directly inside Excel. Requires internet and 365 subscription.</li><li><strong>Xlwings</strong>: An open-source, free library with PRO support. Relies on external Python and Excel to automate operations.</li><li><a href="http://pyxll/"><strong>PyXLL</strong></a>: Proprietary commercial add-in directly inside Excel. Fast, reliable, but subscription-based per user.</li></ol><p>For most practical use cases, Xlwings is the way to go because it is free, fast, and based on external Python that communicates with Excel through COM (Component Object Model) API. Additionally, the creator of this package, <a href="https://x.com/felixzumstein?lang=en">Felix Zumstein</a>, had written a book, <a href="https://www.amazon.com/Python-Excel-Environment-Automation-Analysis/dp/1492081000"><em>Python for Excel</em></a>, which I read during my internship.</p><figure><img alt="Python for Excel by Felix Zumstein" src="https://cdn-images-1.medium.com/max/398/0*z46M75K6uw_y5RP7.jpg" /><figcaption>Python for Excel by Felix Zumstein</figcaption></figure><p>So, after a month and a half, I was getting relatively ready to use my Python skills to automate boring stuff in Excel.</p><h3>Excel Automation: Foreign Exchange Rates</h3><p>After completing my tasks given by my mentor, I spent my time learning and playing around with Xlwings. When I could not install Python on my corporate laptop due to restrictions, I went to the IT&amp;admin team for installation. My jaws dropped dead when I heard this question: “What is Python and why you need it?” After a brief bureaucratic back and forth, I realized I could bypass this simply by installing <a href="https://www.anaconda.com/">Anaconda</a>.</p><p>When I came up to my team members stating we could automate some Excel operations with Python and Xlwings, I got a response that surprised pretty much no one: “Yeah, give it a try and let us know.”</p><p>Being a big company that had foreign suppliers, the company needed foreign exchange rates, USD and EUR. Someone had to manually go to the <a href="https://cbu.uz/en/">Central Bank</a> website, fetch the Excel file, and update our local file. A very good illustration for automation. So, I wrote it and automated my laptop to run it every day at 8.30 a.m. with <a href="https://learn.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-start-page">Windows Task Scheduler</a>.</p><p>Below is the code:</p><h3>Project</h3><p><em>All code snippets are available in </em><a href="https://github.com/hmbarotov/coding-snippets/tree/main/xlwings-fx"><em>this repository</em></a><em>. All terminal commands work with both Unix-based systems and Windows. Where they don’t, notice is given.</em></p><p>So, how do you get information from the web? The default response is to scrape it. Or check for available API endpoints. If you can, use API because it is simpler.</p><p>I could get currency exchange rates from <a href="https://cbu.uz/en/arkhiv-kursov-valyut/json/">JSON API</a> from the Central Bank, but I was too deep in my task that I just went straight to scraping from its homepage.</p><p>Here was the format of the Excel sheet that we had info on FX:</p><figure><img alt="Excel Sheet for Foreign Exchange Rates" src="https://cdn-images-1.medium.com/max/1024/1*c1-Y5i25aFfKgzMH-R_N4A.png" /><figcaption>Excel Sheet for Foreign Exchange Rates</figcaption></figure><p>The logic of my little program was this: Get the rates of USD and EUR against sum (our national currency) for a given date and put it in the relevant cell. Here is how I went about it:</p><ol><li>Scrape the data from the <a href="https://cbu.uz/en/">website</a>;</li><li>Determine the date and put it in the relevant cell;</li><li>Automate this to run every weekday at 8.30 a.m.</li></ol><h4>#1 Scraping</h4><p>To scrape, I used requests and BeautifulSoup with lxml . After installing packages, I imported necessary libraries and set constants:</p><pre>import sys<br>import time<br>from string import ascii_uppercase<br><br>import requests<br>import xlwings as xw<br>from bs4 import BeautifulSoup<br><br>CBU_URL = &quot;https://cbu.uz/en/&quot;<br>SHEET_USD = &quot;USD_2026&quot;<br>SHEET_EUR = &quot;EUR_2026&quot;</pre><p>Then, I wrote the scraping logic with a few error handling cases. I first got the html, parsed the necessary rates with bs4 and used a function to return the result:</p><pre>def get_html(url, timeout=5):<br>    print(&quot;&gt;&gt;&gt; Fetching exchange rates from CBU...&quot;)<br>    try:<br>        resp = requests.get(url, timeout=timeout)<br>        resp.raise_for_status()<br>        return resp.text<br>    except requests.ConnectionError as e:<br>        print(f&quot;&gt;&gt;&gt; Loss of connectivity:\n{e}&quot;)<br>        time.sleep(10)<br>        sys.exit(1)<br>    except requests.Timeout as e:<br>        print(f&quot;&gt;&gt;&gt; Request timed out:\n{e}&quot;)<br>        time.sleep(10)<br>        sys.exit(1)<br>    except requests.RequestException as e:<br>        print(f&quot;&gt;&gt;&gt; Request failed:\n{e}&quot;)<br>        time.sleep(10)<br>        sys.exit(1)<br><br><br>def parse_rates_from_html(html):<br>    soup = BeautifulSoup(html, &quot;lxml&quot;)<br><br>    calendar_div = soup.find(&quot;div&quot;, class_=&quot;input_calendar&quot;)<br>    if not calendar_div:<br>        raise RuntimeError(&quot;Calendar div not found: div.input_calendar&quot;)<br><br>    inp = calendar_div.find(&quot;input&quot;)<br>    if not inp or not inp.has_attr(&quot;value&quot;):<br>        raise RuntimeError(&quot;Calendar input/value not found inside div.input_calendar&quot;)<br><br>    currency_date = inp[&quot;value&quot;]<br>    print(f&quot;&gt;&gt;&gt; FX Rates date: {currency_date}&quot;)<br><br>    rates = {&quot;USD&quot;: 0.0, &quot;EUR&quot;: 0.0}<br><br>    for item in soup.find_all(&quot;div&quot;, class_=&quot;exchange__item_value&quot;)[:5]:<br>        code = item.strong.text.strip() if item.strong else &quot;&quot;<br><br>        if code in rates:<br>            rate_str = item.text.split(&quot;=&quot;)[1].strip()<br>            rates[code] = float(rate_str)<br><br>    return rates, currency_date<br><br><br>def fetch_exchange_rates():<br>    html = get_html(CBU_URL, timeout=5)<br>    return parse_rates_from_html(html)</pre><h4>#2 Writing to Excel</h4><p>This is the step for Xlwings. Once I got the relevant cell, I used this package to write to the sheet. Although this is only a tiny use case of xlwings, it was still important in that it helped me to learn the package:</p><pre>def get_excel_cell_from_date(date_str):<br>    day = int(date_str[:2]) + 2<br>    month_index = int(date_str[3:5])<br>    column = ascii_uppercase[month_index]<br>    return f&quot;{column}{day}&quot;<br><br><br>def write_to_excel(file_path, cell, rates):<br>    print(f&quot;&gt;&gt;&gt; Writing to Excel at {file_path}...&quot;)<br>    wb = xw.Book(file_path)<br><br>    wb.sheets[SHEET_USD][cell].value = rates[&quot;USD&quot;]<br>    wb.sheets[SHEET_EUR][cell].value = rates[&quot;EUR&quot;]<br>    wb.save()<br><br>    print(&quot;&gt;&gt;&gt; Excel file saved.&quot;)</pre><p>Then, I wrote the main() function:</p><pre>def main():<br>    print(&quot;&gt;&gt;&gt; Starting exchange rate fetcher...&quot;)<br><br>    file_path = r&quot;\\peter\ZDrive\00016243\Desktop\FX_Rate\excel_files\FX_2026.xlsx&quot;<br>    rates, date_str = fetch_exchange_rates()<br>    cell = get_excel_cell_from_date(date_str)<br><br>    print(f&quot;&gt;&gt;&gt; Rates fetched: USD = {rates[&#39;USD&#39;]}, EUR = {rates[&#39;EUR&#39;]}&quot;)<br>    print(f&quot;&gt;&gt;&gt; Writing rates to cell {cell}...&quot;)<br><br>    write_to_excel(file_path, cell, rates)<br>    print(&quot;&gt;&gt;&gt; Program finished.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>This program, run in the VS Code, produced this:</p><pre>(.venv) PS Microsoft.PowerShell.Core\FileSystem::\\peter\ZDrive\00016243\Desktop\FX_Rate&gt; &amp; //peter/ZDrive/00016243/Desktop/FX_Rate/.venv/Scripts/python.exe //peter/ZDrive/00016243/Desktop/FX_Rate/main.py<br>&gt;&gt;&gt; Starting exchange rate fetcher...<br>&gt;&gt;&gt; Fetching exchange rates from CBU...<br>&gt;&gt;&gt; FX Rates date: 05.02.2026<br>&gt;&gt;&gt; Rates fetched: USD = 12265.77, EUR = 14492.01<br>&gt;&gt;&gt; Writing rates to cell C7...<br>&gt;&gt;&gt; Writing to Excel at \\peter\ZDrive\00016243\Desktop\FX_Rate\excel_files\FX_2026.xlsx...<br>&gt;&gt;&gt; Excel file saved.<br>&gt;&gt;&gt; Program finished.</pre><p>It actually wrote to the Excel file on Feb 5, 2026, which is the date I run the program for this article:</p><figure><img alt="Excel Xlwings Output" src="https://cdn-images-1.medium.com/max/1024/1*ga5B4qZv6zInbOvD2I1vSg.png" /><figcaption>Excel Xlwings Output</figcaption></figure><h4>#3 Windows Task Scheduler</h4><p>Windows has its own cron job — <a href="https://learn.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-start-page">Task Scheduler</a>. It is a GUI, so pretty simple to set up and run. Once you have the Python file ready, it is as simple as creating a .bat file that you tell Task Scheduler to run at a predetermined interval.</p><h3>Concluding Thoughts</h3><p>The case and the Python code were dead simple. However, it automated one task — and did so perfectly. My manager was surprised how well this worked. Unfortunately, my time was running out and I was assigned a giant Power BI project. In hindsight, I think I should have used Python and <a href="https://streamlit.io/">Streamlit</a>.</p><p>The matter was complicated when I was offered a part-time job but chose a prestigious internship at the Central Bank of Uzbekistan, so I declined the offer. However, I still think what I could have automated if I had stayed.</p><p>Unfortunately, as far as I know, my efforts have been in vain as the management did not invest in Python (I was a terrible advocate) and no new Python specialist was hired. So much could have been done, but the corporation is not a startup; it favors stability and predictibility over change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87fdf604d193" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Django: My Path & Resources I Used]]></title>
            <link>https://medium.com/@hmbarotov/learning-django-my-path-resources-i-used-e310d7ff941b?source=rss-1e36d397faf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e310d7ff941b</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-beginner]]></category>
            <category><![CDATA[django-resources]]></category>
            <dc:creator><![CDATA[Hojiakbar Barotov]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 12:52:37 GMT</pubDate>
            <atom:updated>2026-05-29T12:51:41.765Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical roadmap of the books, blogs, tutorials, and projects that helped me learn Django</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nxseulf-4YUYosbqqhkMAw.png" /><figcaption>Learning Django</figcaption></figure><p>I remember learning <a href="https://www.djangoproject.com/">Django</a>, a popular Python web-framework, for the first time 3 years ago, in early 2023. Installing <a href="https://www.python.org/">Python 3</a> on my painfully slow Windows machine, setting up a dev environment on <a href="https://code.visualstudio.com/">VS Code</a>, and trying to understand what the hell this funny-sounding Django stuff is.</p><p>Now, looking back, I can see how far I have come in my journey and how far I still need to go. As a somewhat competent Django user that have built multiple Django applications, I can see how much I have internalized and where my understanding of Django and web-development is still full of gaps.</p><p>Therefore, in this article, I decided to reflect back on my Django journey. Hope it will bring your own memories back.</p><h3>Coming to Django</h3><p>In my freshman year at university, in early 2023, I decided to take up programming seriously. This was inspired by the curriculum of my university; at that time, I had chosen <em>Understanding Finance </em>and <em>Visual Programming </em>as my optional modules at the second semester. I really wanted to explore programming on my own because I could do so through YouTube. On top of that, my brother was a Django developer.</p><p>I had some experience spending time on a game-based, community-driven learning app for programming called <a href="https://www.sololearn.com/en/">Sololearn</a>. I knew some Python and had quite a good knowledge of web-design. Indeed, I had built <a href="https://hojiakbardev.netlify.app/">my first portfolio website</a> at the age of 17 with <a href="https://getbootstrap.com/">Bootstrap5</a>. It is still hosted for free on Netlify, while I have long forgotten my email and credentials :)</p><figure><img alt="My first static portfolio website" src="https://cdn-images-1.medium.com/max/1024/1*KvWwPa1cHane7CVEX0WLuA.png" /><figcaption>My first static <a href="https://hojiakbardev.netlify.app/">portfolio website</a></figcaption></figure><p>I was not satisfied though; I was not content with just designing static web-pages. I had wanted to do something more. Therefore, I dropped web-design, and would drop learning programming altogether due to my university entrance exams. So, fast forward to my freshman year, I knew that I would choose Python.</p><p>I chose to learn Python because it was an easy, beginner-friendly, yet powerful language. I read that I could do a lot — I mean, <em>a lot. </em>Python was the programming language of business, economics, and finance. Automation, data processes, AI/ML, web-development, scripting — they were all strong sides of Python. Although I didn’t have the slightest idea what they actually were, I thought to myself,</p><blockquote>Well, Python seems a cool and easy language. Let’s give it a try.</blockquote><p>Like most people, I started with the <a href="https://ehmatthes.github.io/pcc_2e/">Python Crash Course, the 2nd edition</a>. This is I think by far the most comprehensive, beginner-friendly, yet project-based Python book out there. It has two sections: theory and practice. In the first section, you learn basics of programming: loops, conditionals, variables, files. In the second section, you build a 2D game with <a href="https://www.pygame.org/news">Pygame</a>, visualize data with <a href="https://matplotlib.org/">Matplotlib</a>, and finally <strong>build a learning log system</strong> <strong>with Django</strong>.</p><figure><img alt="Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming" src="https://cdn-images-1.medium.com/max/395/0*E9G_OEn9vEQ0rQmS.jpg" /><figcaption>Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming</figcaption></figure><p>Off we go, I immersed myself in the book. The final Django project was my favorite because I had built something that I could show to my family. My brother was a Django developer at that time, so he helped me with the resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/0*zPeN874G_Qod7yIh.png" /><figcaption><a href="https://ehmatthes.github.io/pcc_3e/solutions/chapter_20/">Learning Log Project</a> from the Python Crash Course</figcaption></figure><p>I was not really looking for a job or wanted to build something specific; Python and Django looked cool, and I was very young and impressed. So, I decided to learn Django alongside my <em>Visual Programming </em>module at university.</p><h3>Learning Django</h3><p>So, how does one <a href="https://www.podcasts.nu/episodes/django-chat/how-to-learn-django-ep2-replay-NwuGcSy6Y7">learn Django</a>?</p><p>Is it books, YouTube, online courses, blogs, or bootcamps? The answers, of course, is it depends. Which one do you prefer? Because Django is a popular web-framework, it is well-served by a teaching community. You can choose your adventure.</p><p>I chose books and blog because it is my natural learning style. I prefer being able to search through the content, jump around, and come back for a quick review. Videos are helpful for me in cases where I am particularly stuck or new and need visual examples.</p><p>So, it is not only books or videos. You can choose different methods depending on what you need when you need it. Only the Sith deal in absolutes.</p><p>That said, I am going to show a few books, blogs, and other content that I found particularly helpful for learning during my studies. They are given in the order I found and used:</p><blockquote>Note: These resources are those I used personally. There are many other good resources out there I may not be familiar with. In no way is this list exhaustive.</blockquote><pre>| # | Resource                      | Type             | Best for                 | What you actually get                                                   | Why you might like it                                      |<br>| - | ----------------------------- | ---------------- | ------------------------ | ----------------------------------------------------------------------- | ---------------------------------------------------------- |<br>| 1 | LearnDjango.com               | Blog + courses   | Beginners → intermediate | Step-by-step tutorials. No skipped steps. Clear screenshots.            | You never feel lost. Even mkdir is explained.              |<br>| 2 | Django for Beginners          | Book             | Total beginners          | Core Django. Models, views, templates, auth, forms, tests.              | Builds strong basics fast. Very structured.                |<br>| 3 | Django for APIs               | Book             | Backend + API builders   | Django REST Framework. Tokens. Permissions. Frontend integration.       | Helps you move beyond classic server-rendered apps.        |<br>| 4 | Django for Professionals      | Book             | Advanced beginners       | Docker, env vars, Postgres, email, security, deployment.                | Feels like real production setup. Not toy projects.        |<br>| 5 | Corey Schafer Django Series   | YouTube playlist | Project builders         | Full social-blog app. Auth, profiles, posts, deployment.                | You finally build something big and messy.                 |<br>| 6 | Django 5 By Example           | Book             | Serious skill growth     | Blog, social site, ecommerce, e-learning SaaS. Celery, Redis, Channels. | Closest thing to real-world Django in a book.              |<br>| 7 | Simple Is Better Than Complex | Blog             | Concept clarity          | Forms, auth, CBVs, signals, crispy forms, small features.               | Great when you want to understand how Django really works. |<br>| 8 | BugBytes                      | YouTube channel  | Modern Django            | Django + HTMX, async views, clean UI patterns.                          | Fast answers to practical problems. Very up to date.       |</pre><h4>#1 <a href="https://learndjango.com/">LearnDjango.com</a></h4><p>One central repository for all things related to learning Django. Run by <a href="https://wsvincent.com/">William Vincent</a>, a best-selling Django author and <a href="https://djangochat.com/">Django podcast</a> host, it includes free beginner-friendly and intermediate Django tutorials and paid courses.</p><p>I really like its quick how-to’s and the full content of any blog piece. The author does not leave out any steps, even as mundane as directory creation. While nowadays I can go to a blog and take out exactly what I need, that was not the case when I started. For beginners, this feature is a golden mine.</p><p>These days this site has become a de-facto go-to place to learn Django for beginners due to its friendly and comprehensive blog articles. In fact, the content below is explained and recommended more deeply in this blog post, <a href="https://learndjango.com/tutorials/how-learn-django">How to Learn Django (2025)</a></p><h4>#2 <a href="https://learndjango.com/courses/">Django for Series</a> by William Vincent</h4><p>The Django web framework is updated every 9 months. A major, LTS (long-term support) release happens every 3 releases (every 27 months): Django 5.0 becomes 5.1 and 5.2, which is an LTS release, and then 6.0. As old as Django is, it is still actively developed and used, which is extremely rare for most open-source projects.</p><figure><img alt="Django for Beginners Book Cover" src="https://cdn-images-1.medium.com/max/800/0*lTvnkaiEoRG8CF12.jpg" /><figcaption>Django for Beginners Book Cover</figcaption></figure><p>This active development makes it extremely hard for authors to keep up-to-date. Therefore, you don’t find many up-to-date materials on Django. If you are a competent user, that is not a big deal, but if not, you will be confused.</p><p>The best-selling author, William Vincent, has written and regularly updated 3 books on Django: <a href="https://learndjango.com/courses/django-for-beginners/">Django for Beginners</a>, <a href="https://learndjango.com/courses/django-for-apis/">Django for APIs</a>, and <a href="https://learndjango.com/courses/django-for-professionals/">Django for Professionals</a>. They are beginner, intermediate, and advanced books on the framework.</p><p>The first book introduces core concepts of the core technology: setup, commands, CRUD, users, authentication, forms, tests, databases, database table relationships, and deployment. Although the title says for beginners, you will gain a lot of understanding of the core Django. I took the Django 4.2 edition of the book back in 2023.</p><figure><img alt="Django for APIs Book Cover" src="https://cdn-images-1.medium.com/max/800/0*b0tT2be427tcn_Gh.jpg" /><figcaption>Django for APIs Book Cover</figcaption></figure><p>Most Django developers in the real industry do not write pure Django; they usually write REST APIs. REST (Representational State Transfer) APIs (Application Program Interface) is a way for two machines to talk to one another over the wire. In Django, you most likely use <a href="https://www.django-rest-framework.org/">Django REST Framework</a> or <a href="https://django-ninja.dev/">Django-Ninja</a>. This book introduces the API world of Django with examples.</p><p>The latest edition demonstrates the integration of Vue.js with Django, which was not the case in the 4th edition I read. I will probably give it a read to this book again in the future.</p><p>How does one go from novice to competent? By progressively expanding their boundaries and limitations. It is not easy to go from building toy projects in Django to truly build production websites with proper configuration, emails, permissions, and deployment. That’s why Django for Professionals is a super book for advanced beginners looking to upskill.</p><figure><img alt="Django for Professionals Book Cover" src="https://cdn-images-1.medium.com/max/800/0*LDTCd5DAnC6x-uh1.jpg" /><figcaption>Django for Professionals Book Cover</figcaption></figure><p>This book introduces the elephant of the room for beginners: Docker, which is its own world. Pretty much every professional developer uses Docker in professional projects, so Will Vincent does a really good job of explaining it in the context of Django. This was the biggest takeaway for me. Still, Docker is a beast; you will constantly learn new stuff about it.</p><p>Another particular feature of this book is that it is broken into two sections: the first one is the standard steps you would do for any production website — Docker, production database, authentication, static and media assets, email, environment variables, base security. You can then build any website on top of this preparation, which you do in the second half.</p><h4>#3 <a href="https://youtube.com/playlist?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&amp;si=TXIoSUCW6EnNUoHh">Django Series</a> by Corey Schafer</h4><p>Now what? You read three increasingly-advanced books on Django, developed a few toy projects, and deployed some of them. Now what? <em>So what?</em></p><p>You likely came across with a coding concept known as <a href="https://www.wbscodingschool.com/blog/what-is-tutorial-hell-how-to-get-out/">tutorial hell</a> — a case where you endlessly watch tutorials, build demo projects, yet still cannot complete independent projects. It is a vicious cycle because you feel you are learning, but you are just repeating the same old stuff. While the three books above are excellent for building blocks, they are not by themselves enough for project-based learning.</p><figure><img alt="Django Series by Corey Schafer" src="https://cdn-images-1.medium.com/max/336/0*VbAFZqIDDrrwEfPX" /><figcaption>Django Series by Corey Schafer</figcaption></figure><p>Enter the Django Series by Corey Schafer on YouTube where you build a production Django Medium/Twitter clone and deploy to <a href="https://www.heroku.com/">Heroku</a> (yes, that platform that used to provide free hosting). Although the series is a couple of years old and uses Django 2.1, it is arguably by far the best Django series on YouTube. If you know the foundations of this framework, you can figure out how to update the code base to Django 6.0 because it is very stable and boring (which is a good thing, btw).</p><p>This series ties everything together and creates a fully-working web application. While the deployment videos are most likely broken due to changes with Heroku, you will learn and truly build something you can perfect with Django.</p><h4>#4 <a href="https://github.com/PacktPublishing/Django-5-By-Example">Django 5 by Example</a></h4><p>Project-based learning works best in programming because you get your hands dirty and really understand what is going on. Although authors try their best to make their content as accurate and relevant as possible, independent changes in Django, Python, or third-parties make the code broken from time to time. It is normal; and you will need to really understand and fix the bugs yourself. That’s how you grow.</p><figure><img alt="Django 5 By Example Book Cover" src="https://cdn-images-1.medium.com/max/1024/0*AwQidtoOy-jpfSCK" /><figcaption>Django 5 By Example Book Cover</figcaption></figure><p>This project-based book by Antonio Mele is considered to be the best book for project-based learning for advanced/comptent Django learners. It is not a book for people with Django experience, not total beginners.</p><p>It covers four professional Django application from scratch, with increasing difficulty:</p><ul><li><strong>Blog Application</strong>: A complete blog with full Django basics (CRUD + authentication), comments, search, filters, tagging, sitemaps, RSS, Postgres setup with Docker.</li><li><strong>Social Website</strong>: a Pinterest clone with user likes, following system, social authentication, Django signals, messages, M2M relationships, infinite scroll with JavaScript, custom authentication.</li><li><strong>Ecommerce Application</strong>: A multi-language ecommerce website with Django sessions, the cart system, queues with Celery and RabbitMQ, payments with Stripe, custom views in the admin and custom context processors, PDF generation for invoices, and translations and internationalization (i18n).</li><li><strong>eLearning Saas</strong>: an eLearning SaaS with Redis cache, data models, model inheritence, CMS system, authorization and permissions, APIs with Django REST Framework, real-time chat functionality with WebSockets and Django Channels, custom middleware and management commands.</li></ul><p>If you are looking for a job as a Django developer, understanding, completing, and improving these projects give you an advantage because it is the most real-world experience that a book can provide. I still to this day refer to some chapters and concepts when I implement them in my projects.</p><p>Django video courses may also provide such projects on Udemy or Coursera. But I have never taken an online course on Django, so I cannot provide additional info on this.</p><p>In short, this is the book you should read to really grow your skills and understanding while learning Django.</p><h4>#5 <a href="https://simpleisbetterthancomplex.com/">Simple is Better Than Complex</a></h4><p>This is a super resource focused on the workings of Django. Although a little outdated, this website provides a lot of value. This website is more of an opinionated Django blog coming from an experienced developer trying to simplify complex topics. Hence the name, Simple is Better Than Complex.</p><p>This web blog is not a learning guide or book per se; it rather provides standalone tutorials. <a href="https://simpleisbetterthancomplex.com/tutorial/2019/01/03/how-to-use-date-picker-with-django.html">Need a Date Picker with Django?</a> There is a guide for that. <a href="https://simpleisbetterthancomplex.com/tutorial/2018/11/28/advanced-form-rendering-with-django-crispy-forms.html">Form rendering with Django Crispy Forms?</a> There is a guide for that. Want to learn Django with the author in the comics? <a href="https://simpleisbetterthancomplex.com/series/2017/09/04/a-complete-beginners-guide-to-django-part-1.html">There is a series for that.</a></p><p>This website is literally a <strong>goldmine</strong> for intermediate Django developers.</p><h4>#6 <a href="https://www.youtube.com/@bugbytes3923">BugBytes</a></h4><p>Need an up-to-date, relevant channel for Django? BugBytes is here. I especiialy like his course on Django &amp; htmx, where he builds a finance tracker app from scratch.</p><figure><img alt="Bug Bytes: Django &amp; htmx Series" src="https://cdn-images-1.medium.com/max/336/0*bVeIEqjmKSbnjDh4" /><figcaption>Bug Bytes: Django &amp; htmx Series</figcaption></figure><p>His tutorials, in addition to courses, are similar to the one Simple is Better Than Complex writes, albeit up-to-date and video-based. I quickly watch how the author implements a particular feature/logic, and incorporate in my own projects.</p><p>For quick concepts, this channel is very, very useful. I think (and hope) that the channel will grow much more in popularity.</p><h4>#7 <a href="https://djangochat.com/">Django Chat</a></h4><p>Most developers like listening to podcasts. William Vincent, the book author and and former board member, and Carlton Gibson, a former Django fellow, have run a Django podcast for 7 years now, with close to 200 episodes. The oldest episodes, up to around the first 50, were mostly on the core Django pieces: testing, cache, middleware, deployment, admin, URLs, Views, Models, and APIs. A very good resource to listen to during commute.</p><p>Then, they shifted focus on how Django is run, core Django people, how Django is being used in the wild. Django Chat covers a wide range of interesting topics you can listen to.</p><h4>#8 <a href="https://www.feldroy.com/two-scoops-of-django">Two Scoops of Django</a></h4><p>This is the book I am planning to read soon. It is not a project-based book, but a book of guidelines. It shows best practices from two experienced Django developers. It is said to be a very good reference book that Django developers still use. I included this book for the sake of completeness.</p><figure><img alt="Two Scoops of Django Book Cover" src="https://cdn-images-1.medium.com/max/560/0*hjSfyaRii2SNwWrD.jpg" /><figcaption>Two Scoops of Django Book Cover</figcaption></figure><h3>Conclusion</h3><p>I first got into Django because it looked fun. I stayed and learned Django because it helped me build projects I wanted.</p><p>Everyone has a different learning path. I included my own path and resources I personally used to get where I am now. I will continue building projects with Django, so this article will probably be updated in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e310d7ff941b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add UptimeRobot for your Django site — an ultra fast way.]]></title>
            <link>https://medium.com/@hmbarotov/add-uptimerobot-for-your-django-site-an-ultra-fast-way-339d6cbfb97b?source=rss-1e36d397faf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/339d6cbfb97b</guid>
            <category><![CDATA[uptime]]></category>
            <category><![CDATA[uptime-monitoring]]></category>
            <category><![CDATA[django-tips]]></category>
            <dc:creator><![CDATA[Hojiakbar Barotov]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 17:09:59 GMT</pubDate>
            <atom:updated>2026-05-29T12:36:08.267Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monitor Your Django Site with UptimeRobot</h3><p>Set up fast uptime checks and downtime alerts for a deployed Django app</p><figure><img alt="Django UptimeRobot tutorial" src="https://cdn-images-1.medium.com/max/1024/1*T9oHd21TKaMBMPoNtJD58Q.png" /><figcaption>Django UptimeRobot tutorial</figcaption></figure><h3>What is Uptime?</h3><p>From Wikipedia:</p><blockquote><strong>Uptime</strong> is a <a href="https://en.wikipedia.org/wiki/Measurement">measure</a> of system reliability, expressed as the period of <a href="https://en.wikipedia.org/wiki/System_time">time</a> a <a href="https://en.wikipedia.org/wiki/Machine">machine</a>, typically a <a href="https://en.wikipedia.org/wiki/Computer">computer</a>, has been continuously working and available. Uptime is the opposite of <a href="https://en.wikipedia.org/wiki/Downtime">downtime</a>.</blockquote><p>In simple terms, uptime measures how long your website is running without downtime. If your website goes down for 10 minutes in a day for whatever reason (system updates, server errors, etc), then your site is working for 1,430 minutes a day — or for 99.31%. This percentage is your uptime measure.</p><p>This translates to 300 minutes of downtime in a month, or 3650 minutes of downtime in a year. The optimal measure of course depends on the nature of your application: 300 minutes of downtime in a medium-sized web log is a minor inconvenience but possibly a huge amount of lost revenue for an e-commerce site.</p><p>Uptime is closely tied to the concept of High Availability (HA). This is where the <a href="https://en.wikipedia.org/wiki/High_availability#Percentage_calculation">nines</a> come into play. As of now, the highest nines are 12 nines: this means the site is down only for <strong>31.56 microseconds in a year! </strong>This is the gold standard of uptime that is achieved only by the biggest websites, like Google, Amazon, and Instagram.</p><figure><img alt="High Availability Table" src="https://cdn-images-1.medium.com/max/576/0*-HhFBqWf7ICKjK3f.png" /><figcaption>High Availability Table</figcaption></figure><p>In a production environment, everything that can go wrong will go wrong. There are a million things that can go wrong: database updates, broken code, server upsize, etc. Therefore, the uptime measure is not a silver bullet for how well your site is working. It does not measure performance, usability, usefulness of a web application. It just measures the uptime status of your application over a period of time.</p><h3>What is UptimeRobot?</h3><p>So, how do we measure the uptime status of our application? Usually, by depending on the external service that checks for the status of our site. This type of service works by sending periodic requests, usually in every 30 seconds to 5 minutes and checking the status code of the HTTP responses.</p><p>There are <a href="https://medium.com/@cbartlett/9-free-uptime-robot-alternatives-you-should-consider-in-2025-0eb04a1e7357">several services</a> that offer status monitoring online. They each have similar core features and a few niche features. That said, UptimeRobot is arguably the go-to tool for this task. It provides a free status monitoring service and can handle very large websites as well.</p><figure><img alt="UptimeRobot Monitoring Page" src="https://cdn-images-1.medium.com/max/1024/1*4aO6zPw0TCjki6zIl_rPCw.png" /><figcaption>UptimeRobot Monitoring Page</figcaption></figure><p>UptimeRobot is a deep and customizable SaaS. It provides status monitoring, status reporting, incident management, maintenance windows, and API &amp; integrations. However, most features are not included under the free plan.</p><p>For example, here is an <a href="https://stats.uptimerobot.com/Lwhf9FucX9">example status page</a> for my Django website:</p><figure><img alt="UptimeRobot Status Report Page" src="https://cdn-images-1.medium.com/max/1024/1*EQPRraJZMuR75GekAu0MNw.png" /><figcaption>UptimeRobot Status Report Page</figcaption></figure><p>The beauty of such a service is that it can differentiate between different HTTP responses. Generally, status codes from 200 to 399 are <em>success </em>HTTP responses; they mean the website is up and returning something sensible. 400–599 usually mean something is broken: either something is wrong on the client side or the server side. UptimeRobot can report these cases, although not detailed like Sentry.</p><p>In the rest of the article, I am going to show how we can implement a very simple, yet efficient Django endpoint for UptimeRobot so that we can check for uptime status. First of all, register for a free account on UptimeRobot <a href="https://dashboard.uptimerobot.com/sign-up?ref=header">here</a>.</p><h3>Implementing UptimeRobot for Django</h3><p>Assuming you have already registered and have a Django project deployed on the web, we can continue.</p><p>In the free plan, as of this writing, UptimeRobot supports up to 50 endpoints. Usually, in a simple Django application you need only a few endpoints to check for uptime.</p><p>Initially, it might make sense to use the homepage/landing page as the main endpoint to check. After all, it is the main page most people land on. It should be up and running at all times!</p><p>While it makes sense to think like that, it is not entirely correct. The rule of thumbs is that, if one endpoint is running without a problem, then your landing page also is. This is because they share so much in common: the same architecture, database, server, and routes.</p><p>Therefore, it is very common to write a dead-simple Django view that just returns HTTP 200 for uptime monitoring. This is neat if you think about it; this approach avoids all the overhead that comes from HTTP request for the main page: HTML template rendering, CSS, JS, and image loading, the fetching of external libraries like Google Fonts.</p><p>So, for strict uptime monitoring, most Django developers write a small Django view like this:</p><pre># core/views.py<br><br>from django.http import HttpResponse<br>from django.views import View<br><br><br>class UpTimeCheckView(View):<br>    def get(self, request, *args, **kwargs):<br>        return HttpResponse(&quot;OK&quot;, content_type=&quot;text/plain&quot;)</pre><p>And they embed this in their url routing:</p><pre># urls.py<br><br>from core.views import UpTimeCheckView<br>from django.urls import include, path<br># Other imports go here... <br><br>urlpatterns = [<br>    path(&quot;uptime-check/&quot;, UpTimeCheckView.as_view(), name=&quot;uptime-check&quot;),<br>    # Other URLs go here...<br>]</pre><p>Elegenat, innit? Now, you put this endpoint in UptimeRobot. Here is how you get an uptime monitoring service in less than 10 minutes for your Django website.</p><p>Of course, this service is very configurable and scalable. But for the most part, this single endpoint is quite useful in determining how well your site is running over a period of time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=339d6cbfb97b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate htmx 2.0 with Django]]></title>
            <link>https://medium.com/@hmbarotov/integrate-htmx-2-0-with-django-e7825b3cfadd?source=rss-1e36d397faf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7825b3cfadd</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-htmx]]></category>
            <dc:creator><![CDATA[Hojiakbar Barotov]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 17:45:27 GMT</pubDate>
            <atom:updated>2026-05-29T12:31:15.482Z</atom:updated>
            <content:encoded><![CDATA[<p>HTML-first interactivity with django-htmx</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHs5T3DyGRmAxH0sA4gEnQ.png" /><figcaption>Django htmx 2.0 integration tutorial</figcaption></figure><h3>What is htmx?</h3><p>In case you didn’t know, <a href="https://htmx.org/">htmx</a> is a very popular fronted package that aims to</p><blockquote>give you access to <a href="https://htmx.org/docs/#ajax">AJAX</a>, <a href="https://htmx.org/docs/#css_transitions">CSS Transitions</a>, <a href="https://htmx.org/docs/#websockets-and-sse">WebSockets</a> and <a href="https://htmx.org/docs/#websockets-and-sse">Server Sent Events</a> directly in HTML, using <a href="https://htmx.org/reference/#attributes">attributes</a>, so you can build <a href="https://htmx.org/examples/">modern user interfaces</a> with the <a href="https://en.wikipedia.org/wiki/HATEOAS">simplicity</a> and <a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">power</a> of hypertext</blockquote><p>htmx is inherently a JavaScript package that lets you use modern browser features directly from HTML rather than having to use JS.</p><p>It achieves this feat by using hx- attributes directly inside any HTML tags. Traditionally, only <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a">&lt;a&gt;</a> &amp; <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form">&lt;form&gt;</a> can make HTTP requests. With htmx, it is possible to make requests with any HTML element without having to rely on JS.</p><p>htmx’s philosophy is of hypertext usage — <em>javascript fatigue: longing for a hypertext already in hand. </em>This package enables server-side developers to add interactivity to their websites without having to taking on commit complex JavaScript libraries, such as React or Vue, with deep learning curves.</p><p>This philosophy makes sense; why use a fully-fledged SPA framework when all you need is a bit of interactivity and UX enhancement? Most small-to-medium websites work just fine by sprinkling htmx on top of HTML. This explains the massive success of this package in the last 5 years.</p><h3>htmx with Django</h3><p>Django, being a dominant server-side web framework of Python, lands itself quite well to fully taking advantage of htmx. Traditionally, Django is a server-side framework that renders HTML files on the server, compared to only JSON in most API-first frameworks, such as <a href="https://fastapi.tiangolo.com/">FastAPI</a>.</p><p>Because of this HTML-first approach in traditional Django, htmx really shines. With an easy, consistent structure, self-evident hx- attributes, and superb documentation, you can transform your Django project into a smooth, interactive respectable software that does not depend on JavaScript.</p><p>However, if you know that you will have more than one client, i.e. a web client, Android, iOS, and/or a desktop, you are much better off starting with the API-first approach because htmx is bound to HTML, and logically, to the web. This ensures that you will have only one backend codebase that provides API access to various clients.</p><h3>htmx Integration</h3><p>In this guide, I am going to write a very short introduction on installing and integrating htmx with Django.</p><h4>Initial Setup</h4><p><em>All code snippets are available in </em><a href="https://github.com/HBarotov/coding-snippets/tree/main/django_testing"><em>this repository</em></a><em>. All terminal commands work with both Unix-based systems and Windows. Where they don’t, notice is given.</em></p><p>Assuming Python (≥3.6) is installed, create a directory:</p><pre>$ mkdir django_htmx_integration &amp;&amp; cd django_htmx_integration</pre><p>Next, create a virtual environment and install <strong>Django 5.2</strong>. Then generate a requirements.txt file to record the Python packages installed in your project. Finally, check Django’s version to confirm that the installation was successful:</p><pre># Windows<br>$ python -m venv .venv<br>$ .venv\Scripts\Activate.ps1<br>(.venv) $ python -m pip install django==5.2<br>(.venv) $ python -m pip freeze &gt; requirements.txt<br>(.venv) $ python -m django --version<br>5.2.9<br><br># MacOS/Linux<br>$ python3 -m venv .venv<br>$ source .venv/bin/activate<br>(.venv) $ python -m pip install django==5.2<br>(.venv) $ python -m pip freeze &gt; requirements.txt<br>(.venv) $ python -m django --version<br>5.2.9</pre><p>It’s also best practice to put sensitive or unnecessary files into .gitignore so they don’t get tracked by Git. Create a .gitignore file in your project root and add these lines:</p><pre># django_testing/.gitignore<br><br>__pycache__ # cached Python bytecode folders<br>*.pyc       # cached Python bytecode files<br>db.sqlite3  # default SQLite3 database file Django generates<br>.venv       # virtual environment</pre><p>These files aren’t useful in version control because they aren’t part of your production code.</p><h4>Django Project</h4><p>Create a Django project:</p><pre>(.venv) $ django-admin startproject django_project .<br>(.venv) $ python manage.py migrate<br>(.venv) $ python manage.py runserver</pre><p>Now, run the development server and visit <a href="http://localhost:8000/">http://localhost:8000/</a> in your browser. You should see Django’s welcome page if everything is set up correctly.</p><figure><img alt="Django Welcome Page" src="https://cdn-images-1.medium.com/max/1024/0*ch_t9I2BvOt0fhNp.png" /><figcaption>Django Welcome Page</figcaption></figure><p>Now create a templates/ directory to hold HTML files at the project level. Create a _base.html file that acts as a base file from which all other templates inherit. On Windows, you can do this directly in your code editor.</p><pre># MacOS/Linux<br>(.venv) $ mkdir templates<br>(.venv) $ touch templates/_base.html</pre><p>Now, populate our master HTML file as follows:</p><pre>&lt;!-- templates/_base.html --&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Django HTMX Integration&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    {% block content %}<br>    {% endblock content %}<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>htmx integration</h4><p>Actually, it is dead simple to integrate HTMX. You have 4 options — CDN, local copy, npm, or webpack, but as a Django developer, you will most probably</p><p>#1: <strong>Use CDN</strong>. This is the easiest approach. You just put &lt;script&gt; tag in your head in the master html:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Django HTMX Integration&lt;/title&gt;<br><br>    &lt;!-- HTMX JS --&gt;<br>    &lt;script<br>      src=&quot;https://cdnjs.cloudflare.com/ajax/libs/htmx/2.0.7/htmx.min.js&quot;<br>      integrity=&quot;sha512-IisGoumHahmfNIhP4wUV3OhgQZaaDBuD6IG4XlyjT77IUkwreZL3T3afO4xXuDanSalZ57Un+UlAbarQjNZCTQ==&quot;<br>      crossorigin=&quot;anonymous&quot;<br>      referrerpolicy=&quot;no-referrer&quot;<br>    &gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    {% block content %} {% endblock content %}<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>#2: <strong>Download a local copy. </strong>htmx is a very small project in size; you can download the package directly and put it somewhere your Django can find. Most likely, you will store your static files (CSS, JS, and website images) in a folder called <em>static. </em>This includes tweaking a few changes in the django_project/settings.py file:</p><pre># Static files (CSS, JavaScript, Images)<br># https://docs.djangoproject.com/en/5.2/howto/static-files/<br><br>STATIC_URL = &quot;/static/&quot;<br>STATICFILES_DIRS = [BASE_DIR / &quot;static&quot;]</pre><p>And creating a project-level <em>static </em>folder:</p><pre># MacOS/Linux<br>(.venv) $ mkdir static<br>(.venv) $ mkdir static/js</pre><p>Then, you can download a copy <a href="https://cdn.jsdelivr.net/npm/htmx.org@2.0.8/dist/htmx.min.js">from jsDelivr</a> and put it inside the <em>js </em>folder.</p><p>Finally, you can link it to the file inside your base HTML:</p><pre>&lt;!DOCTYPE html&gt;<br><br>{% load static %}<br><br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Django HTMX Integration&lt;/title&gt;<br><br>    &lt;!-- HTMX JS --&gt;<br>    &lt;script src=&quot;{% static &#39;js/htmx.min.js&#39; %}&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    {% block content %} {% endblock content %}<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Don’t forget to use {% load static %} , which loads static files into Django, or else it won’t work.</p><h4>django-htmx</h4><p>To fully take advantage of htmx in Django, use <a href="https://pypi.org/project/django-htmx/">django-htmx</a>. It is a set of extensions for using Django with htmx in more secure, comfortable, and effective ways.</p><p>First, install django-htmx:</p><pre>(.venv) $ python -m pip install django-htmx<br>Collecting django-htmx<br>  Downloading django_htmx-1.27.0-py3-none-any.whl (62 kB)<br>     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.1/62.1 KB 381.8 kB/s eta 0:00:00<br>Requirement already satisfied: django&gt;=4.2 in ./.venv/lib/python3.10/site-packages (from django-htmx) (5.2.9)<br>Requirement already satisfied: asgiref&gt;=3.6 in ./.venv/lib/python3.10/site-packages (from django-htmx) (3.11.0)<br>Requirement already satisfied: typing_extensions&gt;=4 in ./.venv/lib/python3.10/site-packages (from asgiref&gt;=3.6-&gt;django-htmx) (4.15.0)<br>Requirement already satisfied: sqlparse&gt;=0.3.1 in ./.venv/lib/python3.10/site-packages (from django&gt;=4.2-&gt;django-htmx) (0.5.5)<br>Installing collected packages: django-htmx<br>Successfully installed django-htmx-1.27.0</pre><p>Second, add it to your <em>INSTALLED_APPS </em>in django_project/settings.py :</p><pre># django_project/settings.py<br><br>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    # 3rd party<br>    &#39;django_htmx&#39;,<br>]</pre><p>Then, add the middleware:</p><pre># django_project/settings.py<br><br>MIDDLEWARE = [<br>    &#39;django.middleware.security.SecurityMiddleware&#39;,<br>    &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,<br>    &#39;django.middleware.common.CommonMiddleware&#39;,<br>    &#39;django.middleware.csrf.CsrfViewMiddleware&#39;,<br>    &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,<br>    &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,<br>    &#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,<br>    # 3rd party<br>    &#39;django_htmx.middleware.HtmxMiddleware&#39;,<br>]</pre><p>With this basic setup, you will be good to go using htmx to augment your Django web applications.</p><p>htmx 2.0 is a relatively mature package that can make your Django application smooth and interactive with minimal amounts of code and overhead. For small projects or demo products, it works great. Even for medium-sized applications too.</p><p>In this short guide, we have seen htmx, Django, and their integration. With this setup, you will be able to use htmx for many use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7825b3cfadd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Impersonating users in Django with Django-Loginas]]></title>
            <link>https://medium.com/@hmbarotov/impersonating-users-in-django-with-django-loginas-e6ca20b4fbd3?source=rss-1e36d397faf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6ca20b4fbd3</guid>
            <category><![CDATA[django-login]]></category>
            <category><![CDATA[django-loginas]]></category>
            <category><![CDATA[impersonation]]></category>
            <category><![CDATA[django-hijack]]></category>
            <dc:creator><![CDATA[Hojiakbar Barotov]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 16:03:32 GMT</pubDate>
            <atom:updated>2026-05-29T12:25:05.270Z</atom:updated>
            <content:encoded><![CDATA[<h3>Impersonating Users in Django with django-loginas</h3><p>Add an admin-only login-as-user flow for support debugging</p><figure><img alt="Django-loginas tutorial" src="https://cdn-images-1.medium.com/max/1024/1*VWL_RH7nGwCe65VS1xLiSA.png" /><figcaption>Django-loginas tutorial</figcaption></figure><p>In your SaaS product, you often see users reporting problems you think impossible. You think you covered all the practical edge cases, and then comes this weird scenario from a customer. Replicating their issue is often both hard and slow; you want to debug and resolve it as quickly as possible.</p><p>Often, the best way is to see the problem from their perspective. What exactly is the problem? What steps did a user take to arrive at this problem? The straightforward approach is to login as that user. Rest assured, this does not mean you should get access to their email/password, or 2FA.</p><p>The goal is for site admins to login as that user without breaking ethical and legal boundaries: <em>impersonation. </em>You access your SaaS as ordinary users and see what they see. And resolve any problems. Remember, this very high-level access should be given only for site admins.</p><p>All major web frameworks provide a way for impersonation: <a href="https://github.com/404labfr/laravel-impersonate">laravel-impersonate</a> for Laravel, <a href="https://github.com/ankane/pretender">pretender</a> for Ruby on Rails, and <a href="https://github.com/django-hijack/django-hijack">django-hijack</a> or <a href="https://github.com/skorokithakis/django-loginas">django-loginas</a> for Django.</p><p>In this guide, we will implement django-loginas for our Django project to login as another user. But first, why django-loginas, and not django-hijack?</p><h3>Loginas or Hijack?</h3><p>Both Django packages are used to impersonate users, but they differ slightly in their use:</p><ul><li>Django-hijack is a fully-fledged impersonation tool for medium-to-large websites. Its security and control arebetter compared to django-loginas, and so is the complexity. Admins can impersonate through both admin and UI.</li><li>Django-loginas is a minimal admin button for superusers to impersonate non-superusers. Its dependency and maintenance are minimal. It is used for smaller websites.</li></ul><p>They are both excellent projects with active maintenance. Their only difference is their use case. To illustrate the concept of impersonation, I am using django-loginas.</p><h3>Django-loginas Setup</h3><p>This is somewhat a dated note, but if you are still using Python 2, use an earlier version of this project, up to 0.3.6.</p><p>First, assuming you already have a Django project running with user registration and authentication, install django-loginas with either uv or pip. I am going to use pip:</p><pre>$ pip install django-loginas<br>Collecting django-loginas==0.3.13<br>  Downloading django_loginas-0.3.13-py2.py3-none-any.whl.metadata (6.7 kB)<br>Downloading django_loginas-0.3.13-py2.py3-none-any.whl (22 kB)<br>Installing collected packages: django-loginas<br>Successfully installed django-loginas-0.3.13</pre><p>Then, add loginas to your INSTALLED_APPS :</p><pre># django_project/settings.py<br><br>INSTALLED_APPS = [<br>    # ...<br>    &quot;loginas&quot;,<br>    # ...<br>]</pre><p>Update your project_level <em>urls.py</em> file. Ensure urls from django-loginas comes before django admin urls:</p><pre># django_project/urls.py<br><br>from django.contrib import admin<br>from django.urls import include<br><br>urlpatterns = <br>    path(&#39;admin/&#39;, include(&#39;loginas.urls&#39;)),<br>    path(&#39;admin/&#39;, admin.site.urls),<br>  # ... the rest of your URLconf goes here ...<br>]</pre><p>Finally, if you have a Custom User, add the package’s template to its admin model so that our “<em>LOG IN AS USER” </em>button appears in the admin:</p><pre># accounts/admin.py<br><br>class YourUserAdmin(ModelAdmin):<br>    change_form_template = &#39;loginas/change_form.html&#39;</pre><p>At this point, we should be good to go. Visit the admin, navigate to a non-superuser, and you should see the “LOG IN AS USER” button:</p><figure><img alt="Django Loginas Button in Admin Panel" src="https://cdn-images-1.medium.com/max/1024/1*FrAaUigaxG0k4N8awT7Qug.jpeg" /><figcaption>Django Loginas Button in Admin Panel</figcaption></figure><p>Now, if we actually click that button, we are redirected to our website as the user <strong>nathan:</strong></p><figure><img alt="Logging in as the user nathan | Django Loginas" src="https://cdn-images-1.medium.com/max/1024/1*jJN9S1ksGXRpUj2aQ9Wt3w.jpeg" /><figcaption>Logging in as the user nathan | Django Loginas</figcaption></figure><p>Now, we successfully impersonated our target user.</p><h4>Django-loginas additional config</h4><p>Even though I said django-loginas is minimalistic, it still provides additional configuration for you if needed, without having to implement django-hijack at an earlier stage. You can refer to its documentation <a href="https://pypi.org/project/django-loginas/#description">here</a>.</p><p>That said, if you know you will need extensive monitoring, impersonation, and customization, it is better to take the time to start with django-hijack than to change the package in the middle of the project.</p><h3>Conclusion</h3><p>Impersonating users for debugging by superusers is the task you may sometimes find yourself in a real production setting. All major web frameworks provide this feature through community projects or built-in options.</p><p>In Django, we primarily use django-hijack or django-loginas for impersonation. Use the first third-party plugin when your web application is big and needs extensive customization and monitoring. Start with django-loginas when you need minimal setup for logging in as users for quick debugging.</p><p>But be careful who you give this access to. Be cautious.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6ca20b4fbd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Debug Toolbar: Configuration and Overview]]></title>
            <link>https://medium.com/@hmbarotov/django-debug-toolbar-configuration-and-overview-97dbe8279279?source=rss-1e36d397faf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/97dbe8279279</guid>
            <category><![CDATA[django-debugging]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-debug-toolbar]]></category>
            <dc:creator><![CDATA[Hojiakbar Barotov]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 16:34:59 GMT</pubDate>
            <atom:updated>2026-05-29T11:58:22.384Z</atom:updated>
            <content:encoded><![CDATA[<h3>Django Debug Toolbar: Configuration, Panels &amp; Local Debugging</h3><p>A practical overview of Debug Toolbar panels for Django development</p><figure><img alt="Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*iSzKqoUaXBo9DrvhBphzUA.png" /><figcaption>Django Debug Toolbar</figcaption></figure><p>In this guide, we are going to look at one of the most popular third-party projects in Django — Django Debug Toolbar — used for debugging Django applications <strong>locally</strong>. It is a must for any sizable web project or API endpoint you build with Django. In fact, it is <a href="https://learndjango.com/tutorials/10-most-used-django-packages">among the top 10 Django packages</a> installed through PyPI.</p><p>For <strong>production, </strong>you usually use <a href="https://sentry.io/welcome/">sentry.io</a> which monitors your Django application and catches errors in real-time. Indeed, Sentry that we know and use for our production Django was <a href="https://cra.mr/sentry-from-the-beginning/">inspired by</a> Django Debug Toolbar in around 2008.</p><p>We have two parts, the configuration and overview of the debug toolbar. Let’s dive in.</p><h3>Configuration</h3><p>Assuming you have created a Django project within a virtual environment, install Debug Toolbar with pip:</p><pre>(.venv) $ python -m pip install django-debug-toolbar<br>Collecting django-debug-toolbar<br>  Using cached django_debug_toolbar-6.0.0-py3-none-any.whl.metadata (4.5 kB)<br>Requirement already satisfied: django&gt;=4.2.9 in ./.venv/lib/python3.12/site-packages (from django-debug-toolbar) (5.2.6)<br>Requirement already satisfied: sqlparse&gt;=0.2 in ./.venv/lib/python3.12/site-packages (from django-debug-toolbar) (0.5.3)<br>Requirement already satisfied: asgiref&gt;=3.8.1 in ./.venv/lib/python3.12/site-packages (from django&gt;=4.2.9-&gt;django-debug-toolbar) (3.9.1)<br>Using cached django_debug_toolbar-6.0.0-py3-none-any.whl (266 kB)<br>Installing collected packages: django-debug-toolbar<br>Successfully installed django-debug-toolbar-6.0.0</pre><p>The Django Debug Toolbar obviously depends on Django, so it first checks if Django is installed first. In my case, because I already have the toolbar in other projects, it uses its cached wheel, speeding up the installation.</p><p>If your Django/Python version is older, you may opt for older Django/Python versions. The latest toolbar requires Django 4.2.9 or above.</p><h4>Step 1: Check for Static Files</h4><p>The default core Django supports the Debug Toolbar out of the box, but check these two config in settings.py to be sure:</p><p>First, check that &#39;django.contrib.staticfiles&#39; is in your INSTALLED_APPS setting, and <a href="https://docs.djangoproject.com/en/stable/howto/static-files/">configured properly</a>:</p><pre># django_project/settings.py<br><br>INSTALLED_APPS = [<br>    # ...<br>    &quot;django.contrib.staticfiles&quot;,<br>    # ...<br>]<br><br>STATIC_URL = &quot;static/&quot;</pre><p>Second, make sure that your TEMPLATES setting contains a DjangoTemplates backend whose APP_DIRS options is set to True:</p><pre># django_project/settings.py<br><br>TEMPLATES = [<br>    {<br>        &quot;BACKEND&quot;: &quot;django.template.backends.django.DjangoTemplates&quot;,<br>        &quot;APP_DIRS&quot;: True,<br>        # ...<br>    }<br>]</pre><p>These settings are needed because the Toolbar depends on static files to work correctly.</p><h4>Step 2: Install the App</h4><p>Add debug_toolbar to your INSTALLED_APPS setting for Django to recognize it:</p><pre># django_project/settings.py<br><br>INSTALLED_APPS = [<br>    # ...<br>    &quot;debug_toolbar&quot;,<br>    # ...<br>]</pre><h4>Step 3: Add the URLs</h4><p>Add this tool’s URLs to the project’s URLS. Because the Debug Toolbar should only be used during local development, we include a DEBUG check as well:</p><pre># django_project/urls.py<br><br>from django.conf import settings<br>from django.urls import include<br><br>urlpatterns = [<br>  # ... the rest of your URLconf goes here ...<br>]<br><br>if settings.DEBUG:<br>    urlpatterns += [<br>        path(&quot;__debug__/&quot;, include(&quot;debug_toolbar.urls&quot;)),<br>    ]</pre><h4><strong>Step 4: Add the Middleware</strong></h4><p>Add the package to the start of your MIDDLEWARE setting:</p><pre># django_project/settings.py<br><br>MIDDLEWARE = [<br>    # ...<br>    &quot;debug_toolbar.middleware.DebugToolbarMiddleware&quot;,<br>    # ...<br>]</pre><p>The Debug Toolbar should come as early as possible as it analyzes the request/response firsthand. From the documentation:</p><blockquote>The order of MIDDLEWARE is important. You should include the Debug Toolbar middleware as early as possible in the list. However, it must come after any other middleware that encodes the response’s content, such as <a href="https://docs.djangoproject.com/en/dev/ref/middleware/#django.middleware.gzip.GZipMiddleware"><strong>GZipMiddleware</strong></a>.</blockquote><h4>Step 5: Add Internal IPs</h4><p>The Toolbar is shown only if your IP address is listed in Django’s <a href="https://docs.djangoproject.com/en/dev/ref/settings/#std-setting-INTERNAL_IPS"><strong>INTERNAL_IPS</strong></a> setting. For local development, you must add 127.0.0.1 , localhost, to the setting. Create this setting in your settings.py :</p><pre># django_project/settings.py<br><br>INTERNAL_IPS = [<br>    # ...<br>    &quot;127.0.0.1&quot;,<br>    # ...<br>]</pre><p>If you use Docker, which is a different environment than your localhost, you should add this:</p><pre># django_project/settings.py<br><br>import socket<br><br># Debug toolbar config<br>hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())<br>INTERNAL_IPS = [ip[:-1] + &quot;1&quot; for ip in ips]</pre><p>So far, this should work. Run your development server and access your web page. You should see a small Debug Toolbar icon on the right of the page:</p><figure><img alt="The Django Debug Toolbar Icon" src="https://cdn-images-1.medium.com/max/82/1*gi2zuDaoHkxEVn6tzuuPWQ.png" /><figcaption>The Django Debug Toolbar Icon</figcaption></figure><p>Now, we are good to go.</p><h3>Debug Toolbar Overview</h3><p>The Toolbar gives you default panels on installation, which you can change by DEBUG_TOOLBAR_SETTINGS :</p><pre># django_project/settings.py<br><br>DEBUG_TOOLBAR_PANELS = [<br>    &#39;debug_toolbar.panels.history.HistoryPanel&#39;,<br>    &#39;debug_toolbar.panels.versions.VersionsPanel&#39;,<br>    &#39;debug_toolbar.panels.timer.TimerPanel&#39;,<br>    &#39;debug_toolbar.panels.settings.SettingsPanel&#39;,<br>    &#39;debug_toolbar.panels.headers.HeadersPanel&#39;,<br>    &#39;debug_toolbar.panels.request.RequestPanel&#39;,<br>    &#39;debug_toolbar.panels.sql.SQLPanel&#39;,<br>    &#39;debug_toolbar.panels.staticfiles.StaticFilesPanel&#39;,<br>    &#39;debug_toolbar.panels.templates.TemplatesPanel&#39;,<br>    &#39;debug_toolbar.panels.alerts.AlertsPanel&#39;,<br>    &#39;debug_toolbar.panels.cache.CachePanel&#39;,<br>    &#39;debug_toolbar.panels.signals.SignalsPanel&#39;,<br>    &#39;debug_toolbar.panels.redirects.RedirectsPanel&#39;,<br>    &#39;debug_toolbar.panels.profiling.ProfilingPanel&#39;,<br>]</pre><p>However, for most beginner to intermediate projects, you do not need to add anything else. You might want to trim some if you are sure you won’t be using a panel or two, such as cache or signals .</p><p>We are going to use the <em>same web page (localhost:8000/en/groups/) </em>to look at each panel one by one. The page is a fairly complex page with database connections, templates, and logic. Currently, it looks like this:</p><figure><img alt="Our sample Django page for Django Debug Toolbar tutorial" src="https://cdn-images-1.medium.com/max/1024/1*p6IJfX367iTfRZy0l-z1Kg.png" /><figcaption>Our sample Django page for Django Debug Toolbar tutorial</figcaption></figure><p>Let’s start with each panel.</p><h4>History</h4><p>The History panel gives you a history of requests made during this session. It reports response <em>time, method, path, variables, and status. </em>This panel also provides a way to switch to different requests, making navigation between requests easy.</p><p>The most helpful of these is <em>Requests Variables, </em>which provides context variables returned as part of response.</p><figure><img alt="History Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*duPAFj8_c7Lq8wonuigY-Q.png" /><figcaption>History Panel for Django Debug Toolbar</figcaption></figure><h4>Versions</h4><p>The Versions panel shows the versions of Django, Python, and installed apps only in your settings.py . Note that this doesn’t show <em>all third-party packages</em> used in your project. pip freeze &gt; requirements.txt is a common approach to see them if you use pip .</p><figure><img alt="Versions Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*uED43UgES7cLVNtDqYu6UA.png" /><figcaption>Versions Panel for Django Debug Toolbar</figcaption></figure><h4>Time</h4><p>This panel shows the breakdown of time spent in various places. In a slow request, this gives you information where you are losing milliseconds. Note that this panel works minimally (no breakdowns) on Windows because Windows does not support the resources module.</p><figure><img alt="Versions Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*6kYG_cUuAi0FFF4KycrjYg.png" /><figcaption>Versions Panel for Django Debug Toolbar</figcaption></figure><h4>Settings</h4><p>This is the panel why you should <strong>never, ever </strong>use Django Debug Toolbar in production. This panel shows all the settings defined in your Django project. In the hands of an experienced hacker, this is really a treasure map.</p><figure><img alt="Settings Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*K_82GSNOuZLVnCpewpV7xw.png" /><figcaption>Settings Panel for Django Debug Toolbar</figcaption></figure><h4>Headers</h4><p>This panel shows the metadata — headers of both request and response headers. They give full data about what is being passed back and forth, including sensitive tokens, ids, and cookies. You see why we stress that the Toolbar is only for local development?</p><figure><img alt="Headers Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*X5BPTBJDvSee7mMaONJsvA.png" /><figcaption>Headers Panel for Django Debug Toolbar</figcaption></figure><p>For example, this particular request is made from browser Brave on a Linux desktop from the localhost. The response headers contain similar information.</p><h4>Request</h4><p>This particular section is all about the request — function, args, kwargs, cookies, session, and so forth — that can be quite useful to understand what we are trying to send for and get from the server.</p><figure><img alt="Request Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*rhxttzZM4WElVASUEoG9tA.png" /><figcaption>Request Panel for Django Debug Toolbar</figcaption></figure><h4>SQL</h4><p>The SQL tab is arguably the most used and useful of all, because it shows all the queries from the database in your page. Middle-level and senior developers spend quite a bit of time optimizing their queries, and this panel is the golden pot.</p><figure><img alt="SQL Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*2o38QL5A5rep3FVEjCbJ3A.png" /><figcaption>SQL Panel for Django Debug Toolbar</figcaption></figure><p>You can see which queries are being sent, in which order, and the exact query run by your database. The Expl button next to a query is equivalent to SQL’s EXPLAIN command, which is the key to debugging more complex queries:</p><figure><img alt="SQL Explain of Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*UgMSfzswjDujKYbwtDqTvA.png" /><figcaption>SQL Explain of Django Debug Toolbar</figcaption></figure><p>Also, this panel shows SQL problems of duplicate and “n+1” queries by default. Because this page is already optimized (see the last two big queries), we don’t see it here.</p><h4>Static files</h4><p>This section is self-explanatory; you can see all the info about static files (CSS, JS, images) used in your Django project. It also shows static files of third-party packages, such as Django Debug Toolbar or Rosetta (used for translations in the admin).</p><figure><img alt="Static files Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*u4pQB8TnijpD-JUur8PLhw.png" /><figcaption>Static files Panel for Django Debug Toolbar</figcaption></figure><h4>Templates</h4><p>Templates shows the templates rendered for this page, as well as their context variables. Currently, 53 of them are used to render this single page, which is quite a big number. Although the majority comes from Bootstrap 5, this is a potential performance problem which I could take time to look at.</p><figure><img alt="Templates Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*IT-2OV1_Y409A7mwYYre4A.png" /><figcaption>Templates Panel for Django Debug Toolbar</figcaption></figure><p>You now see how beneficial the Toolbar can be in identifying bugs and bottlenecks? I identified a potential problem in my side project writing about Django Debug Toolbar :)</p><h4>Alerts</h4><p>This is a panel I have never used personally. I imagine this panel has its own use cases.</p><p>From the documentation:</p><blockquote>This panel shows alerts for a set of pre-defined cases:</blockquote><blockquote>Alerts when the response has a form without the enctype=&quot;multipart/form-data&quot; attribute and the form contains a file input.</blockquote><figure><img alt="Alerts Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*avtRlOgcgr7GQA_7L9FMSQ.png" /><figcaption>Alerts Panel for Django Debug Toolbar</figcaption></figure><h4>Cache</h4><p>This is another prominent panel from the Toolbar that shows cache information. Because this particular view has no cache associated with it, it is now empty. In other cases, you would use this panel to check if your cache backend worked successfully.</p><figure><img alt="Cache Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*qIJLuq8gkf2SAK0PCnwiNw.png" /><figcaption>Cache Panel for Django Debug Toolbar</figcaption></figure><p>Note that if you use per-site caching in Django (i.e. cache everything in your Django site), this panel is incompatible with that scenario.</p><h4>Signals</h4><p>Signals are more intermediate concepts in Django. Essentially, they do something when an event occurs in another part of your application that you don’t have control over.</p><p>For example, when a user signs up in your site, you may want to use a signal to create a profile for them automatically. You do not have control over the core Django, so it is a safer and better bet to use a signal in this case.</p><figure><img alt="Signals Panel for Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*msEu-PSuigVLSNc8X49Yew.png" /><figcaption>Signals Panel for Django Debug Toolbar</figcaption></figure><p>We are seeing 46 receivers of 15 signals because Django uses signals under the hood for various purposes. If we defined a custom signal, we would see its name listed here as well.</p><h4>Intercept redirects</h4><p>This is a toggle, not a panel. If turned on, this shows you an intermediate page before redirecting.</p><p>This particular project uses internationalization — support for different languages — and by default redirects users to en/ , ru/ , or uz/ based on their browser language setting. In case their language is not supported by the site, it falls back to en/</p><p>Now, look what happens if we go to <em>localhost:8000 </em>without a language prefix with this option on:</p><figure><img alt="Intercept redirects of Django Debug Toolbar" src="https://cdn-images-1.medium.com/max/1024/1*vxZOsscY1hzuWRUKs26usg.png" /><figcaption>Intercept redirects of Django Debug Toolbar</figcaption></figure><p>It gives an intermediary page for this redirect, which can be helpful for solving bugs related to redirects.</p><h4>Profiling</h4><p>Profiling is a big, advanced topic in programming. Essentially, it is about measuring how a program actually uses resources when it runs. This tab is included, but inactive by default. Advanced Django developers can use it to see how the program behaves when it is run.</p><h3>Customization</h3><p>While Django Debug Toolbar is quite mature and helpful, you can customize it however you want. <a href="https://django-debug-toolbar.readthedocs.io/en/latest/panels.html#third-party-panels">The official docs</a> have references to third-party panels that can be added depending on your needs.</p><p>The base package gives you almost everything you need for a small-to-medium Django project. While it is possible to add additional panels, think if you really need them.</p><h3>Conclusion</h3><p>The Django Debug Toolbar is a superb third-party package that every Django project uses during development for debugging and performance optimization. It is easy to install, use, and customize, and <strong>free.</strong></p><p>This post was a beginner-friendly introduction to using and interpreting Django Debug Toolbar. Check out <a href="https://django-debug-toolbar.readthedocs.io/en/latest/index.html">its documentation</a> for advanced usage and customization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97dbe8279279" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing Django with uv, Postgres, and Redis]]></title>
            <link>https://medium.com/@hmbarotov/dockerizing-django-with-uv-postgres-and-redis-e1dd9abe9640?source=rss-1e36d397faf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1dd9abe9640</guid>
            <category><![CDATA[django-docker]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[uv]]></category>
            <category><![CDATA[dockerize]]></category>
            <dc:creator><![CDATA[Hojiakbar Barotov]]></dc:creator>
            <pubDate>Sat, 17 May 2025 07:13:22 GMT</pubDate>
            <atom:updated>2026-05-29T11:41:42.456Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical Docker Compose setup for local development</p><figure><img alt="Django Docker tutorial" src="https://cdn-images-1.medium.com/max/1024/1*d6M7UMkMGUtYzlvP5U8iwA.png" /><figcaption>Django Docker tutorial</figcaption></figure><p>As <strong>uv</strong> positions itself as <em>the one tool to manage them all</em> in the Python ecosystem, more developers are adopting it as part of their Docker workflows to speed up build times.</p><p>If you haven’t heard of it yet, <strong>uv</strong> is an extremely fast and convenient Python package manager — written in Rust and developed by Astral (the company behind the linter <strong>ruff</strong>). It replaces multiple Python tools, such as pip and venv, and brings a standardized, blazing-fast approach to Python package management.</p><p>This has been a real game-changer, as uv is on its way to solving packaging problems that have frustrated Python developers for decades.</p><p>In this post, we’ll dockerize a <strong>Django project from scratch</strong> with <strong>uv</strong>, <strong>Postgres</strong>, and <strong>Redis</strong>. While the guide is beginner-friendly, advanced developers can also benefit from the ready-to-use boilerplate for local development.</p><p>Let’s get started.</p><h3>uv</h3><p>There are <a href="https://docs.astral.sh/uv/getting-started/installation/">multiple ways</a> to install <strong>uv</strong>, but the easiest is through the standalone installer provided by Astral.</p><pre># MacOS / Linux<br>$ curl -LsSf https://astral.sh/uv/install.sh | sh<br><br># Windows<br>$ powershell -ExecutionPolicy ByPass -c &quot;irm https://astral.sh/uv/install.ps1 | iex&quot;</pre><p>Once installed, verify the installation by running:</p><pre>$ uv --version<br>uv 0.8.14</pre><p>If you see a version number, you’re good to go.</p><h4>uv config</h4><p><em>All code snippets are available in </em><a href="https://github.com/hmbarotov/coding-snippets/tree/main/django_docker"><em>this repository</em></a><em>. All terminal commands work with both Unix-based systems and Windows. Where they don’t, notice is given.</em></p><p>Create the project folders and initialize uv:</p><pre># MacOS / Linux<br><br># create a root folder and an app folder for Django code<br>$ mkdir django_docker &amp;&amp; cd django_docker<br>$ mkdir app &amp;&amp; cd app<br><br># initialize a uv-managed project (uses Python 3.12; downloads it if missing)<br>$ uv init --python 3.12<br>$ uv venv<br><br># activate the environment<br>$ source .venv/bin/activate<br><br># Windows<br># Create directories in your code editor and change directories to app.<br>$ uv init --python 3.12<br>$ uv venv<br>$ .venv\Scripts\activate</pre><p>This will result in this <strong>app</strong> dirctory:</p><pre>app/<br>├── pyproject.toml     # base dependencies you declare (e.g., Django)<br>├── uv.lock            # fully resolved, pinned dependency graph<br>├── .python-version    # Python version uv uses for this project<br>├── .venv/             # virtual environment managed by uv<br>└── README.md          # Project description</pre><h4>Django Project</h4><p>Install Django:</p><pre>$ uv add django<br>Using CPython 3.12.11<br>Creating virtual environment at: .venv<br>Resolved 5 packages in 7ms<br>Installed 3 packages in 125ms<br> + asgiref==3.9.1<br> + django==5.2.5<br> + sqlparse==0.5.3</pre><p>When you open pyproject.toml, you’ll see <strong>Django</strong> added to your base dependencies:</p><pre>[project]<br>name = &quot;app&quot;<br>version = &quot;0.1.0&quot;<br>description = &quot;Add your description here&quot;<br>readme = &quot;README.md&quot;<br>requires-python = &quot;&gt;=3.12&quot;<br>dependencies = [<br>    &quot;django&gt;=5.2.5&quot;, # Django added<br>]</pre><p>uv also creates a verbose uv.lock file that records the <strong>entire resolved dependency tree</strong>. Django is a top-level dependency, which in turn depends on packages like <strong>asgiref</strong>—and uv.lock pins all of those versions for reproducible installs.</p><p>Create the Django project:</p><pre>$ uv run django-admin startproject django_project .</pre><p>Use uv run to execute django-admin inside the uv-managed environment. We include the trailing dot (.) to place the generated files in the <strong>current directory</strong> (the app/ folder), giving you a top-level package named django_project.</p><p>Create a .gitignore in the project root to keep unnecessary or sensitive files out of version control:</p><pre># Python bytecode / cache<br>__pycache__/<br>*.pyc<br>*.pyo<br>*.pyd<br>.python-version<br><br># Virtual environments<br>.venv/<br><br># Django<br>db.sqlite3<br>media/<br>staticfiles/<br><br># pytest / tools<br>.pytest_cache/<br>.ruff_cache/<br><br># OS / editors<br>.DS_Store<br>.idea/<br>.vscode/<br><br># Env files (keep secrets out of Git)<br>.env<br>.env.*</pre><p>Now, let’s configure <strong>Docker</strong>.</p><h3>Docker Config</h3><p>Installing Docker varies by OS and deserves its own guide. Use the <a href="https://docs.docker.com/engine/install/"><strong>official Docker documentation</strong></a> for your platform. Once Docker is installed and running, continue below.</p><p>Create a Dockerfile inside app/ :</p><pre># MacOS/Linux<br>$ touch Dockerfile</pre><p>This is where we configure <strong>uv</strong> inside Docker.</p><pre># pull official base image<br>FROM python:3.12-slim-bookworm<br><br># set work directory<br>WORKDIR /app<br><br># set environment variables<br>ENV PYTHONDONTWRITEBYTECODE=1 \<br>    PYTHONUNBUFFERED=1 \<br>    UV_LINK_MODE=copy \<br>    UV_PYTHON_DOWNLOADS=never \<br>    UV_PROJECT_ENVIRONMENT=/app/.venv<br><br># install uv<br>COPY --from=ghcr.io/astral-sh/uv:0.8.14 /uv /uvx /bin/<br><br># Since there&#39;s no point in shipping lock files, we move them<br># into a directory that is NOT copied into the runtime image.<br># The trailing slash makes COPY create `/_lock/` automagically.<br>COPY pyproject.toml uv.lock /_lock/<br><br># Synchronize dependencies.<br># This layer is cached until uv.lock or pyproject.toml change.<br>RUN --mount=type=cache,target=/root/.cache \<br>    cd /_lock &amp;&amp; \<br>    uv sync \<br>    --frozen \<br>    --no-install-project<br><br># copy project<br>COPY . .</pre><p><strong>Why these steps?</strong></p><ul><li>Your <strong>local OS and Docker</strong> are separate. A container starts empty, so we pull python:3.12-slim, set WORKDIR /app, and configure environment variables that help keep the image lean.</li><li>We <strong>install uv</strong>, copy pyproject.toml and uv.lock first, and run uv sync to install dependencies. This maximizes Docker layer caching.</li><li>Finally, we copy your code and define the default command.</li></ul><p>Create docker-compose.yml (at the project root, next to app/). docker-compose lets you manage multiple containers (services) together. Below, we define a <strong>web</strong> service for Django (using uv) for local development.</p><pre>services:<br>  web:<br>    build: ./app<br>    command: uv run manage.py runserver 0.0.0.0:8000<br>    volumes:<br>      - ./app/:/app/<br>    ports:<br>      - 8000:8000<br>    env_file:<br>      - ./.env.dev</pre><p>The docker-compose.yml file lets us manage multiple containers (services) from one place.</p><ul><li><strong>web service</strong> → builds from our app/ directory (where the Django code lives). We configure it with the command , ensuring that whenever the web service starts, the Django development server runs automatically inside the container.</li><li><strong>volumes</strong> → mount the local app/ folder into /app/ inside Docker. This way, any changes you make in your local code are immediately reflected inside the container.</li><li><strong>ports</strong> → map 8000:8000 so that: Your <strong>host machine</strong> (laptop) listens on port 8000. The <strong>web container</strong> also listens on port 8000.</li></ul><p>As a result, visiting <a href="http://localhost:8000/">http://localhost:8000/</a> in your browser connects you directly to the Django server running inside Docker.</p><figure><img alt="Django Welcome Page" src="https://cdn-images-1.medium.com/max/1024/1*fG8oDAi27NvHdNX2i98Ljg.png" /><figcaption>Django Welcome Page</figcaption></figure><p>Add .env.devat the project root. This file holds environment variables and secrets for <strong>local development</strong>.</p><pre>DEBUG=True<br>SECRET_KEY=secret_key<br>ALLOWED_HOSTS=localhost,127.0.0.1</pre><p>In production websites, you must use a strong, random secret key that is at least 50 characters long. This is critical because every other security feature in Django — such as password hashing, sessions, and more — relies on the secret key.</p><p>To manage secrets in Django, there are multiple third-party packages available, but here we’ll use <strong>django-environ</strong>. Install it with:</p><pre>$ uv add django-environ<br>Resolved 6 packages in 4ms<br>Installed 1 package in 1ms<br> + django-environ==0.12.0</pre><p>Next, open /app/django_project/settings.py and update it as follows:</p><pre>from pathlib import Path<br><br># Importing and reading env variables<br>from environ import Env<br><br>env = Env()<br>env.read_env()<br><br># Build paths inside the project like this: BASE_DIR / &#39;subdir&#39;.<br>BASE_DIR = Path(__file__).resolve().parent.parent<br><br><br># Quick-start development settings - unsuitable for production<br># See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/<br><br># SECURITY WARNING: keep the secret key used in production secret!<br>SECRET_KEY = env.str(&quot;SECRET_KEY&quot;) # Use env variable<br><br># SECURITY WARNING: don&#39;t run with debug turned on in production!<br>DEBUG = env.bool(&quot;DEBUG&quot;, default=False) # Using env variable<br><br>ALLOWED_HOSTS = env.list(&quot;ALLOWED_HOSTS&quot;) # Using env variable</pre><p>In the project root (next to .env.dev), create a .dockerignore file. This prevents unnecessary or sensitive files from being copied into the Docker image:</p><pre>.venv/<br>.git/<br>__pycache__/</pre><p>Build the image:</p><pre>$ docker compose build</pre><p>Once the build completes, start the container:</p><pre>$ docker compose up</pre><p>Now, open <a href="http://localhost:8000/">http://localhost:8000/</a> in your browser to see the Django welcome page again.</p><figure><img alt="Django Welcome Screen" src="https://cdn-images-1.medium.com/max/1024/1*FV4z87L87H3AZhxfbM-bKQ.png" /><figcaption>Django Welcome Screen</figcaption></figure><h3>Postgres</h3><p>If you’re a beginner, managing Postgres directly on your laptop can be a nightmare. With Docker, you can keep databases isolated in their own containers, making setup and cleanup much easier.</p><p>To install Postgres inside Docker, add a new service in docker-compose.yml:</p><pre>services:<br>  db:<br>    image: postgres:16.5<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data/<br>    environment:<br>      - POSTGRES_USER=dev_user<br>      - POSTGRES_PASSWORD=dev_password<br>      - POSTGRES_DB=dev_db<br>  web:<br>    build: ./app<br>    command: uv run manage.py runserver 0.0.0.0:8000<br>    volumes:<br>      - ./app/:/app/<br>    ports:<br>      - 8000:8000<br>    env_file:<br>      - ./.env.dev<br>    depends_on:<br>      - db<br><br>volumes:<br>  postgres_data:</pre><p>Here’s what this does:</p><ul><li>We define a <strong>db</strong> service running Postgres 16.5.</li><li>A <strong>volume</strong> (postgres_data) is mounted at /var/lib/postgresql/data/. This ensures that even if you stop the container, your database data persists. You won’t need to re-populate it every time you restart Docker during development.</li><li>The <strong>web</strong> service depends on db, meaning Django won’t start until Postgres is ready.</li></ul><p>For simplicity, we’ve hard-coded the database credentials here. This is fine for local development, but in production you should use stronger credentials and a secrets manager.</p><p>To connect Django to Postgres, we must use the same credentials in the web service. Update .env.dev with:</p><pre>DEBUG=True<br>SECRET_KEY=secret_key<br>ALLOWED_HOSTS=localhost,127.0.0.1<br>SQL_ENGINE=django.db.backends.postgresql # new<br>SQL_USER=dev_user # new<br>SQL_PASSWORD=dev_password # new<br>SQL_DATABASE=dev_db # new<br>SQL_HOST=db # new<br>SQL_PORT=5432 # new</pre><p>Update the DATABASES dictionary in <strong>app/django_project/settings.py</strong>:</p><pre># Database<br># https://docs.djangoproject.com/en/5.2/ref/settings/#databases<br><br>DATABASES = {<br>    &quot;default&quot;: {<br>        &quot;ENGINE&quot;: env.str(&quot;SQL_ENGINE&quot;, default=&quot;django.db.backends.sqlite3&quot;),<br>        &quot;NAME&quot;: env.str(&quot;SQL_DATABASE&quot;, default=BASE_DIR / &quot;db.sqlite3&quot;),<br>        &quot;USER&quot;: env.str(&quot;SQL_USER&quot;, default=&quot;user&quot;),<br>        &quot;PASSWORD&quot;: env.str(&quot;SQL_PASSWORD&quot;, default=&quot;password&quot;),<br>        &quot;HOST&quot;: env.str(&quot;SQL_HOST&quot;, default=&quot;localhost&quot;),<br>        &quot;PORT&quot;: env.str(&quot;SQL_PORT&quot;, default=&quot;5432&quot;),<br>    }<br>}</pre><p>This configuration ensures that if no environment variables are found, Django falls back to SQLite. Otherwise, it uses <strong>Postgres</strong> with the credentials from .env.dev. By default, Postgres listens on port <strong>5432</strong>, which we’ve specified.</p><p>To allow Python to connect to Postgres, Django requires a database driver. For a long time, the default was <strong>psycopg2</strong>, but we now use <strong>psycopg3</strong>, which includes async support, better performance, and other improvements.</p><p>Install it with:</p><pre>$ uv add &quot;psycopg[binary]&quot;<br>Resolved 9 packages in 268ms<br>Prepared 1 package in 316ms<br>Installed 3 packages in 4ms<br> + psycopg==3.2.9<br> + psycopg-binary==3.2.9<br> + typing-extensions==4.15.0</pre><p>Rebuild the image and run both containers in one step:</p><pre>$ docker compose up -d --build<br><br>...<br>#19 DONE 0.0s<br>[+] Running 5/5<br> ✔ django_docker-web                     Built                                                            0.0s <br> ✔ Network django_docker_default         Created                                                          0.1s <br> ✔ Volume &quot;django_docker_postgres_data&quot;  Created                                                          0.0s <br> ✔ Container django_docker-db-1          Started                                                          0.5s <br> ✔ Container django_docker-web-1         Started                                                          0.6s </pre><p>This starts both the <strong>web</strong> (Django) and <strong>db</strong> (Postgres) services together. Run the necessary 18 unapplied migrations:</p><pre>$ docker compose exec web uv run manage.py migrate --no-input<br><br>Operations to perform:<br>  Apply all migrations: admin, auth, contenttypes, sessions<br>Running migrations:<br>  Applying contenttypes.0001_initial... OK<br>  Applying auth.0001_initial... OK<br>  Applying admin.0001_initial... OK<br>  ...</pre><p>To confirm that Postgres data is being persisted in a Docker volume, run:</p><pre>$ docker volume inspect django_docker_postgres_data</pre><p>You should see output similar to this, showing the mount point and metadata for the volume:</p><pre>[<br>    {<br>        &quot;CreatedAt&quot;: &quot;2025-09-01T07:51:21+05:00&quot;,<br>        &quot;Driver&quot;: &quot;local&quot;,<br>        &quot;Labels&quot;: {<br>            &quot;com.docker.compose.config-hash&quot;: &quot;84f495dc3f92361b7907a1f796ce7a6801a277015c6b4e464ca6b1ff895d3451&quot;,<br>            &quot;com.docker.compose.project&quot;: &quot;django_docker&quot;,<br>            &quot;com.docker.compose.version&quot;: &quot;2.39.1&quot;,<br>            &quot;com.docker.compose.volume&quot;: &quot;postgres_data&quot;<br>        },<br>        &quot;Mountpoint&quot;: &quot;/var/lib/docker/volumes/django_docker_postgres_data/_data&quot;,<br>        &quot;Name&quot;: &quot;django_docker_postgres_data&quot;,<br>        &quot;Options&quot;: null,<br>        &quot;Scope&quot;: &quot;local&quot;<br>    }<br>]</pre><p>This means your Postgres data is safely stored in the volume, so it persists even if the container is stopped or removed.</p><h4>entrypoint.sh</h4><p>In short, an <strong>entrypoint.sh</strong> file is a shell script that defines the primary command or process to run when a Docker container starts. It’s a common Docker pattern used to prepare the container environment before starting the main application.</p><p>In our case, we’ll use entrypoint.sh to ensure the Postgres database is up and accepting connections before starting Django.</p><p>Create the file <strong>app/entrypoint.sh</strong>, next to your Dockerfile:</p><pre>#!/bin/sh<br><br>if [ &quot;$DATABASE&quot; = &quot;postgres&quot; ]<br>then<br>    echo &quot;Waiting for postgres...&quot;<br><br>    while ! nc -z $SQL_HOST $SQL_PORT; do<br>      sleep 0.1<br>    done<br><br>    echo &quot;PostgreSQL started&quot;<br>fi<br><br>exec &quot;$@&quot;</pre><p>This script:</p><ul><li>Checks if the DATABASE environment variable is set to postgres.</li><li>Waits until Postgres (at $SQL_HOST:$SQL_PORT) is ready to accept connections.</li><li>Proceeds to run the main container command.</li></ul><p>Make the script executable:</p><pre>$ chmod +x app/entrypoint.sh</pre><p>We grant execute permissions to all users (owner, group, and others) so Docker can run the script without permission issues:</p><p>Now, update your <strong>app/Dockerfile</strong> to copy and run this script when the container starts. Add these lines near the end of the file:</p><pre># pull official base image<br>FROM python:3.12-slim-bookworm<br><br># set work directory<br>WORKDIR /app<br><br># set environment variables<br>ENV PYTHONDONTWRITEBYTECODE=1 \<br>    PYTHONUNBUFFERED=1 \<br>    UV_LINK_MODE=copy \<br>    UV_PYTHON_DOWNLOADS=never \<br>    UV_PROJECT_ENVIRONMENT=/app/.venv<br><br># install system dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends netcat-traditional<br><br># install uv inside Docker<br>COPY --from=ghcr.io/astral-sh/uv:0.6.17 /uv /uvx /bin/<br><br># Since there&#39;s no point in shipping lock files, we move them<br># into a directory that is NOT copied into the runtime image.<br># The trailing slash makes COPY create `/_lock/` automagically.<br>COPY pyproject.toml uv.lock /_lock/<br><br># Synchronize dependencies.<br># This layer is cached until uv.lock or pyproject.toml change.<br>RUN --mount=type=cache,target=/root/.cache \<br>    cd /_lock &amp;&amp; \<br>    uv sync \<br>    --frozen \<br>    --no-install-project<br><br># copy entrypoint.sh<br>COPY ./entrypoint.sh .<br>RUN sed -i &quot;s/\r$//g&quot; /app/entrypoint.sh<br>RUN chmod +x /app/entrypoint.sh<br><br># copy project<br>COPY . .<br><br># run entrypoint.sh<br>ENTRYPOINT [&quot;/app/entrypoint.sh&quot;]</pre><p>We copy entrypoint.sh into the Docker image, strip any trailing whitespace, and set the correct permissions inside Docker. After copying the project code, we run the script before starting the main application.</p><p>This ensures that every time the container starts, entrypoint.sh runs first. It checks that Postgres is healthy before starting Django.</p><p>Finally, add DATABASE to your <strong>.env.dev</strong> file so the script knows which database to wait for:</p><pre>DEBUG=True<br>SECRET_KEY=secret_key<br>ALLOWED_HOSTS=localhost,127.0.0.1<br>SQL_ENGINE=django.db.backends.postgresql<br>SQL_USER=dev_user<br>SQL_PASSWORD=dev_password<br>SQL_DATABASE=dev_db<br>SQL_HOST=db<br>SQL_PORT=5432<br>DATABASE=postgres</pre><p>First, bring down the running containers and remove associated volumes:</p><pre>$ docker-compose down -v<br><br>[+] Running 4/4<br> ✔ Container django_docker-web-1       Removed                                                            0.4s <br> ✔ Container django_docker-db-1        Removed                                                            0.2s <br> ✔ Volume django_docker_postgres_data  Removed                                                            0.0s <br> ✔ Network django_docker_default       Removed                                                            0.2s </pre><blockquote>⚠️ <strong>Warning</strong>: The -v flag also removes the <strong>database volume</strong>. This means all your Postgres data will be deleted. Use this option with caution—most of the time you should avoid it to preserve your database.</blockquote><p>Now, rebuild the Docker image and start everything up again:</p><pre>$ docker compose up -d --build</pre><p>Navigate to <a href="http://localhost:8000/">http://localhost:8000/</a> to ensure it is working.</p><h3>Redis</h3><p><strong>Redis</strong> is an in-memory database with many use cases. In Django, it’s most commonly used as:</p><ul><li>A <strong>cache backend</strong> to speed up queries and template rendering.</li><li>A <strong>message broker</strong> for Celery, which lets you run time-consuming tasks (like sending emails) outside the main request/response cycle.</li></ul><p>Configuring Redis for Celery is a big topic on its own. Here, we’ll focus on setting up Redis in Docker for <strong>basic Django caching</strong>.</p><p>Define a new service called <strong>cache</strong>:</p><pre>services:<br>  db:<br>    image: postgres:16.5<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data/<br>    environment:<br>      - POSTGRES_USER=dev_user<br>      - POSTGRES_PASSWORD=dev_password<br>      - POSTGRES_DB=dev_db<br>  web:<br>    build: ./app<br>    command: uv run manage.py runserver 0.0.0.0:8000<br>    volumes:<br>      - ./app/:/app/<br>    ports:<br>      - 8000:8000<br>    env_file:<br>      - ./.env.dev<br>    depends_on:<br>      - db<br>      - cache<br><br>  cache: # new<br>    image: redis:7.2.4<br>    restart: always<br>    ports:<br>      - 6379:6379<br>    logging:<br>      driver: &quot;json-file&quot;<br>      options:<br>        max-size: &quot;50m&quot;<br>        max-file: &quot;3&quot;<br><br>volumes:<br>  postgres_data:</pre><p>This starts Redis alongside Postgres and Django. We define internal and external ports, logging, and the restart option. The web service now depends on both db and cache.</p><p>Django doesn’t ship with Redis support by default, so we install the official Python package:</p><pre>$ uv add redis<br>Using CPython 3.12.11<br>Resolved 10 packages in 510ms<br>Prepared 1 package in 490ms<br>Installed 1 package in 16ms<br> + redis==6.4.0</pre><p>In <strong>app/django_project/settings.py</strong>, add the Redis cache configuration:</p><pre># Cache config<br>CACHES = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;django.core.cache.backends.redis.RedisCache&quot;,<br>        &quot;LOCATION&quot;: &quot;redis://cache:6379&quot;,<br>    }<br>}<br><br>CACHE_MIDDLEWARE_ALIAS = &quot;default&quot;<br>CACHE_MIDDLEWARE_SECONDS = 60 * 60 * 24  # 24 hours<br>CACHE_MIDDLEWARE_KEY_PREFIX = &quot;django_project&quot;</pre><blockquote>Note: the LOCATION (redis://cache:6379) matches the cache service and port defined in docker-compose.yml.</blockquote><p>Stop and rebuild everything:</p><pre>$ docker compose down -v<br>$ docker compose up -d --build</pre><p>Finally, to ensure our <em>cache </em>is working, run this command:</p><pre>$ docker compose logs cache</pre><p>To confirm Redis is running, check its logs:</p><pre>cache-1  | 1:C 01 Sep 2025 03:07:37.341 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo<br>cache-1  | 1:C 01 Sep 2025 03:07:37.341 * Redis version=7.2.4, bits=64, commit=00000000, modified=0, pid=1, just started<br>cache-1  | 1:C 01 Sep 2025 03:07:37.341 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf<br>cache-1  | 1:M 01 Sep 2025 03:07:37.341 * monotonic clock: POSIX clock_gettime<br>cache-1  | 1:M 01 Sep 2025 03:07:37.342 * Running mode=standalone, port=6379.<br>cache-1  | 1:M 01 Sep 2025 03:07:37.343 * Server initialized<br>cache-1  | 1:M 01 Sep 2025 03:07:37.344 * Ready to accept connections tcp</pre><p>This confirms that Redis is running and ready to accept connections. The best way to verify caching in Django is to configure it and observe the results with <strong>django-debug-toolbar</strong>. This will show cached queries, templates, and other optimizations directly in your browser during development.</p><h3>Conclusion</h3><p>Dockerizing a Django project with <strong>uv</strong>, <strong>Postgres</strong>, and <strong>Redis</strong> is especially useful if you don’t want to install Postgres and Redis directly on your machine — a process that can be frustrating for beginners. On top of that, using <strong>uv</strong> speeds up image builds significantly.</p><p>In this tutorial, we focused on building a Docker setup <strong>from scratch</strong>. The boilerplate we created is a great starting point for experimenting with new ideas or running projects locally.</p><p>If you need a <strong>production-ready Docker setup</strong>, check out this excellent guide from <a href="https://testdriven.io/?utm_source=chatgpt.com">TestDriven.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1dd9abe9640" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>