<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Udemezue John - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Udemezue John - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 22:23:58 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/udemezue/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Revert a Migration in Django ]]>
                </title>
                <description>
                    <![CDATA[ So, you're working with Django, you've run a migration, and now something’s broken. Maybe you added a field that shouldn't be there. Maybe you renamed a model, and suddenly your database is a mess. Or maybe you're just experimenting and want to roll ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-revert-a-migration-in-django/</link>
                <guid isPermaLink="false">68781860a9407a5fe14ed384</guid>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Wed, 16 Jul 2025 21:23:44 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745937479722/d02a1abc-33b1-4506-8001-033b4ec43130.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>So, you're working with Django, you've run a migration, and now something’s broken. Maybe you added a field that shouldn't be there.</p>
<p>Maybe you renamed a model, and suddenly your database is a mess. Or maybe you're just experimenting and want to roll things back.</p>
<p>That’s where reverting migrations comes in.</p>
<p>Knowing how to undo a migration in Django is just as important as knowing how to make one. It’s not about being perfect – it’s about being able to fix mistakes fast, without panic. I've been there.</p>
<p>A single migration can break everything if it goes wrong. But the good news is, Django gives you tools to take a step back safely.</p>
<p>Let me walk you through how this works, using plain language and clear steps.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-exactly-is-a-migration-in-django">What Exactly Is a Migration in Django?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-revert-a-migration-in-django">How to Revert a Migration in Django</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-case-1-undo-a-migration-thats-already-been-applied">Case 1: Undo a Migration That’s Already Been Applied</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-case-2-undo-a-migration-you-havent-applied-yet">Case 2: Undo a Migration You Haven’t Applied Yet</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-special-case-reverting-all-migrations-reset-everything">Special Case: Reverting All Migrations (Reset Everything)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-scenario-fixing-a-broken-migration">Example Scenario: Fixing a Broken Migration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-pitfalls-and-how-to-avoid-them">Common Pitfalls (And How to Avoid Them)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-faqs">FAQs</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-can-i-revert-more-than-one-migration-at-a-time">Can I revert more than one migration at a time?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-do-i-know-which-migration-names-to-use">How do I know which migration names to use?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-is-reverting-migrations-safe">Is reverting migrations safe?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-further-resources">Further Resources</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-exactly-is-a-migration-in-django">What Exactly Is a Migration in Django?</h2>
<p>Before we can talk about undoing a migration, let’s make sure we’re on the same page.</p>
<p>A migration in Django is a record of changes to your database. It tracks what models you’ve added or changed, and applies those changes to your actual database using SQL (behind the scenes).</p>
<p>You usually create a migration with this command:</p>
<pre><code class="lang-bash">python manage.py makemigrations
</code></pre>
<p>And apply it like this:</p>
<pre><code class="lang-bash">python manage.py migrate
</code></pre>
<p>That’s when Django updates your database tables to match your models.</p>
<p>Now, what if you want to undo that last step?</p>
<h2 id="heading-how-to-revert-a-migration-in-django">How to Revert a Migration in Django</h2>
<p>Alright, here’s the main part. Let’s say you just ran a migration and want to undo it. There are two situations:</p>
<ol>
<li><p><strong>You applied the migration already and want to reverse it</strong></p>
</li>
<li><p><strong>You haven’t applied it yet and just want to delete it</strong></p>
</li>
</ol>
<p>Let’s handle both.</p>
<h3 id="heading-case-1-undo-a-migration-thats-already-been-applied">Case 1: Undo a Migration That’s Already Been Applied</h3>
<p>If you've already run <code>python manage.py migrate</code>, Django has changed your database.</p>
<p>To reverse that migration, use this:</p>
<pre><code class="lang-bash">python manage.py migrate your_app_name migration_name_before
</code></pre>
<p>Let me break that down:</p>
<ul>
<li><p><code>your_app_name</code> is the name of your Django app (like <code>blog</code>, <code>users</code>, or <code>store</code>)</p>
</li>
<li><p><code>migration_name_before</code> is the name of the migration <em>before</em> the one you want to undo</p>
</li>
</ul>
<p>Let’s go through an example.</p>
<p>Say you have these migrations for an app called <code>store</code>:</p>
<pre><code class="lang-python"><span class="hljs-number">0001</span>_initial.py  
<span class="hljs-number">0002</span>_add_price_to_product.py  
<span class="hljs-number">0003</span>_change_price_field.py
</code></pre>
<p>If you want to undo the <code>0003_change_price_field.py</code> migration, you’d run:</p>
<pre><code class="lang-bash">python manage.py migrate store 0002
</code></pre>
<p>That tells Django to roll back to migration <code>0002</code>, effectively undoing everything in <code>0003</code>.</p>
<p>Once that’s done, you’ll see output like:</p>
<pre><code class="lang-python">Operations to reverse:
   - Alter field price on product
</code></pre>
<p>And your database is back the way it was before <code>0003</code>.</p>
<h3 id="heading-case-2-undo-a-migration-you-havent-applied-yet">Case 2: Undo a Migration You Haven’t Applied Yet</h3>
<p>Maybe you ran <code>makemigrations</code>, but not <code>migrate</code>. So you just created the migration file and haven’t actually touched the database yet.</p>
<p>In that case, you can safely delete the migration file.</p>
<p>Just go into your app’s <code>migrations/</code> folder, and delete the unwanted migration file (for example: <code>0003_change_price_field.py</code>).</p>
<p>Then you can re-run <code>makemigrations</code> with the correct changes.</p>
<p>Quick tip: Don't delete <code>__init__.py</code> or the <code>0001_initial.py</code> file unless you know what you’re doing. That first one is usually required.</p>
<h2 id="heading-special-case-reverting-all-migrations-reset-everything">Special Case: Reverting All Migrations (Reset Everything)</h2>
<p>Sometimes you just want to wipe all the migrations and start over.</p>
<p>This is common when you're still in development, and your database structure is messy.</p>
<p>Here's how I usually do it:</p>
<ol>
<li><p><strong>Delete the migration files</strong> inside the <code>migrations/</code> folder of your app (except for <code>__init__.py</code>)</p>
</li>
<li><p><strong>Drop the database</strong> or just clear the tables if you're using SQLite or a test DB</p>
</li>
<li><p>Run:</p>
</li>
</ol>
<pre><code class="lang-bash">python manage.py makemigrations
python manage.py migrate
</code></pre>
<p>If you're using SQLite, you can also just delete the <code>.sqlite3</code> file and start fresh.</p>
<p>For PostgreSQL or MySQL, you'll need to drop and recreate the database, or reset it using a tool like <code>pgAdmin</code> or <code>DBeaver</code>.</p>
<h2 id="heading-example-scenario-fixing-a-broken-migration">Example Scenario: Fixing a Broken Migration</h2>
<p>Let’s say you added a new field to a model:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Product</span>(<span class="hljs-params">models.Model</span>):</span>
    name = models.CharField(max_length=<span class="hljs-number">100</span>)
    price = models.DecimalField(max_digits=<span class="hljs-number">6</span>, decimal_places=<span class="hljs-number">2</span>, default=<span class="hljs-number">0.00</span>)
</code></pre>
<p>You made a typo:</p>
<pre><code class="lang-python">price = models.DecimalField(max_digits=<span class="hljs-number">6</span>, decimal_places=<span class="hljs-number">2</span>, default=<span class="hljs-string">'free'</span>)
</code></pre>
<p>Oops. Django lets you do this:</p>
<pre><code class="lang-bash">python manage.py makemigrations store
python manage.py migrate
</code></pre>
<p>Then it breaks.</p>
<p>You can fix this by reverting:</p>
<pre><code class="lang-bash">python manage.py migrate store 0001
</code></pre>
<p>Then fix the typo in your model and run:</p>
<pre><code class="lang-bash">python manage.py makemigrations
python manage.py migrate
</code></pre>
<p>Back on track!</p>
<h2 id="heading-common-pitfalls-and-how-to-avoid-them">Common Pitfalls (And How to Avoid Them)</h2>
<ul>
<li><p><strong>Don’t just delete a migration without reversing it first</strong>. This can confuse Django.</p>
</li>
<li><p><strong>Always check which migrations are applied</strong> using:</p>
</li>
</ul>
<pre><code class="lang-bash">python manage.py showmigrations
</code></pre>
<ul>
<li><p><strong>Keep backups of your database</strong>, especially in production. Use tools like <code>pg_dump</code> or <code>mysqldump</code> if needed.</p>
</li>
<li><p><strong>Don't reset migrations in a live app</strong> unless you absolutely must. It can mess up production data.</p>
</li>
</ul>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-can-i-revert-more-than-one-migration-at-a-time">Can I revert more than one migration at a time?</h3>
<p>Yes! You just migrate back to the point <em>before</em> the migrations you want to undo.</p>
<p><strong>Example:</strong></p>
<p>You’ve applied:</p>
<pre><code class="lang-python">[X] <span class="hljs-number">0001</span>_initial  
[X] <span class="hljs-number">0002</span>_add_price_to_product  
[X] <span class="hljs-number">0003</span>_change_price_field  
[X] <span class="hljs-number">0004</span>_add_discount_field
</code></pre>
<p>To undo both <code>0004</code> and <code>0003</code>, run:</p>
<pre><code class="lang-python">python manage.py migrate store <span class="hljs-number">0002</span>
</code></pre>
<p>This rolls back both 0004 and 0003, leaving only 0001 and 0002 applied.</p>
<h3 id="heading-how-do-i-know-which-migration-names-to-use"><strong>How do I know which migration names to use?</strong></h3>
<p>Run <code>python manage.py showmigrations</code> And you’ll see a list like:</p>
<pre><code class="lang-python"> [X] <span class="hljs-number">0001</span>_initial
 [X] <span class="hljs-number">0002</span>_add_price_to_product
 [X] <span class="hljs-number">0003</span>_change_price_field
</code></pre>
<p>The <code>[X]</code> shows applied migrations. To undo <code>0003</code>, migrate back to <code>0002</code>.</p>
<h3 id="heading-is-reverting-migrations-safe"><strong>Is reverting migrations safe?</strong></h3>
<p>It is, as long as you haven’t made changes to data that depend on the migration. Always test in development before trying in production.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Reverting migrations in Django isn't scary once you get the hang of it. It's like using undo in a Word document – you just need to know how far back to go.</p>
<p>So now that you know how to revert a migration in Django, what’s the trickiest migration issue you've run into—and how did you fix it?</p>
<p>Shoot me a <a target="_blank" href="http://x.com/_udemezue/">message</a> – I’d love to hear your story.</p>
<h3 id="heading-further-resources">Further Resources</h3>
<ul>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/topics/migrations/">Official Django Migration Docs</a></p>
</li>
<li><p><a target="_blank" href="https://realpython.com/django-migrations-a-primer/">Django Migrations Primer by RealPython</a></p>
</li>
<li><p><a target="_blank" href="https://adamj.eu/tech/2021/04/27/django-migrations-dos-and-donts/">Common Django Mistakes and How to Avoid Them</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Activate Your Django Virtual Environment ]]>
                </title>
                <description>
                    <![CDATA[ If you’re starting with Django, one of the first steps you’ll hear about is activating a virtual environment. And if that sounds a little technical, don’t worry – I’m going to walk you through exactly what that means, why it matters, and how to do it... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-activate-your-django-virtual-environment/</link>
                <guid isPermaLink="false">6877da442945848c5461548c</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ virtualization ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Wed, 16 Jul 2025 16:58:44 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746123776834/337004ca-692e-4df9-89db-81e78a16c7fe.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you’re starting with Django, one of the first steps you’ll hear about is <em>activating a virtual environment</em>. And if that sounds a little technical, don’t worry – I’m going to walk you through exactly what that means, why it matters, and how to do it step-by-step, without any confusing terms.</p>
<p>I’ve helped a lot of people get started with Python and Django, and trust me: understanding virtual environments early on can save you tons of headaches later.</p>
<p>A virtual environment can help you keep your Django projects organized. It also avoids conflicts between different versions of packages, and gives you a cleaner way to manage your development tools.</p>
<p>By the end of this guide, you’ll not only know how to activate your virtual environment, but also why you should.</p>
<p>Let's get into it.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-a-virtual-environment-in-python">What Is a Virtual Environment in Python?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-use-a-virtual-environment">Why Use a Virtual Environment?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-set-up-and-activate-a-django-virtual-environment">How to Set Up and Activate a Django Virtual Environment</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-install-python-if-you-havent-yet">1. Install Python (If You Haven’t Yet)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-install-virtualenv-optional-but-useful">2. Install virtualenv (Optional but Useful)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-create-a-virtual-environment">3. Create a Virtual Environment</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-activate-the-virtual-environment">4. Activate the Virtual Environment</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-can-you-do-after-activating-it">What Can You Do After Activating It?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-deactivate-the-virtual-environment">How to Deactivate the Virtual Environment</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-faqs">FAQs</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-do-i-need-to-activate-the-environment-every-time">Do I need to activate the environment every time?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-if-activate-doesnt-work">What if activate Doesn’t work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-i-use-vs-code-or-another-editor-with-this">Can I use VS Code or another editor with this?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-bonus-tips">Bonus Tips</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-add-a-gitignore-file">Add a .gitignore File</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-requirementstxt">Use requirements.txt</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-helpful-resources">Helpful Resources</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-further-learning">Further Learning</a></p>
</li>
</ol>
<h2 id="heading-what-is-a-virtual-environment-in-python">What Is a Virtual Environment in Python?</h2>
<p>A virtual environment is like a private workspace just for your project. Instead of installing packages (like Django) globally for your whole computer, you install them inside this little bubble. That way, different projects don’t mess with each other.</p>
<p>Imagine you’re working on two Django projects: one needs Django 3.2 and the other needs Django 4.1. Without a virtual environment, you'd run into version conflicts. But with virtual environments, each project stays separate and clean.</p>
<h2 id="heading-why-use-a-virtual-environment">Why Use a Virtual Environment?</h2>
<p>Here’s why I <em>always</em> use one when working with Django:</p>
<ul>
<li><p>Keeps your project dependencies isolated.</p>
</li>
<li><p>Prevents version conflicts between different projects.</p>
</li>
<li><p>Makes it easy to manage and uninstall packages.</p>
</li>
<li><p>Most importantly, <strong>Django expects it</strong>, especially if you want to follow best practices.</p>
</li>
</ul>
<h2 id="heading-how-to-set-up-and-activate-a-django-virtual-environment">How to Set Up and Activate a Django Virtual Environment</h2>
<p>Let’s walk through the process from start to finish.</p>
<h3 id="heading-1-install-python-if-you-havent-yet">1. <strong>Install Python (If You Haven’t Yet)</strong></h3>
<p>You need Python 3.8 or later. You can check what version you have by opening your terminal and typing:</p>
<pre><code class="lang-bash">python --version
</code></pre>
<p>If you see something like <code>Python 3.11.7</code>You’re good.</p>
<p>If you don’t have Python, download it here:</p>
<p>👉 <a target="_blank" href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></p>
<p>Make sure to check the box <strong>“Add Python to PATH”</strong> during installation if you're on Windows.</p>
<h3 id="heading-2-install-virtualenv-optional-but-worth-knowing">2. Install <code>virtualenv</code> (Optional but Worth Knowing)</h3>
<p>Python includes a built-in tool called <code>venv</code>, and that’s what we’ll use in this tutorial.</p>
<p>However, some developers prefer <code>virtualenv</code> because:</p>
<ul>
<li><p>It works with older Python versions</p>
</li>
<li><p>It can be slightly faster in larger environments</p>
</li>
<li><p>It offers some additional flexibility</p>
</li>
</ul>
<p>To install <code>virtualenv</code> just run:</p>
<pre><code class="lang-bash">pip install virtualenv
</code></pre>
<p><strong>Note:</strong> You don’t need <code>virtualenv</code> for this tutorial, but it’s good to know about. We'll be using Python’s built-in <code>venv</code> going forward.</p>
<h3 id="heading-3-create-a-virtual-environment">3. <strong>Create a Virtual Environment</strong></h3>
<p>Now go to your Django project folder (or make one):</p>
<pre><code class="lang-bash">mkdir my_django_project
<span class="hljs-built_in">cd</span> my_django_project
</code></pre>
<p>Then run:</p>
<pre><code class="lang-bash">python -m venv venv
</code></pre>
<ul>
<li><p><code>python -m venv</code> uses Python’s built-in virtual environment module</p>
</li>
<li><p><code>venv</code> is the name of the folder that will store your environment (you can call it anything)</p>
</li>
</ul>
<p>This creates a folder called <code>venv/</code> in your project directory. That folder contains everything your virtual environment needs.</p>
<h3 id="heading-4-activate-the-virtual-environment">4. <strong>Activate the Virtual Environment</strong></h3>
<p>Here’s the part everyone asks about.</p>
<p>Activation depends on your operating system.</p>
<h4 id="heading-on-windows-cmd">On <strong>Windows (CMD)</strong>:</h4>
<pre><code class="lang-bash">venv\Scripts\activate
</code></pre>
<h4 id="heading-on-windows-powershell">On <strong>Windows (PowerShell)</strong>:</h4>
<pre><code class="lang-bash">.\venv\Scripts\Activate.ps1
</code></pre>
<h4 id="heading-on-mac-or-linux">On <strong>Mac or Linux</strong>:</h4>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> venv/bin/activate
</code></pre>
<p>After you activate it, your terminal prompt will change. It’ll look something like this:</p>
<pre><code class="lang-bash">(venv) your-computer-name:my_django_project username$
</code></pre>
<p>That <code>(venv)</code> at the beginning means the virtual environment is active.</p>
<h2 id="heading-what-can-you-do-after-activating-it">What Can You Do After Activating It?</h2>
<p>Now that it’s active, you can install Django (or anything else) just for this project:</p>
<pre><code class="lang-bash">pip install django
</code></pre>
<p>This installs Django inside the virtual environment, not globally.</p>
<p>To double-check:</p>
<pre><code class="lang-bash">pip list
</code></pre>
<p>You’ll see Django and any other installed packages listed there.</p>
<h2 id="heading-how-to-deactivate-the-virtual-environment">How to Deactivate the Virtual Environment</h2>
<p>When you’re done working, just type:</p>
<pre><code class="lang-bash">deactivate
</code></pre>
<p>That’s it. Your terminal goes back to normal, and your system’s Python is no longer linked to the project.</p>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-do-i-need-to-activate-the-environment-every-time"><strong>Do I need to activate the environment every time?</strong></h3>
<p>Yes, every time you open a new terminal session and want to work on your Django project, activate it again using the command for your OS.</p>
<h3 id="heading-what-if-activate-doesnt-work"><strong>What if</strong> <code>activate</code> <strong>Doesn’t work?</strong></h3>
<p>If you’re on Windows, PowerShell might block the script. Run this:</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Set-ExecutionPolicy</span> <span class="hljs-literal">-ExecutionPolicy</span> RemoteSigned <span class="hljs-literal">-Scope</span> CurrentUser
</code></pre>
<p>Then try activating again.</p>
<h3 id="heading-can-i-use-vs-code-or-another-editor-with-this"><strong>Can I use VS Code or another editor with this?</strong></h3>
<p>Absolutely. VS Code even detects your virtual environment automatically. You can select the interpreter from the bottom-left or by pressing <code>Ctrl+Shift+P</code> → “Python: Select Interpreter.”</p>
<h2 id="heading-bonus-tips">Bonus Tips</h2>
<h3 id="heading-add-a-gitignore-file">Add a <code>.gitignore</code> File</h3>
<p>If you're using Git, you don’t want to upload the <code>venv</code> folder to GitHub. Add this line to your <code>.gitignore</code> file:</p>
<pre><code class="lang-python">venv/
</code></pre>
<h3 id="heading-use-requirementstxt">Use <code>requirements.txt</code></h3>
<p>Once you’ve installed your project’s packages, freeze them like this:</p>
<pre><code class="lang-bash">pip freeze &gt; requirements.txt
</code></pre>
<p>Then later, you (or someone else) can install them with:</p>
<pre><code class="lang-bash">pip install -r requirements.txt
</code></pre>
<p>This is useful for team projects or for moving your app to a server.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Activating your Django virtual environment might seem like a small thing, but it’s a big step toward becoming a confident and organized developer.</p>
<p>Once you get the hang of it, it becomes second nature – and your future self will thank you for learning it the right way from the start.</p>
<p>Would you love to connect with me? You can do so on <a target="_blank" href="https://X.com/_udemezue">X.com/_udemezue</a></p>
<h3 id="heading-helpful-resources">Helpful Resources</h3>
<ul>
<li><p><a target="_blank" href="https://docs.python.org/3/library/venv.html">Official Python Docs on <code>venv</code></a></p>
</li>
<li><p><a target="_blank" href="https://www.djangoproject.com/">Django Official Website</a></p>
</li>
<li><p><a target="_blank" href="https://realpython.com/python-virtual-environments-a-primer/">Python Virtual Environments Tutorial (Real Python)</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/63443862/activate-ps1-cannot-be-loaded-because-running-scripts-is-disabled">How to Fix “activate.ps1 cannot be loaded” in PowerShell</a></p>
</li>
</ul>
<h3 id="heading-further-learning">Further Learning</h3>
<p>If you're serious about Django, here are some free and paid resources I recommend:</p>
<ul>
<li><p><a target="_blank" href="https://djangoforbeginners.com/">Django for Beginners by William S. Vincent</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=F5mRW0jo-U4">FreeCodeCamp’s Django Crash Course on YouTube</a></p>
</li>
<li><p><a target="_blank" href="https://cs50.harvard.edu/web/2020/">CS50 Web Programming with Python and JavaScript</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Get Your First SaaS Customers ]]>
                </title>
                <description>
                    <![CDATA[ Starting a SaaS (Software as a Service) business is exciting. You’ve put in the long hours building something you believe people will love. But now comes the big question: How do you get your first customers? Getting those first few users can feel li... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-your-first-saas-customers/</link>
                <guid isPermaLink="false">681242328ca367c7e5d58873</guid>
                
                    <category>
                        <![CDATA[ SaaS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ marketing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Wed, 30 Apr 2025 15:30:58 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746027034713/42b1e6bd-3f5f-4e41-b3d0-ead8168661a6.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Starting a SaaS (Software as a Service) business is exciting. You’ve put in the long hours building something you believe people will love. But now comes the big question: <strong>How do you get your first customers?</strong></p>
<p>Getting those first few users can feel like climbing a mountain. It’s the hardest part, but also the most important. Without customers, your SaaS doesn’t grow.</p>
<p>Without feedback from real users, you can’t improve. And let’s be honest – seeing people pay for your product is a huge motivation boost.</p>
<p>I’ve seen this challenge many times, and I know the pressure is real. That’s why I’m breaking it all down in the simplest way possible. No confusing words, no vague advice – just a clear plan you can use.</p>
<p>Let’s jump right in.</p>
<h2 id="heading-why-getting-your-first-saas-customers-matters-so-much">Why Getting Your First SaaS Customers Matters So Much</h2>
<p>Before we talk strategy, let’s be super clear about why the first customers are gold:</p>
<ul>
<li><p><strong>They validate your idea.</strong> If strangers are willing to pay, you’re onto something real.</p>
</li>
<li><p><strong>They help you shape the product.</strong> Early users are honest about what works and what’s broken.</p>
</li>
<li><p><strong>They fuel your momentum.</strong> A few early wins can give you the confidence to keep pushing forward.</p>
</li>
<li><p><strong>They help you spread the word.</strong> Happy first customers are often your best marketers.</p>
</li>
</ul>
<p>Your first ten customers matter more than your next hundred. So it’s worth taking the time to get this right.</p>
<h2 id="heading-real-ways-to-get-your-first-saas-customers">Real Ways to Get Your First SaaS Customers</h2>
<h3 id="heading-1-start-with-people-you-know">1. Start With People You Know</h3>
<p>Don’t be shy to reach out to friends, family, former coworkers, and old clients. Tell them about your new SaaS and ask if they know anyone who might need it.</p>
<p>And remember: you’re not begging – you’re offering something valuable.</p>
<p><strong>Pro Tip:</strong> Focus on <em>the people they know,</em> not just whether they want to buy themselves.</p>
<h3 id="heading-2-join-communities-where-your-customers-hang-out">2. Join Communities Where Your Customers Hang Out</h3>
<p>Find Facebook groups, Reddit forums, Slack communities, or LinkedIn groups where your ideal users already spend time.</p>
<p>Be helpful. Answer questions. Join conversations. Build trust. Then, when it’s natural, mention your product.</p>
<p><strong>Real Example:</strong> If you built a tool for yoga instructors, find Facebook groups for yoga teachers.</p>
<h3 id="heading-3-launch-on-product-hunt">3. Launch on Product Hunt</h3>
<p>Product Hunt is full of early adopters looking for new tools.</p>
<p>If you do a good launch (with a nice-looking page, clear description, and a bit of buzz on the side), you could get your first few hundred signups in one day.</p>
<p><strong>Helpful read:</strong> <a target="_blank" href="https://www.producthunt.com/blog/how-to-launch-on-product-hunt">How to Launch on Product Hunt Successfully</a></p>
<h3 id="heading-4-offer-a-beta-version">4. Offer a “Beta” Version</h3>
<p>Invite early users to test your software before the official launch.<br>Make it feel special – they get early access, and their feedback will shape the product.</p>
<p><strong>Bonus Tip:</strong> Beta users are often more forgiving about bugs. They <em>expect</em> a few rough edges.</p>
<h3 id="heading-5-use-cold-outreach-but-do-it-right">5. Use Cold Outreach (But Do It Right)</h3>
<p>Sending emails to strangers sounds scary. But if you write short, respectful, personalized emails, it works.<br>Focus on how you can solve a real problem they have – not on how great your product is.</p>
<p><strong>Good Cold Email Example:</strong></p>
<blockquote>
<p>"Hi [Name],<br>I noticed you [specific detail]. I built a tool that might save you [X hours / $X per month].<br>Would you like me to send a quick demo?"</p>
</blockquote>
<p>Keep it about them, not you.</p>
<h3 id="heading-6-get-active-on-linkedin">6. Get Active on LinkedIn</h3>
<p>Post helpful tips, mini case studies, and personal stories. Show people you understand their struggles.<br>It builds trust. It shows you’re serious. And it keeps you top-of-mind when someone <em>does</em> need your product.</p>
<h3 id="heading-7-partner-with-other-small-businesses">7. Partner With Other Small Businesses</h3>
<p>Find companies that serve the same audience but aren’t direct competitors.</p>
<p>Maybe you made a booking app for barbershops. You could partner with a payment processor or marketing agency that also targets barbers.</p>
<p>Offer a referral deal or co-host a webinar together.</p>
<h3 id="heading-8-content-marketing-start-small">8. Content Marketing (Start Small)</h3>
<p>You don’t need a full blog with 50 articles right away. Start with 2–3 simple, super-useful blog posts that answer real questions your customers have.</p>
<p>Example:</p>
<p>If you built an invoicing tool, write posts like:</p>
<ul>
<li><p>“How to Send Your First Invoice as a Freelancer”</p>
</li>
<li><p>“5 Mistakes New Freelancers Make With Payments”</p>
</li>
</ul>
<p>Helpful Link: <a target="_blank" href="https://moz.com/beginners-guide-to-content-marketing">Beginner’s Guide to Content Marketing</a></p>
<h3 id="heading-9-run-a-tiny-paid-ad-test">9. Run a Tiny Paid Ad Test</h3>
<p>A small Facebook or Google ad campaign (even $5–10 a day) can give you quick feedback.</p>
<p>Target very specifically – not just "small business owners," but "independent yoga teachers in New York."</p>
<p>Watch which messages work, which don’t, and adjust fast.</p>
<h3 id="heading-10-create-simple-case-studies">10. Create Simple Case Studies</h3>
<p>Even if you only have <em>one</em> early customer, ask them if you can tell their story. How they used your product. What problem it solved. What results they saw.</p>
<p>Nothing builds trust faster than real success stories.</p>
<h3 id="heading-11-offer-a-founders-deal">11. Offer a Founder's Deal</h3>
<p>Offer lifetime discounts or special plans to your first customers. This rewards them for taking a chance on you early, and it creates urgency (“only 20 spots left!”).</p>
<p>Example: Lifetime access for $99 instead of $20/month.</p>
<h3 id="heading-12-make-it-ridiculously-easy-to-share">12. Make It Ridiculously Easy to Share</h3>
<p>Add a simple “Share with a friend” button in your app, emails, and thank-you pages. Happy users want to help – just make it easy for them.</p>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-should-i-offer-my-saas-for-free-at-first"><strong>Should I offer my SaaS for free at first?</strong></h3>
<p>I would recommend a free <em>trial</em> instead of free <em>forever.</em> Free users are often less serious. You want customers who see value and are willing to pay for it.</p>
<h3 id="heading-how-long-does-it-usually-take"><strong>How long does it usually take?</strong></h3>
<p>Honestly? It depends. Some people land their first customers in a week. Others need a few months. Stay patient and keep improving both your product and your outreach.</p>
<h3 id="heading-what-if-no-one-seems-interested"><strong>What if no one seems interested?</strong></h3>
<p>It happens. If you're hearing crickets, it might be time to talk directly to potential customers, ask more questions, and tweak your offer. Sometimes it’s just a positioning problem.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Getting your first SaaS customers isn’t about being perfect. It’s about getting real people to trust you enough to give your product a shot. Start small. Talk to people. Solve real problems.</p>
<p>And keep improving a little every day.</p>
<p>If you need a hand with SaaS marketing or growing your idea, I’m always happy to connect. You can find me on X at <a target="_blank" href="https://x.com/_udemezue">x.com/_udemezue</a>, or check out my portfolio: <a target="_blank" href="https://udemezue.pages.dev">Udemezue.pages.dev</a>.</p>
<h3 id="heading-further-resources">Further Resources</h3>
<p>If you want to dive deeper, check out:</p>
<ul>
<li><p><a target="_blank" href="https://momtestbook.com/">The Mom Test (book)</a> — How to talk to customers and get honest feedback.</p>
</li>
<li><p><a target="_blank" href="https://www.indiehackers.com/">Indie Hackers</a> — A community where founders share how they got their first users.</p>
</li>
<li><p><a target="_blank" href="https://www.demandcurve.com/">First 1000 Users Guide (from Demand Curve)</a> — Very detailed but still easy to follow.</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Get the User Model in Django – A Simple Guide With Examples ]]>
                </title>
                <description>
                    <![CDATA[ When I’m working with Django, one of the first things I often need to do is work with users – like getting the logged-in user, creating a new one, or extending the default user model to add more information. Now, Django has a built-in User model, but... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-user-model-in-django/</link>
                <guid isPermaLink="false">68123f859249b83d2215937d</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Wed, 30 Apr 2025 15:19:33 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746026362647/7b47e9e7-6baf-409a-8654-0ad1eb528e31.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When I’m working with Django, one of the first things I often need to do is work with users – like getting the logged-in user, creating a new one, or extending the default user model to add more information.</p>
<p>Now, Django has a built-in <code>User</code> model, but sometimes you might want a custom one. That's where things can get a little confusing if you're just starting.</p>
<p>The good news? Getting the user model in Django is very simple once you understand how Django is set up.</p>
<p>Today, I’ll walk you through exactly how to get the user model in Django, explain why it matters, show you real code you can use, and answer a few common questions people usually have around this topic.</p>
<p>Let's jump right into it.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-getting-the-user-model-correctly-matters">Why Getting the User Model Correctly Matters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-the-user-model-in-django">How to Get the User Model in Django</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-full-example-using-the-user-model">Full Example: Using the User Model</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-settingsauthusermodel">When to Use settings.AUTH_USER_MODEL</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-quick-summary">Quick Summary</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-mistakes-to-avoid">Common Mistakes to Avoid</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-faqs">FAQs</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-can-i-access-requestuser-it-directly">1. Can I access request.user it directly?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-what-happens-if-i-call-getusermodel-multiple-times">2. What happens if I call get_user_model() Multiple times?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-how-do-i-know-if-im-using-a-custom-user-model">3. How do I know if I’m using a custom user model?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-when-should-i-create-a-custom-user-model">4. When should I create a custom user model?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-further-resources">Further Resources</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-why-getting-the-user-model-correctly-matters">Why Getting the User Model Correctly Matters</h2>
<p>Before anything else, it’s important to know why this even matters.</p>
<p>Django projects depend heavily on user information – not just for logins, but for permissions, profiles, admin management, and much more.</p>
<p>If you get the user model the wrong way, you can easily run into problems later, especially if you customize your user model.</p>
<p>Django even warns you about this in its <a target="_blank" href="https://docs.djangoproject.com/en/stable/topics/auth/customizing/">official documentation</a>. If you don't use the right way to access the user model, your project could break when you change or extend it.</p>
<p>That’s why it’s super important to always get the user model the <em>recommended</em> way, which I’ll show you next.</p>
<h2 id="heading-how-to-get-the-user-model-in-django">How to Get the User Model in Django</h2>
<p>Alright, here’s the simplest way to get the user model in Django:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib.auth <span class="hljs-keyword">import</span> get_user_model

User = get_user_model()
</code></pre>
<p><strong>What’s happening here?</strong></p>
<ul>
<li><p><code>get_user_model()</code> is a built-in Django function.</p>
</li>
<li><p>It returns the correct User model – whether you're using the default one or a custom one you created.</p>
</li>
</ul>
<p>If you’re wondering why not just import <code>from django.contrib.auth.models import User</code>, the reason is this: if you ever swap out the default User model for a custom one, directly importing like that will break your code.</p>
<p>By using <code>get_user_model()</code>, you stay safe and future-proof your project.</p>
<h2 id="heading-full-example-using-the-user-model">Full Example: Using the User Model</h2>
<p>Let’s look at a full working example, not just a little snippet.</p>
<p>Imagine you want to create a new user inside a Django view:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib.auth <span class="hljs-keyword">import</span> get_user_model
<span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> HttpResponse

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_user_view</span>(<span class="hljs-params">request</span>):</span>
    User = get_user_model()
    user = User.objects.create_user(username=<span class="hljs-string">'newuser'</span>, password=<span class="hljs-string">'securepassword123'</span>)
    <span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">f"Created user: <span class="hljs-subst">{user.username}</span>"</span>)
</code></pre>
<p>In this example:</p>
<ul>
<li><p>First, I get the user model with <code>get_user_model()</code>.</p>
</li>
<li><p>Then, I use Django’s built-in <code>create_user</code> method to create a user safely.</p>
</li>
<li><p>Finally, I send back a simple HTTP response showing the created username.</p>
</li>
</ul>
<p>Notice how clean and flexible it is – no matter what user model you're using under the hood.</p>
<h2 id="heading-when-to-use-settingsauthusermodel">When to Use <code>settings.AUTH_USER_MODEL</code></h2>
<p>Another thing you’ll often see in Django projects is something like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.conf <span class="hljs-keyword">import</span> settings

settings.AUTH_USER_MODEL
</code></pre>
<p>This doesn’t <strong>get</strong> the user model. Instead, it gives you the <strong>string</strong> path to the user model, like <code>"auth.User"</code> (for default) or <code>"myapp.MyCustomUser"</code> if you customized it.</p>
<p>You usually use <code>settings.AUTH_USER_MODEL</code> inside your <strong>models.py</strong> when you want to link to the User model in a ForeignKey, OneToOneField, or ManyToManyField.</p>
<p>For example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.conf <span class="hljs-keyword">import</span> settings
<span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Profile</span>(<span class="hljs-params">models.Model</span>):</span>
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    bio = models.TextField()
</code></pre>
<p>Here, the <code>Profile</code> model is tied to the correct user model. Again, this keeps your project flexible and future-proof.</p>
<h2 id="heading-quick-summary">Quick Summary</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Situation</td><td>What to Use</td></tr>
</thead>
<tbody>
<tr>
<td>Getting the actual User model in Python code (views, forms, admin, and so on)</td><td><code>get_user_model()</code></td></tr>
<tr>
<td>Referring to the User model in database relationships (ForeignKey, OneToOneField, and so on)</td><td><code>settings.AUTH_USER_MODEL</code></td></tr>
</tbody>
</table>
</div><p>Remember this table – it saves a lot of headaches later!</p>
<h2 id="heading-common-mistakes-to-avoid">Common Mistakes to Avoid</h2>
<ul>
<li><p><strong>Directly importing</strong> <code>User</code>: Never just do <code>from django.contrib.auth.models import User</code> unless you are 100% sure you're sticking with the default model forever (not recommended).</p>
</li>
<li><p><strong>Hardcoding relationships</strong>: If you write something like <code>ForeignKey('auth.User')</code> instead of using <code>settings.AUTH_USER_MODEL</code>, it will break if you ever switch to a custom user model.</p>
</li>
<li><p><strong>Not creating custom user models early</strong>: If you think you might ever need a custom user model (like adding phone numbers, extra profile fields), set it up early. Switching later is painful once you have a database full of users.</p>
</li>
</ul>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-1-can-i-access-requestuser-directly">1. Can I access <code>request.user</code> directly?</h3>
<p>Yes! Inside views, <code>request.user</code> gives you the current logged-in user object. Behind the scenes, Django is using the correct user model, whether it’s custom or default.</p>
<h3 id="heading-2-what-happens-if-i-call-getusermodel-multiple-times">2. What happens if I call <code>get_user_model()</code> multiple times?</h3>
<p>No problem at all. Django caches it internally, so it’s efficient. Feel free to call it wherever you need it.</p>
<h3 id="heading-3-how-do-i-know-if-im-using-a-custom-user-model">3. How do I know if I’m using a custom user model?</h3>
<p>Check your Django settings file (<code>settings.py</code>) and look for <code>AUTH_USER_MODEL</code>. If it’s set (like <code>'myapp.MyCustomUser'</code>, you are using a custom model. If it’s not there, Django is using the default.</p>
<h3 id="heading-4-when-should-i-create-a-custom-user-model">4. When should I create a custom user model?</h3>
<p>If you even <em>think</em> you’ll need fields like phone number, date of birth, profile pictures, and so on, it’s better to set up a custom model early.</p>
<p>Here’s a great guide from Django’s official docs on <a target="_blank" href="https://docs.djangoproject.com/en/stable/topics/auth/customizing/">customizing user models</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Working with users in Django doesn’t have to be tricky. Once you know to use <code>get_user_model()</code> when you need the model and <code>settings.AUTH_USER_MODEL</code> for database relationships, your code stays clean, safe, and ready for whatever changes come your way.</p>
<p>Now that you know how to get the user model in Django, what’s one thing you'd love to customize about your users in your project? Shoot me a message on <a target="_blank" href="http://x.com/_udemezue/">X</a>.</p>
<p>If you want me to show you how to <strong>build</strong> a custom user model from scratch, let me know – it’s not hard once you know the steps.</p>
<h3 id="heading-further-resources">Further Resources</h3>
<ul>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/topics/auth/customizing/">Official Django documentation: Using a custom user model</a></p>
</li>
<li><p><a target="_blank" href="https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html">Simple explanation on AbstractBaseUser vs AbstractUser</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/29725217/django-custom-user-model-best-practice">StackOverflow: Best practices for Django user models</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Register Models in Django Admin ]]>
                </title>
                <description>
                    <![CDATA[ When you're building a website or an app with Django, one of the most exciting moments is when your database models finally come to life. But to manage your data easily – adding, editing, or deleting entries – you need Django’s Admin panel. Now, here... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-register-models-in-django-admin/</link>
                <guid isPermaLink="false">6810e5a2dc9845a2ab207f06</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Tue, 29 Apr 2025 14:43:46 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745937579596/e8aed227-b7c3-4bf6-a448-a66782aeea42.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you're building a website or an app with Django, one of the most exciting moments is when your database models finally come to life.</p>
<p>But to manage your data easily – adding, editing, or deleting entries – you need Django’s Admin panel.</p>
<p>Now, here’s the catch: just creating a model isn’t enough. If you want it to show up in the Admin panel, you have to <strong>register</strong> it.</p>
<p>And honestly, registering models in Django Admin is one of the simplest but most important steps. If you miss it, it feels like your model doesn’t even exist.</p>
<p>In this guide, I’ll walk you through exactly how to register your models in Django Admin, step-by-step, with easy-to-understand code examples.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-django-admin-matters">Why Django Admin Matters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-register-models-in-django-admin">How to Register Models in Django Admin</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-step-1-make-sure-you-have-a-model">Step 1: Make Sure You Have a Model</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-register-your-model-in-admin">Step 2: Register Your Model In Admin</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-optional-customize-how-your-model-looks-in-admin">Step 3: (Optional) Customize How Your Model Looks in Admin</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-faqs">FAQS</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-i-added-a-model-but-its-not-showing-up-in-admin-what-happened">1. I added a model, but it’s not showing up in Admin. What happened?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-do-i-have-to-register-every-model-separately">2. Do I have to register every model separately?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-how-do-i-unregister-a-model">3. How do I unregister a model?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-helpful-links-and-resources">Helpful Links and Resources</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></p>
</li>
</ul>
<h2 id="heading-why-django-admin-matters">Why Django Admin Matters</h2>
<p>Django Admin is like your personal dashboard for the backend of your website. Once you register your models, you can manage your app's content without touching any code.</p>
<p>Imagine being able to add new blog posts, approve users, update product listings – all with a few clicks. That’s the magic of Django Admin.</p>
<p>Without properly registering your models, you’re stuck managing everything manually, which can get messy real quick.</p>
<p>Plus, Django Admin saves developers hours of time. It’s one of the reasons Django is such a powerful framework.</p>
<h2 id="heading-how-to-register-models-in-django-admin">How to Register Models in Django Admin</h2>
<h3 id="heading-step-1-make-sure-you-have-a-model">Step 1: Make Sure You Have a Model</h3>
<p>Before you can register anything, you need a model. Here’s a super basic example of a model inside a Django app called <code>blog</code>.</p>
<p>Inside <code>blog/models.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span>(<span class="hljs-params">models.Model</span>):</span>
    title = models.CharField(max_length=<span class="hljs-number">200</span>)
    body = models.TextField()
    date_created = models.DateTimeField(auto_now_add=<span class="hljs-literal">True</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.title
</code></pre>
<p>In this model:</p>
<ul>
<li><p><code>title</code> is a short text field.</p>
</li>
<li><p><code>body</code> is for longer content.</p>
</li>
<li><p><code>date_created</code> automatically stores the time when the post is created.</p>
</li>
</ul>
<p>And that <code>__str__</code> method? That’s just telling Django how to show each Post in the Admin – it’ll display the post’s title instead of something like <code>Post object (1)</code>.</p>
<p><strong>Quick tip</strong>: Always add a <code>__str__</code> method to your models. It makes your Admin interface much cleaner.</p>
<h3 id="heading-step-2-register-your-model-in-admin">Step 2: Register Your Model in Admin</h3>
<p>Alright, your model is ready. Time to register it!</p>
<p>Open <code>blog/admin.py</code>. When you create a new Django app, this file is empty by default.</p>
<p>Here’s how to register the <code>Post</code> model:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Post

admin.site.register(Post)
</code></pre>
<p><strong>What’s happening here?</strong></p>
<ul>
<li><p>First, you import Django’s admin module.</p>
</li>
<li><p>Then, you import your model (<code>Post</code>).</p>
</li>
<li><p>Finally, you use <code>admin.site.register()</code> to tell Django, "Hey, I want this model to show up in the Admin panel."</p>
</li>
</ul>
<p>Save the file. Now if you go to your Admin site (usually at <code>http://127.0.0.1:8000/admin</code>), you’ll see <strong>Posts</strong> listed there.</p>
<h3 id="heading-step-3-optional-customize-how-your-model-looks-in-admin">Step 3: (Optional) Customize How Your Model Looks in Admin</h3>
<p>By default, Django Admin shows your models in a very basic table. But you can make it so much better with a little customization.</p>
<p>Here’s how you can make Posts show the title and creation date at a glance.</p>
<p>Still inside <code>blog/admin.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Post

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostAdmin</span>(<span class="hljs-params">admin.ModelAdmin</span>):</span>
    list_display = (<span class="hljs-string">'title'</span>, <span class="hljs-string">'date_created'</span>)

admin.site.register(Post, PostAdmin)
</code></pre>
<p>Now:</p>
<ul>
<li><p><code>list_display</code> tells Django which fields you want to show in the list view.</p>
</li>
<li><p>You create a <code>PostAdmin</code> class that describes how the <code>Post</code> model should behave in Admin.</p>
</li>
<li><p>When you register, you pass both the model (<code>Post</code>) and the admin class (<code>PostAdmin</code>).</p>
</li>
</ul>
<p><strong>Quick tip</strong>: Customizing your Admin improves your workflow <em>a lot</em> – especially when you’re managing many entries.</p>
<h2 id="heading-faqs">FAQS</h2>
<h3 id="heading-1-i-added-a-model-but-its-not-showing-up-in-admin-what-happened">1. I added a model, but it’s not showing up in Admin. What happened?</h3>
<p>Make sure you:</p>
<ul>
<li><p>Registered the model inside <code>admin.py</code>.</p>
</li>
<li><p>Ran migrations (<code>python manage.py makemigrations</code> and <code>python manage.py migrate</code>) if you changed anything in the model.</p>
</li>
</ul>
<p>Also, check if the app is listed in your <code>INSTALLED_APPS</code> inside <code>settings.py</code>.</p>
<h3 id="heading-2-do-i-have-to-register-every-model-separately">2. Do I have to register every model separately?</h3>
<p>Yes. Each model you want to manage in Admin needs to be registered. But you can register multiple models together too:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Post, Comment, Category

admin.site.register([Post, Comment, Category])
</code></pre>
<h3 id="heading-3-how-do-i-unregister-a-model">3. How do I unregister a model?</h3>
<p>You can use:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Post

admin.site.unregister(Post)
</code></pre>
<p>But honestly, most of the time, you just stop registering it if you don't want it there.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Registering models in Django Admin might seem like a tiny step, but it has a huge impact on how you work with your data.</p>
<p>It turns your database into a friendly dashboard that anyone can use – even non-technical people.</p>
<p>Once you get comfortable with registering and customising your models, you’ll move faster and feel a lot more in control of your app.</p>
<p>Now I’m curious — <strong>which model are you most excited to register in your Django Admin?</strong> Let’s chat on <a target="_blank" href="http://x.com/_udemezue">X</a>.</p>
<h3 id="heading-helpful-links-and-resources">Helpful Links and Resources</h3>
<ul>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/">Django Official Documentation – Admin Site</a></p>
</li>
<li><p><a target="_blank" href="https://realpython.com/get-started-with-django-1/">Understanding Django Models (Real Python)</a></p>
</li>
<li><p><a target="_blank" href="https://tutorial.djangogirls.org/en/django_admin/">Django Girls Tutorial – Introduction to Django Admin</a></p>
</li>
</ul>
<p>These are great places to go if you want to dive even deeper into Django Admin customization.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Enable CORS in Django ]]>
                </title>
                <description>
                    <![CDATA[ If you've ever tried to connect your frontend app to your Django backend and suddenly hit an error that looks something like "has been blocked by CORS policy", you're not alone. It’s frustrating, especially when your code seems fine. So what’s going ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-enable-cors-in-django/</link>
                <guid isPermaLink="false">680fa40e9096ceb5eeedd90e</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CORS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Mon, 28 Apr 2025 15:51:42 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745855234567/f09d3338-c824-4cd8-a26f-93bb485f925a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've ever tried to connect your frontend app to your Django backend and suddenly hit an error that looks something like <strong>"has been blocked by CORS policy"</strong>, you're not alone. It’s frustrating, especially when your code seems fine.</p>
<p>So what’s going on?</p>
<p>This is where <strong>CORS</strong> (Cross-Origin Resource Sharing) comes in. It's a browser security feature that blocks web pages from making requests to a different domain than the one that served the web page.</p>
<p>It’s there to protect users, but if it’s not configured correctly, it can stop your app from working the way you want.</p>
<p>Let’s fix that.</p>
<p>In this article, I’ll walk you through everything you need to know to enable CORS in Django without headaches.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-cors-and-why-should-you-care">What is CORS and Why Should You Care?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-enable-cors-in-django">How to Enable CORS in Django</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-install-django-cors-headers">1. Install django-cors-headers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-add-it-to-installedapps">2. Add It to INSTALLED_APPS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-add-middleware">3. Add Middleware</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-set-the-allowed-origins">4. Set the Allowed Origins</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-optional-settings-you-might-need">Optional Settings You Might Need</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-allow-all-origins-not-recommended-for-production">Allow All Origins (Not Recommended for Production)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-allow-credentials-cookies-auth">Allow Credentials (Cookies, Auth)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-allow-specific-headers">Allow Specific Headers</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-example-full-settings-file-snippet">Example: Full Settings File Snippet</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-errors-and-how-to-fix-them">Common Errors (And How to Fix Them)</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-cors-not-working-at-all">1. CORS Not Working At All?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-preflight-request-fails-options-method">2. Preflight Request Fails (OPTIONS method)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-using-django-rest-framework">3. Using Django Rest Framework?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-faqs">FAQs</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-can-i-allow-multiple-frontend-urls">Can I allow multiple frontend URLs?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-does-cors-affect-local-development-only">Does CORS affect local development only?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-is-it-secure-to-allow-all-origins">Is it secure to allow all origins?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-do-i-need-to-change-anything-on-the-frontend">Do I need to change anything on the frontend?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-further-resources">Further Resources</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></p>
</li>
</ul>
<h2 id="heading-what-is-cors-and-why-should-you-care">What is CORS and Why Should You Care?</h2>
<p>Before you start changing settings, it’s important to understand what CORS is.</p>
<p>Imagine you have a frontend built with React running on <code>http://localhost:3000</code> and a Django API running on <code>http://localhost:8000</code>.</p>
<p>When the frontend tries to talk to the backend, your browser sees that they’re not the same origin (they have different ports), and it blocks the request.</p>
<p>That’s CORS doing its job. It assumes you might be trying to do something unsafe – like stealing cookies or user data – so it steps in.</p>
<p>Now, as a developer, if you trust the frontend and you own both ends, then it’s safe to let those requests through. You just need to tell Django it’s okay.</p>
<h2 id="heading-how-to-enable-cors-in-django">How to Enable CORS in Django</h2>
<p>You’re going to need a third-party package called <code>django-cors-headers</code>. It’s widely used and actively maintained. Here’s how to set it up:</p>
<h3 id="heading-1-install-django-cors-headers">1. Install <code>django-cors-headers</code></h3>
<p>Run this in your terminal:</p>
<pre><code class="lang-bash">pip install django-cors-headers
</code></pre>
<p>This adds the package to your environment so Django can use it.</p>
<h3 id="heading-2-add-it-to-installedapps">2. Add It to <code>INSTALLED_APPS</code></h3>
<p>Open your <code>settings.py</code> file and find the <code>INSTALLED_APPS</code> section. Add this line:</p>
<pre><code class="lang-python">INSTALLED_APPS = [
    ...
    <span class="hljs-string">'corsheaders'</span>,
]
</code></pre>
<p>This registers the app with Django.</p>
<h3 id="heading-3-add-middleware">3. Add Middleware</h3>
<p>Now scroll down to the <code>MIDDLEWARE</code> section in <code>settings.py</code>. Add this <strong>at the top of the list</strong>:</p>
<pre><code class="lang-python">MIDDLEWARE = [
    <span class="hljs-string">'corsheaders.middleware.CorsMiddleware'</span>,
    <span class="hljs-string">'django.middleware.common.CommonMiddleware'</span>,
    ...
]
</code></pre>
<p><strong>Why at the top?</strong> Because middleware in Django runs in order. If you don’t place it at the top, the CORS headers might not be added correctly, and your browser will still block your requests.</p>
<h3 id="heading-4-set-the-allowed-origins">4. Set the Allowed Origins</h3>
<p>This is where you tell Django which origins are allowed to talk to your backend.</p>
<p>Still in <code>settings.py</code>, add:</p>
<pre><code class="lang-python">CORS_ALLOWED_ORIGINS = [
    <span class="hljs-string">"http://localhost:3000"</span>,
]
</code></pre>
<p>Replace <code>localhost:3000</code> with whatever domain or port your frontend is using. If you're using HTTPS or deploying, make sure to include the correct URL, like <code>https://yourfrontend.com</code>.</p>
<p>And that’s it! You’re now allowing your frontend to access your backend.</p>
<h2 id="heading-optional-settings-you-might-need">Optional Settings You Might Need</h2>
<p>Depending on your project, you might run into other issues. Here are some extra settings you might find useful:</p>
<h3 id="heading-allow-all-origins-not-recommended-for-production">Allow All Origins (Not Recommended for Production)</h3>
<p>If you’re just testing and want to allow everything (be careful with this), you can use:</p>
<pre><code class="lang-python">CORS_ALLOW_ALL_ORIGINS = <span class="hljs-literal">True</span>
</code></pre>
<p>Again, don’t use this in production unless you understand the risks. It can open up your API to abuse.</p>
<h3 id="heading-allow-credentials-cookies-auth">Allow Credentials (Cookies, Auth)</h3>
<p>If your frontend is sending authentication credentials like cookies or tokens, you also need this:</p>
<pre><code class="lang-python">CORS_ALLOW_CREDENTIALS = <span class="hljs-literal">True</span>
</code></pre>
<p>And make sure you <strong>don’t</strong> use <code>CORS_ALLOW_ALL_ORIGINS</code> with this setting – it won’t work due to security rules. Stick to <code>CORS_ALLOWED_ORIGINS</code>.</p>
<h3 id="heading-allow-specific-headers">Allow Specific Headers</h3>
<p>By default, common headers are allowed, but if you’re sending custom ones (like <code>X-Auth-Token</code>), you can add:</p>
<pre><code class="lang-python">CORS_ALLOW_HEADERS = [
    <span class="hljs-string">"content-type"</span>,
    <span class="hljs-string">"authorization"</span>,
    <span class="hljs-string">"x-auth-token"</span>,
    ...
]
</code></pre>
<h2 id="heading-example-full-settings-file-snippet">Example: Full Settings File Snippet</h2>
<p>Here’s a mini version of what your <code>settings.py</code> might look like after setup:</p>
<pre><code class="lang-python">INSTALLED_APPS = [
    ...
    <span class="hljs-string">'corsheaders'</span>,
    ...
]

MIDDLEWARE = [
    <span class="hljs-string">'corsheaders.middleware.CorsMiddleware'</span>,
    <span class="hljs-string">'django.middleware.common.CommonMiddleware'</span>,
    ...
]

CORS_ALLOWED_ORIGINS = [
    <span class="hljs-string">"http://localhost:3000"</span>,
]

CORS_ALLOW_CREDENTIALS = <span class="hljs-literal">True</span>
</code></pre>
<p>You can tweak this based on your needs, but that’s the basic structure.</p>
<h2 id="heading-common-errors-and-how-to-fix-them">Common Errors (And How to Fix Them)</h2>
<h3 id="heading-1-cors-not-working-at-all">1. CORS Not Working At All?</h3>
<p>Double check:</p>
<ul>
<li><p>You added <code>corsheaders.middleware.CorsMiddleware</code> it <strong>at the top</strong> of the middleware list.</p>
</li>
<li><p>Your frontend origin matches exactly, including port and protocol.</p>
</li>
<li><p>You restarted your server after changing the settings.</p>
</li>
</ul>
<h3 id="heading-2-preflight-request-fails-options-method">2. Preflight Request Fails (OPTIONS method)</h3>
<p>Sometimes your browser sends an <code>OPTIONS</code> request first to check if the server will allow the real request. Make sure your views or Django setup allow that method, or Django will return a 405 error.</p>
<p>You don’t usually need to do anything here unless you’re using a custom middleware or view decorator that blocks it.</p>
<h3 id="heading-3-using-django-rest-framework">3. Using Django Rest Framework?</h3>
<p>No problem – <code>django-cors-headers</code> works out of the box. Just make sure it’s installed and the middleware is set up correctly.</p>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-can-i-allow-multiple-frontend-urls"><strong>Can I allow multiple frontend URLs?</strong></h3>
<p>Yes! Just add more items to the list:</p>
<pre><code class="lang-python">CORS_ALLOWED_ORIGINS = [
    <span class="hljs-string">"http://localhost:3000"</span>,
    <span class="hljs-string">"https://myfrontend.com"</span>,
]
</code></pre>
<h3 id="heading-does-cors-affect-local-development-only"><strong>Does CORS affect local development only?</strong></h3>
<p>No, it applies in production too. Any time your frontend and backend are on different origins (different domain or port), you need to handle CORS.</p>
<h3 id="heading-is-it-secure-to-allow-all-origins"><strong>Is it secure to allow all origins?</strong></h3>
<p>No. Only do that temporarily during development. Always restrict access in production to just the domains you trust.</p>
<h3 id="heading-do-i-need-to-change-anything-on-the-frontend"><strong>Do I need to change anything on the frontend?</strong></h3>
<p>Sometimes. If you're sending credentials (like cookies), you’ll need to set <code>credentials: "include"</code> in your fetch or Axios requests.</p>
<p>Example with fetch:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">"http://localhost:8000/api/data"</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">"GET"</span>,
  <span class="hljs-attr">credentials</span>: <span class="hljs-string">"include"</span>,
})
</code></pre>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>CORS can feel like a wall you keep running into when building web apps. But once you get the hang of how it works – and how to set it up in Django – it becomes a small thing you configure and move on.</p>
<p>Just remember:</p>
<ul>
<li><p>Be specific in production</p>
</li>
<li><p>Always restart the server after changes</p>
</li>
<li><p>Don’t ignore warnings in your browser console – they’re your friends</p>
</li>
</ul>
<p>Now you know how to enable CORS in Django the right way.</p>
<h3 id="heading-further-resources">Further Resources</h3>
<ul>
<li><p><a target="_blank" href="https://github.com/adamchainz/django-cors-headers">django-cors-headers GitHub page</a> – for full documentation.</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">MDN CORS Overview</a> – to understand how CORS works under the hood.</p>
</li>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/topics/http/middleware/">Official Django Middleware Docs</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create Models in Your Django Project ]]>
                </title>
                <description>
                    <![CDATA[ If you're building something with Django, there's one thing you can't skip: creating models. Models are the heart of any Django app. They define how your data is structured, how it's stored in the database, and how Django can interact with it. Now, i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-models-in-your-django-project/</link>
                <guid isPermaLink="false">680be6e3dfe4e9c64b6b0997</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Fri, 25 Apr 2025 19:47:47 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745610452559/e009644b-bfef-4e43-9f1b-5f2e4deebdfa.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're building something with Django, there's one thing you can't skip: creating models. Models are the heart of any Django app. They define how your data is structured, how it's stored in the database, and how Django can interact with it.</p>
<p>Now, if you're new to Django or still wrapping your head around the basics, don’t worry. I’ve been there too. Models might sound a bit intimidating at first, but they’re pretty straightforward once you see how they work.</p>
<p>I’ll walk you through it all – step by step – so by the end of this post, you’ll not only know how to create models, but also how to use them in real projects.</p>
<p>Let’s get into it.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-a-model-in-django">What is a Model in Django?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-models-in-django">How to Create Models in Django</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-step-1-start-a-django-project-if-you-havent-already">Step 1: Start a Django Project (if you haven’t already)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-define-your-model">Step 2: Define Your Model</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-register-the-app-and-create-the-database">Step 3: Register the App and Create the Database</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-4-create-and-use-objects">Step 4: Create and Use Objects</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-extra-model-features-that-youll-use">Extra Model Features That You’ll Use</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-default-values">1. Default Values</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-auto-timestamps">2. Auto Timestamps</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-model-meta-options">3. Model Meta Options</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-using-models-in-django-admin">Using Models in Django Admin</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-faqs">FAQs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></p>
</li>
</ol>
<h2 id="heading-what-is-a-model-in-django">What is a Model in Django?</h2>
<p>A model in Django is just a Python class that tells Django how you want your data to look. Django takes care of the hard part (talking to the database), so you can focus on describing your data in simple Python code.</p>
<p>Here’s a quick example of a basic model:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
    title = models.CharField(max_length=<span class="hljs-number">100</span>)
    author = models.CharField(max_length=<span class="hljs-number">50</span>)
    published_date = models.DateField()
    price = models.DecimalField(max_digits=<span class="hljs-number">5</span>, decimal_places=<span class="hljs-number">2</span>)
</code></pre>
<p>Let me break it down:</p>
<ul>
<li><p><code>title</code> and <code>author</code> are just short pieces of text, so I’m using <code>CharField</code>.</p>
</li>
<li><p><code>published_date</code> is a date – easy enough, that’s what <code>DateField</code> is for.</p>
</li>
<li><p><code>price</code> is a number with decimals, so <code>DecimalField</code> does the job.</p>
</li>
</ul>
<p>Each line describes one piece of data I want to store for every book. Simple, right?</p>
<h2 id="heading-how-to-create-models-in-django">How to Create Models in Django</h2>
<h3 id="heading-step-1-start-a-django-project-if-you-havent-already">Step 1: Start a Django Project (if you haven’t already)</h3>
<p>If you’re brand new, first you need a Django project:</p>
<pre><code class="lang-bash">django-admin startproject mysite
<span class="hljs-built_in">cd</span> mysite
python manage.py startapp books
</code></pre>
<p>Now you’ve got a Django app called <code>books</code> where you can put your models.</p>
<h3 id="heading-step-2-define-your-model">Step 2: Define Your Model</h3>
<p>Inside your app folder (<code>books</code>), open <code>models.py</code>. That’s where you’ll define your model.</p>
<p>Here’s a slightly more real-world example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span>(<span class="hljs-params">models.Model</span>):</span>
    name = models.CharField(max_length=<span class="hljs-number">100</span>)
    birthdate = models.DateField()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.name


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
    title = models.CharField(max_length=<span class="hljs-number">200</span>)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    summary = models.TextField()
    isbn = models.CharField(max_length=<span class="hljs-number">13</span>, unique=<span class="hljs-literal">True</span>)
    published = models.DateField()
    price = models.DecimalField(max_digits=<span class="hljs-number">6</span>, decimal_places=<span class="hljs-number">2</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.title
</code></pre>
<p>What’s happening here:</p>
<ul>
<li><p>I’ve created two models: <code>Author</code> and <code>Book</code>.</p>
</li>
<li><p><code>Book</code> has a relationship with <code>Author</code> using <code>ForeignKey</code>. That means one author can have many books.</p>
</li>
<li><p>I’m using <code>__str__()</code> to return a nice name when I look at objects in the Django admin.</p>
</li>
</ul>
<h3 id="heading-step-3-register-the-app-and-create-the-database">Step 3: Register the App and Create the Database</h3>
<p>Before Django can use your models, make sure your app is added to the project settings.</p>
<p>Open <code>mysite/settings.py</code> and find the <code>INSTALLED_APPS</code> list. Add <code>'books',</code> to it:</p>
<pre><code class="lang-python">INSTALLED_APPS = [
    <span class="hljs-comment"># other apps</span>
    <span class="hljs-string">'books'</span>,
]
</code></pre>
<p>Now, run migrations to create the database tables for your models:</p>
<pre><code class="lang-bash">python manage.py makemigrations
python manage.py migrate
</code></pre>
<p>This is how Django turns your Python code into actual database tables. The first command makes a migration file (basically, instructions for the database), and the second applies it.</p>
<h3 id="heading-step-4-create-and-use-objects">Step 4: Create and Use Objects</h3>
<p>Now you can use these models in your code. Open the Django shell:</p>
<pre><code class="lang-bash">python manage.py shell
</code></pre>
<p>Then try this out:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> books.models <span class="hljs-keyword">import</span> Author, Book
<span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> date

<span class="hljs-comment"># Create an author</span>
jane = Author.objects.create(name=<span class="hljs-string">"Jane Austen"</span>, birthdate=date(<span class="hljs-number">1775</span>, <span class="hljs-number">12</span>, <span class="hljs-number">16</span>))

<span class="hljs-comment"># Create a book</span>
book = Book.objects.create(
    title=<span class="hljs-string">"Pride and Prejudice"</span>,
    author=jane,
    summary=<span class="hljs-string">"A novel about manners and marriage in early 19th-century England."</span>,
    isbn=<span class="hljs-string">"1234567890123"</span>,
    published=date(<span class="hljs-number">1813</span>, <span class="hljs-number">1</span>, <span class="hljs-number">28</span>),
    price=<span class="hljs-number">9.99</span>
)

print(book)
</code></pre>
<p>Django will save these to your database automatically.</p>
<h2 id="heading-extra-model-features-that-youll-use">Extra Model Features That You’ll Use</h2>
<h3 id="heading-1-default-values">1. Default Values</h3>
<p>You can give a field a default value:</p>
<pre><code class="lang-python">is_published = models.BooleanField(default=<span class="hljs-literal">False</span>)
</code></pre>
<h3 id="heading-2-auto-timestamps">2. Auto Timestamps</h3>
<p>These are super useful when tracking created or updated times:</p>
<pre><code class="lang-python">created_at = models.DateTimeField(auto_now_add=<span class="hljs-literal">True</span>)
updated_at = models.DateTimeField(auto_now=<span class="hljs-literal">True</span>)
</code></pre>
<h3 id="heading-3-model-meta-options">3. Model Meta Options</h3>
<p>You can add class Meta to customize things like the default ordering:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
    <span class="hljs-comment"># fields...</span>

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        ordering = [<span class="hljs-string">'published'</span>]
</code></pre>
<h2 id="heading-using-models-in-django-admin">Using Models in Django Admin</h2>
<p>Django’s built-in admin panel is one of the best parts of the framework. But your models won’t show up there unless you register them.</p>
<p>In <code>books/admin.py</code>, add:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Author, Book

admin.site.register(Author)
admin.site.register(Book)
</code></pre>
<p>Now run:</p>
<pre><code class="lang-bash">python manage.py createsuperuser
</code></pre>
<p>Then go to <a target="_blank" href="http://127.0.0.1:8000/admin">http://127.0.0.1:8000/admin</a>, log in, and boom – your models are there, with a full interface.</p>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-can-i-change-a-model-after-ive-made-it"><strong>Can I change a model after I’ve made it?</strong></h3>
<p>Yes, but you’ll need to make a new migration:</p>
<pre><code class="lang-bash">python manage.py makemigrations
python manage.py migrate
</code></pre>
<h3 id="heading-what-databases-work-with-django"><strong>What databases work with Django?</strong></h3>
<p>Django works with PostgreSQL, MySQL, SQLite (default), and more. Most people start with SQLite when learning because it's easy and works out of the box.</p>
<h3 id="heading-whats-the-difference-between-charfield-and-textfield"><strong>What’s the difference between CharField and TextField?</strong></h3>
<p>Use <code>CharField</code> for short text with a max length (like a name or title). Use <code>TextField</code> for longer text (like a blog post or summary).</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Once you understand models, the rest of Django starts to click into place. Everything – forms, views, templates – eventually connects back to the model. It's how your app stores and works with real data.</p>
<p>The best way to learn is by building something. Start small, maybe a book catalog, a task manager, or a personal blog. Add models one at a time and play with them in the admin.</p>
<h3 id="heading-further-resources">Further Resources</h3>
<ul>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/topics/db/models/">Official Django Docs – Models</a></p>
</li>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/models/fields/">Django Model Field Reference</a></p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django">Simple Django Tutorial – Mozilla Developer Network</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Change Your Django Secret Key (Without Breaking Your App) ]]>
                </title>
                <description>
                    <![CDATA[ If you're working on a Django project, you've probably come across the SECRET_KEY in your settings file. It might seem like just another line of code, but it's one of the most important pieces of your project. SECRET_KEY keeps your app secure by sign... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-change-your-django-secret-key-without-breaking-your-app/</link>
                <guid isPermaLink="false">680b9ed80564f7c150cbf95b</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Fri, 25 Apr 2025 14:40:23 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745592003292/023f4ddd-61d7-4e06-b616-31de7924f6a9.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're working on a Django project, you've probably come across the <code>SECRET_KEY</code> in your settings file. It might seem like just another line of code, but it's one of the most important pieces of your project.</p>
<p><code>SECRET_KEY</code> keeps your app secure by signing cookies, passwords, and other sensitive data. And if it ever gets exposed or leaked – yeah, that’s a problem.</p>
<p>Changing your Django <code>SECRET_KEY</code> is something you should do carefully. Maybe your key was committed to GitHub (we’ve all been there), or you just want to refresh it for better security.</p>
<p>Whatever the reason, I’ll walk you through how to do it safely without breaking anything. I’ll explain everything in plain English so you’re not left wondering what just happened.</p>
<p>Let’s get into it.</p>
<h2 id="heading-what-is-the-django-secretkey">What Is The Django <code>SECRET_KEY</code>?</h2>
<p>The <code>SECRET_KEY</code> is a long string of random characters stored in your <code>settings.py</code> file. It’s used internally by Django to:</p>
<ul>
<li><p>Securely sign session cookies</p>
</li>
<li><p>Generate password reset tokens</p>
</li>
<li><p>Protect data using cryptographic signing</p>
</li>
</ul>
<p>Here’s what it looks like in your Django project:</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings.py</span>
SECRET_KEY = <span class="hljs-string">'django-insecure-12345supersecretrandomstring'</span>
</code></pre>
<p>If someone gets access to your <code>SECRET_KEY</code>, they could potentially:</p>
<ul>
<li><p>Forge session cookies and impersonate users</p>
</li>
<li><p>Reset passwords or tamper with signed data</p>
</li>
<li><p>Compromise the entire app</p>
</li>
</ul>
<p>So yeah – it’s kind of a big deal.</p>
<h2 id="heading-when-should-you-change-your-django-secret-key">When Should You Change Your Django Secret Key?</h2>
<p>You should change your <code>SECRET_KEY</code> if:</p>
<ul>
<li><p>You accidentally shared it in public code (like GitHub)</p>
</li>
<li><p>It was hardcoded in a file, and you want to switch to environment variables</p>
</li>
<li><p>You’re rotating keys as part of a security policy</p>
</li>
<li><p>You suspect it’s been compromised</p>
</li>
</ul>
<p>Still not sure if it’s necessary? If the key has ever been shared or stored where someone else could access it, just change it.</p>
<h2 id="heading-how-to-change-your-django-secretkey-safely">How to Change Your Django <code>SECRET_KEY</code> Safely</h2>
<h3 id="heading-1-generate-a-new-secret-key">1. <strong>Generate a New Secret Key</strong></h3>
<p>The key needs to be long, random, and secure. Django doesn’t provide a command for this out of the box, but you can generate one using Python.</p>
<p>Here’s a simple script:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.core.management.utils <span class="hljs-keyword">import</span> get_random_secret_key

print(get_random_secret_key())
</code></pre>
<p>To run this:</p>
<ol>
<li><p>Open your terminal</p>
</li>
<li><p>Run the Django shell with <code>python manage.py shell</code></p>
</li>
<li><p>Paste in the script</p>
</li>
</ol>
<p>It’ll return something like:</p>
<pre><code class="lang-python">x3%<span class="hljs-number">6</span>kn$mlg58+<span class="hljs-keyword">as</span>!rcvnmvd8%(<span class="hljs-number">2</span>p!p<span class="hljs-comment">#&amp;yk@r)+tdlj*w9kx!5gx</span>
</code></pre>
<p>Copy this. You’ll need it in a second.</p>
<h3 id="heading-2-store-the-key-securely-dont-hardcode-it">2. <strong>Store the Key Securely (Don’t Hardcode It)</strong></h3>
<p>Instead of pasting it into <code>settings.py</code>, it’s better to use an environment variable. That way, you don’t risk exposing it if you ever share your code.</p>
<p>Here’s how:</p>
<ol>
<li>Open your <code>.env</code> file (create one if it doesn’t exist):</li>
</ol>
<pre><code class="lang-python"><span class="hljs-comment"># .env</span>
SECRET_KEY=<span class="hljs-string">'x3%6kn$mlg58+as!rcvnmvd8%(2p!p#&amp;yk@r)+tdlj*w9kx!5gx'</span>
</code></pre>
<ol start="2">
<li>Install <code>python-decouple</code> if you haven’t already:</li>
</ol>
<pre><code class="lang-bash">pip install python-decouple
</code></pre>
<ol start="3">
<li>Update your <code>settings.py</code>:</li>
</ol>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> decouple <span class="hljs-keyword">import</span> config

SECRET_KEY = config(<span class="hljs-string">'SECRET_KEY'</span>)
</code></pre>
<p>Now your key is stored outside your code. Much safer.</p>
<h3 id="heading-3-commit-carefully">3. <strong>Commit Carefully</strong></h3>
<p>Make sure:</p>
<ul>
<li><p>Your <code>.env</code> file is added to <code>.gitignore</code></p>
</li>
<li><p>You never push it to your repository</p>
</li>
</ul>
<p>Here’s how <code>.gitignore</code> should look:</p>
<pre><code class="lang-python"><span class="hljs-comment"># .gitignore</span>
.env
</code></pre>
<p>You’d be surprised how often <code>.env</code> files get pushed by accident. Always double-check before you commit.</p>
<h3 id="heading-4-restart-your-app">4. <strong>Restart Your App</strong></h3>
<p>After changing the key, restart your server. If you’re using a platform like Heroku or Docker, make sure you update the <code>SECRET_KEY</code> in your environment variables dashboard.</p>
<p>For Heroku:</p>
<pre><code class="lang-bash">heroku config:<span class="hljs-built_in">set</span> SECRET_KEY=<span class="hljs-string">'your-new-key'</span>
</code></pre>
<p>For Docker:</p>
<pre><code class="lang-yaml"><span class="hljs-comment"># docker-compose.yml</span>
<span class="hljs-attr">environment:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">SECRET_KEY=your-new-key</span>
</code></pre>
<h3 id="heading-5-re-log-in-and-ask-users-to-do-the-same">5. <strong>Re-Log In (and Ask Users To Do the Same)</strong></h3>
<p>Changing the secret key invalidates all old sessions. So, everyone (including you) will be logged out. This is expected behaviour. If you're running a public site, it’s a good idea to notify users in advance.</p>
<h2 id="heading-what-happens-if-you-dont-change-it">What Happens If You Don't Change It?</h2>
<p>If your key is compromised, attackers can:</p>
<ul>
<li><p>Forge data</p>
</li>
<li><p>Hijack accounts</p>
</li>
<li><p>Break authentication systems</p>
</li>
</ul>
<p>It’s not just about best practices. It’s about real-world security.</p>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-will-this-break-my-app">Will this break my app?</h3>
<p>No, as long as you restart your app and store the key properly, everything will work fine. Just remember: all users will be logged out.</p>
<h3 id="heading-can-i-use-the-same-key-for-multiple-projects">Can I use the same key for multiple projects?</h3>
<p>Nope. Each project should have its unique secret key.</p>
<h3 id="heading-can-i-rotate-the-key-regularly">Can I rotate the key regularly?</h3>
<p>Yes, just be mindful that changing it too often will log users out repeatedly.</p>
<h3 id="heading-i-forgot-to-add-env-to-gitignore-what-now">I forgot to add <code>.env</code> to <code>.gitignore</code>. What now?</h3>
<p>Regenerate the key, update your project, and make sure the new <code>.env</code> file isn’t tracked.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Changing your Django <code>SECRET_KEY</code> might feel intimidating the first time, but it’s pretty simple when you break it down. As long as you generate a secure key, store it safely, and don’t expose it publicly, you’re doing great.</p>
<p>One last thing—<strong>when was the last time you checked if your secret key was accidentally pushed to GitHub?</strong> It might be a good time to take a quick look.</p>
<h3 id="heading-helpful-resources">Helpful Resources</h3>
<ul>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/settings/#std-setting-SECRET_KEY">Django Docs – SECRET_KEY</a></p>
</li>
<li><p><a target="_blank" href="https://www.gitguardian.com/">GitGuardian – Secrets Detection</a></p>
</li>
<li><p><a target="_blank" href="https://12factor.net/config">12 Factor App – Config</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/henriquebastos/python-decouple">Python-Decouple GitHub</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Is Q in Django? (And Why It's Super Useful) ]]>
                </title>
                <description>
                    <![CDATA[ If you're working with Django and writing queries, chances are you’ve bumped into a situation where you need to combine filters in a way that’s just... not straightforward. Maybe you're trying to search for users with a username or an email that matc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-q-in-django-and-why-its-super-useful/</link>
                <guid isPermaLink="false">680a4adad2926105c84b08ae</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Thu, 24 Apr 2025 14:29:46 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745504806983/58c92bf9-b2e6-486a-8722-d364decc5d1a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're working with Django and writing queries, chances are you’ve bumped into a situation where you need to combine filters in a way that’s just... not straightforward.</p>
<p>Maybe you're trying to search for users with a username <em>or</em> an email that matches something. Or maybe you're trying to filter results where one condition is true <em>but</em> another is false.</p>
<p>That’s where <code>Q</code> comes in.</p>
<p>I remember the first time I ran into this problem – trying to use <code>or</code> in a <code>.filter()</code> and realizing quickly that regular Python logic doesn’t play nice there.</p>
<p>The error messages were confusing, and the docs didn’t help much. So let me break it down for you in a simple, practical way.</p>
<p>By the end of this guide, you’ll understand exactly what <code>Q</code> is, how it works, and how it can make your Django queries cleaner, more powerful, and a lot more flexible.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-whats-q-all-about">What's Q All About?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-q-in-django">How to Use Q in Django</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-example-1-or-logic">Example 1: OR Logic</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-2-and-logic-still-useful-with-q">Example 2: AND Logic (Still Useful with Q)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-3-not-logic">Example 3: NOT Logic</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-when-should-you-use-q">When Should You Use Q?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-mixing-q-and-regular-filters">Mixing Q and Regular Filters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-world-example-filtering-products">Real-World Example: Filtering Products</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-gotchas-things-to-watch-out-for">Gotchas (Things To Watch Out For)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-frequently-asked-questions">Frequently Asked Questions</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-is-using-q-slower-than-a-regular-filter">Is using Q slower than a regular filter()?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-i-use-q-with-annotate-or-aggregate">Can I use Q with annotate() or aggregate()?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-i-build-q-objects-dynamically">Can I build Q objects dynamically?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-further-resources">Further Resources</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-whats-q-all-about">What's Q All About?</h2>
<p>In Django, the <code>Q</code> object (from <code>django.db.models</code>) lets you build complex queries using <strong>OR</strong>, <strong>AND</strong>, and <strong>NOT</strong> logic – something that’s hard to do using just regular <code>.filter()</code> calls.</p>
<p>Normally, when you use <code>.filter()</code> in Django, it adds AND logic like this:</p>
<pre><code class="lang-python">MyModel.objects.filter(name=<span class="hljs-string">'Alice'</span>, age=<span class="hljs-number">30</span>)
</code></pre>
<p>This will get all rows where the <code>name</code> is <code>'Alice'</code> <em>and</em> the <code>age</code> is <code>30</code>. But what if you want:</p>
<blockquote>
<p>Get all rows where name is 'Alice' <strong>or</strong> age is 30?</p>
</blockquote>
<p>You can’t just do this:</p>
<pre><code class="lang-python">MyModel.objects.filter(name=<span class="hljs-string">'Alice'</span> <span class="hljs-keyword">or</span> age=<span class="hljs-number">30</span>)  <span class="hljs-comment"># ❌ This won't work!</span>
</code></pre>
<p>That’s where <code>Q</code> comes in.</p>
<h2 id="heading-how-to-use-q-in-django">How to Use Q in Django</h2>
<p>Here’s the basic import:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db.models <span class="hljs-keyword">import</span> Q
</code></pre>
<p>Now, you can use <code>Q</code> to create conditions and combine them using the <code>|</code> (OR), <code>&amp;</code> (AND), and <code>~</code> (NOT) operators.</p>
<p>Let’s say you have a model like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>(<span class="hljs-params">models.Model</span>):</span>
    name = models.CharField(max_length=<span class="hljs-number">100</span>)
    age = models.IntegerField()
    city = models.CharField(max_length=<span class="hljs-number">100</span>)
</code></pre>
<h3 id="heading-example-1-or-logic">Example 1: OR Logic</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db.models <span class="hljs-keyword">import</span> Q

people = Person.objects.filter(Q(name=<span class="hljs-string">'Alice'</span>) | Q(age=<span class="hljs-number">30</span>))
</code></pre>
<p>This will return anyone whose name is 'Alice' <strong>or</strong> whose age is 30. That’s clean and readable, right?</p>
<h3 id="heading-example-2-and-logic-still-useful-with-q">Example 2: AND Logic (Still Useful with Q)</h3>
<pre><code class="lang-python">people = Person.objects.filter(Q(name=<span class="hljs-string">'Alice'</span>) &amp; Q(age=<span class="hljs-number">30</span>))
</code></pre>
<p>This will return people where <strong>both</strong> conditions are true. Technically, this gives the same result as using:</p>
<pre><code class="lang-python">Person.objects.filter(name=<span class="hljs-string">'Alice'</span>, age=<span class="hljs-number">30</span>)
</code></pre>
<p>So why bother with Q here?</p>
<p>The real power of <code>Q</code> with <code>AND</code> is when you start <strong>nesting more complex conditions</strong>. For instance, suppose you want to find people who are named Alice and either live in Paris or are under 25. Here’s how you could write that:</p>
<pre><code class="lang-python">people = Person.objects.filter(
    Q(name=<span class="hljs-string">'Alice'</span>) &amp; (Q(city=<span class="hljs-string">'Paris'</span>) | Q(age__lt=<span class="hljs-number">25</span>))
)
</code></pre>
<p>Without <code>Q</code>, this logic would be hard (and messy) to express. <code>Q</code> lets you group conditions logically and write flexible, readable queries.</p>
<h3 id="heading-example-3-not-logic">Example 3: NOT Logic</h3>
<p>What if you want everyone <em>except</em> people named Alice?</p>
<pre><code class="lang-python">people = Person.objects.filter(~Q(name=<span class="hljs-string">'Alice'</span>))
</code></pre>
<p>The <code>~</code> operator flips the condition – it's saying “not this”.</p>
<h2 id="heading-when-should-you-use-q">When Should You Use Q?</h2>
<p>You can reach for <code>Q</code> when:</p>
<ul>
<li><p>You need OR conditions</p>
</li>
<li><p>You want to combine filters dynamically (for example, building a query based on user input)</p>
</li>
<li><p>You need to write complex conditional logic</p>
</li>
<li><p>You want to exclude certain things using <code>~Q(...)</code></p>
</li>
</ul>
<h3 id="heading-but-are-there-times-you-shouldnt-use-q"><strong>But are there times you shouldn't use Q?</strong></h3>
<p>Yes – if you're writing a straightforward filter with only AND logic (like <code>name='Alice'</code> and <code>age=30</code>), using <code>Q</code> doesn't add much value. It can make your code unnecessarily verbose. Stick with plain <code>.filter()</code> unless you need more flexibility.</p>
<h2 id="heading-mixing-q-and-regular-filters">Mixing Q and Regular Filters</h2>
<p>You can mix <code>Q</code> objects with normal keyword arguments in a filter. Just be careful with parentheses and order.</p>
<pre><code class="lang-python">Person.objects.filter(Q(name=<span class="hljs-string">'Alice'</span>) | Q(city=<span class="hljs-string">'Paris'</span>), age__gte=<span class="hljs-number">25</span>)
</code></pre>
<p>This translates to:</p>
<p><strong>(name = 'Alice' OR city = 'Paris') AND age &gt;= 25</strong></p>
<p>But here’s where <strong>parentheses</strong> make a big difference.</p>
<p>Take this incorrect example:</p>
<pre><code class="lang-python">Person.objects.filter(Q(name=<span class="hljs-string">'Alice'</span>) | Q(city=<span class="hljs-string">'Paris'</span>) &amp; Q(age__gte=<span class="hljs-number">25</span>))
</code></pre>
<p>Due to operator precedence, this will evaluate as:</p>
<p><strong>name = 'Alice' OR (city = 'Paris' AND age &gt;= 25)</strong></p>
<p>Which is not what you probably intended!</p>
<p>So when in doubt, <strong>use parentheses</strong> to clearly define your logic:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Correct: (name = 'Alice' OR city = 'Paris') AND age &gt;= 25</span>
Person.objects.filter((Q(name=<span class="hljs-string">'Alice'</span>) | Q(city=<span class="hljs-string">'Paris'</span>)) &amp; Q(age__gte=<span class="hljs-number">25</span>))
</code></pre>
<h2 id="heading-real-world-example-filtering-products">Real-World Example: Filtering Products</h2>
<p>Say you’ve got a <code>Product</code> model with <code>price</code>, <code>in_stock</code>, and <code>category</code>.</p>
<p>You want all products that are either:</p>
<ul>
<li><p>cheaper than $20 and in stock<br>  <strong>or</strong></p>
</li>
<li><p>In the 'Books' category</p>
</li>
</ul>
<p>Here’s how that might look:</p>
<pre><code class="lang-python">Product.objects.filter(
    (Q(price__lt=<span class="hljs-number">20</span>) &amp; Q(in_stock=<span class="hljs-literal">True</span>)) | Q(category=<span class="hljs-string">'Books'</span>)
)
</code></pre>
<p>Without <code>Q</code>You’d have to write separate queries and merge them, or use more complicated logic. This way is faster and more efficient.</p>
<h2 id="heading-things-to-watch-out-for">Things to Watch Out For</h2>
<ul>
<li><p><strong>Use parentheses</strong>: Just like in math, they control how things combine. Don’t trust default operator precedence unless you know it well.</p>
</li>
<li><p><strong>Don’t use</strong> <code>or</code>/<code>and</code> keywords: Python’s logical operators don’t work with Django ORM queries. Use <code>|</code> and <code>&amp;</code> instead.</p>
</li>
<li><p><strong>Mixing</strong> <code>Q</code> with <code>.exclude()</code>? Be extra careful. Why? Because <code>.exclude()</code> <strong>inverts</strong> the logic of the entire filter. That means if you write:</p>
<pre><code class="lang-python">  Person.objects.exclude(Q(name=<span class="hljs-string">'Alice'</span>) &amp; Q(city=<span class="hljs-string">'Paris'</span>))
</code></pre>
<p>  It’s saying: <strong>Exclude anyone who is named Alice <em>and</em> lives in Paris.</strong></p>
<p>  But what if you wrote:</p>
<pre><code class="lang-python">  Person.objects.exclude(Q(name=<span class="hljs-string">'Alice'</span>) | Q(city=<span class="hljs-string">'Paris'</span>))
</code></pre>
<p>  Now it excludes anyone named Alice <strong>or</strong> who lives in Paris – a much broader exclusion! So always double-check what you're excluding.</p>
</li>
<li><p>You might need to invert specific parts of your logic using <code>~Q(...)</code> <strong>before</strong> passing them to <code>.exclude()</code> Rather than excluding the whole expression.</p>
</li>
</ul>
<h2 id="heading-frequently-asked-questions">Frequently Asked Questions</h2>
<h3 id="heading-is-using-q-slower-than-a-regular-filter"><strong>Is using Q slower than a regular</strong> <code>filter()</code><strong>?</strong></h3>
<p>Nope! Under the hood, Django converts your query into optimized SQL. Whether you use <code>filter(name='Alice')</code> or <code>filter(Q(name='Alice'))</code>Performance is almost the same. What matters more is <em>how complex</em> your query is.</p>
<h3 id="heading-can-i-use-q-with-annotate-or-aggregate"><strong>Can I use Q with</strong> <code>annotate()</code> <strong>or</strong> <code>aggregate()</code><strong>?</strong></h3>
<p>Yep. You can use <code>Q</code> with <code>annotate()</code> to apply conditional logic for things like counting or filtering within annotations.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db.models <span class="hljs-keyword">import</span> Count

<span class="hljs-comment"># Count users with more than one blog post</span>
User.objects.annotate(
    post_count=Count(<span class="hljs-string">'posts'</span>, filter=Q(posts__published=<span class="hljs-literal">True</span>))
)
</code></pre>
<h3 id="heading-can-i-build-q-objects-dynamically"><strong>Can I build Q objects dynamically?</strong></h3>
<p>Absolutely. That’s one of the best parts! You can build up a list of <code>Q()</code> objects and combine them however you want:</p>
<pre><code class="lang-python">filters = Q()
<span class="hljs-keyword">if</span> search_name:
    filters |= Q(name__icontains=search_name)
<span class="hljs-keyword">if</span> search_city:
    filters |= Q(city__icontains=search_city)

results = Person.objects.filter(filters)
</code></pre>
<p>This is especially useful for search forms or APIS where users can pass different combinations of filters.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>So that’s <code>Q</code> In Django. It’s not some scary, abstract concept – it’s just a powerful way to control how your queries behave.</p>
<p>Once you get used to using <code>Q</code>, your code becomes cleaner, easier to read, and more flexible when handling complex filters.</p>
<p>Honestly, I can’t imagine writing Django queries without it anymore.</p>
<h3 id="heading-further-resources">Further Resources</h3>
<p>Want to go deeper?</p>
<ul>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/topics/db/queries/#complex-lookups-with-q-objects">Django Q Object Official Docs</a></p>
</li>
<li><p><a target="_blank" href="https://realpython.com/tutorials/django/">Real Python's Guide to Q Objects</a></p>
</li>
<li><p><a target="_blank" href="https://books.agiliq.com/projects/django-orm-cookbook/en/latest/q_objects.html">Django ORM Cookbook</a> – solid practical examples</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Change the Password of a Superuser in Django ]]>
                </title>
                <description>
                    <![CDATA[ Changing a superuser password in Django might sound like a big task, but it’s one of the easiest things to do once you know how. If you’re working on a Django project – whether it’s a hobby blog, a client’s website, or a bigger web application – mana... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-change-the-password-of-a-superuser-in-django/</link>
                <guid isPermaLink="false">6808f23b332c138efcea040d</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Wed, 23 Apr 2025 13:59:23 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745416742960/89cce35f-2e91-4329-8fea-0d1551bea2c7.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Changing a superuser password in Django might sound like a big task, but it’s one of the easiest things to do once you know how.</p>
<p>If you’re working on a Django project – whether it’s a hobby blog, a client’s website, or a bigger web application – managing your admin accounts safely is a must.</p>
<p>And one key part of that? Making sure your superuser password is strong, secure, and easy for <em>you</em> to update.</p>
<p>You might be doing this because you forgot the old password, you're handing the project off to someone else, or you're tightening security after a team change.</p>
<p>Whatever your reason is, this guide will walk you through the easiest and safest ways to change a superuser password in Django.</p>
<p>I’ll break everything down in simple language, no heavy tech lingo or assumptions.</p>
<p>Let’s dive in.</p>
<h3 id="heading-what-well-cover">What we’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-changing-the-superuser-password-matters">Why Changing the Superuser Password Matters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-simple-ways-to-change-a-django-superuser-password">3 Simple Ways to Change a Django Superuser Password</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-method-1-use-djangos-built-in-command">Method 1: Use Django’s Built-In Command</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-method-2-use-the-django-shell">Method 2: Use the Django Shell</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-method-3-use-django-admin-if-youre-logged-in">Method 3: Use Django Admin (If You’re Logged In)</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-bonus-forgot-your-superuser-username">Bonus: Forgot Your Superuser Username?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-faqs">FAQs</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-if-i-forgot-both-the-username-and-password">What if I forgot both the username and password?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-will-this-log-out-other-users">Will this log out other users?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-i-change-the-password-from-the-database-directly">Can I change the password from the database directly?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-do-i-know-if-my-new-password-is-secure">How do I know if my new password is secure?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-further-reading-and-tools">Further Reading and Tools</a></p>
</li>
</ul>
<h2 id="heading-why-changing-the-superuser-password-matters">Why Changing the Superuser Password Matters</h2>
<p>Your Django superuser has full access to the admin dashboard. This means they can add or delete users, edit data, manage settings – everything. If that account gets compromised, the whole site is at risk.</p>
<p>Here’s what could go wrong if the password is weak or outdated:</p>
<ul>
<li><p>Someone could delete your database.</p>
</li>
<li><p>A hacker could inject malicious data.</p>
</li>
<li><p>Private user info could be exposed.</p>
</li>
</ul>
<p>According to <a target="_blank" href="https://www.verizon.com/business/en-sg/resources/articles/analyzing-covid-19-data-breach-landscape/">Verizon’s Data Breach Investigations Report</a>, over <strong>80%</strong> of hacking-related breaches are due to compromised or weak passwords. That’s a huge risk for something that’s easy to fix in a few minutes.</p>
<p>So let’s make sure your Django admin is locked down tight – without breaking anything.</p>
<h2 id="heading-3-simple-ways-to-change-a-django-superuser-password">3 Simple Ways to Change a Django Superuser Password</h2>
<p>I’ll show you three different ways to update your superuser password. You only need to pick one that fits your current setup.</p>
<h3 id="heading-method-1-use-djangos-built-in-command">Method 1: Use Django’s Built-In Command</h3>
<p>If you have access to the command line and your project’s virtual environment, this is the cleanest way.</p>
<h4 id="heading-activate-your-virtual-environment"><strong>Activate your virtual environment</strong></h4>
<p>This depends on your setup, but if you're using <code>venv</code> it might look like this:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> venv/bin/activate
</code></pre>
<p>Or on Windows:</p>
<pre><code class="lang-python">venv\Scripts\activate
</code></pre>
<h4 id="heading-navigate-to-your-project-folder"><strong>Navigate to your project folder</strong></h4>
<p>This is where <code>manage.py</code> lives:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> your_project_folder
</code></pre>
<h4 id="heading-run-the-following-command"><strong>Run the following command:</strong></h4>
<pre><code class="lang-bash">python manage.py changepassword your_superuser_username
</code></pre>
<p>Example:</p>
<pre><code class="lang-bash">python manage.py changepassword admin
</code></pre>
<p>Django will then ask you to enter a new password. Type it in, hit enter, confirm it again, and you’re done.</p>
<p>That’s it. You just changed your superuser password!</p>
<h3 id="heading-method-2-use-the-django-shell">Method 2: Use the Django Shell</h3>
<p>Maybe you don’t remember the username or want more control. The Django shell lets you interact directly with your database using Python.</p>
<p>Here’s how:</p>
<p>First, open the shell:</p>
<pre><code class="lang-bash">python manage.py shell
</code></pre>
<p>Then run the following code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib.auth <span class="hljs-keyword">import</span> get_user_model

User = get_user_model()

user = User.objects.get(username=<span class="hljs-string">"admin"</span>)  <span class="hljs-comment"># Replace 'admin' with your username</span>
user.set_password(<span class="hljs-string">"new_secure_password"</span>)   <span class="hljs-comment"># Replace with your new password</span>
user.save()
</code></pre>
<p>Now exit the shell:</p>
<pre><code class="lang-python">exit()
</code></pre>
<p>That’s it. This method is especially helpful if you’re working in a staging environment or doing things programmatically.</p>
<h3 id="heading-method-3-use-django-admin-if-youre-logged-in">Method 3: Use Django Admin (If You’re Logged In)</h3>
<p>This one only works if you can still log in with the current superuser account.</p>
<ol>
<li><p>Go to your Django admin page, usually at <code>http://127.0.0.1:8000/admin/</code>.</p>
</li>
<li><p>Log in with your current credentials.</p>
</li>
<li><p>Click on <strong>Users</strong>.</p>
</li>
<li><p>Find your superuser account and click on it.</p>
</li>
<li><p>Scroll down to the “Password” section and click <strong>"this form"</strong> under the "Raw passwords are not stored..." message.</p>
</li>
<li><p>Enter your new password twice and save.</p>
</li>
</ol>
<p>This method is super quick and doesn’t require any code at all.</p>
<h2 id="heading-bonus-forgot-your-superuser-username">Bonus: Forgot Your Superuser Username?</h2>
<p>If you don’t remember the exact username of your superuser, no worries. You can list all users like this:</p>
<pre><code class="lang-bash">python manage.py shell
</code></pre>
<p>Then:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib.auth <span class="hljs-keyword">import</span> get_user_model

User = get_user_model()

<span class="hljs-keyword">for</span> user <span class="hljs-keyword">in</span> User.objects.all():
    print(user.username)
</code></pre>
<p>This will print out all usernames in your system, including your superuser.</p>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-what-if-i-forgot-both-the-username-and-password"><strong>What if I forgot both the username and password?</strong></h3>
<p>Use the shell method above to list all usernames, then reset it using either the shell or the <code>changepassword</code> command.</p>
<h3 id="heading-will-this-log-out-other-users"><strong>Will this log out other users?</strong></h3>
<p>Changing your superuser password won’t affect other users unless you have custom logic tied to sessions. For most projects, everything else keeps running just fine.</p>
<h3 id="heading-can-i-change-the-password-from-the-database-directly"><strong>Can I change the password from the database directly?</strong></h3>
<p>Technically yes, but <strong>don’t do it</strong>. Passwords in Django are hashed using PBKDF2 by default. If you enter something manually in the database, it won’t work unless it's hashed the right way. Always use the Django shell or admin panel instead.</p>
<h3 id="heading-how-do-i-know-if-my-new-password-is-secure"><strong>How do I know if my new password is secure?</strong></h3>
<p>Django checks password strength by default. But if you want to be extra safe, use a tool like <a target="_blank" href="https://bitwarden.com/password-generator/">Bitwarden Password Generator</a> or <a target="_blank" href="https://1password.com/password-generator/">1Password’s Generator</a>.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>That’s pretty much everything you need to know to change your superuser password in Django. It’s quick, safe, and once you’ve done it once, it’ll be second nature.</p>
<p>It’s small actions like this that go a long way in keeping your Django projects secure. And since it only takes a minute or two, there’s no reason to put it off.</p>
<p>Let’s keep the conversation going, Connect with me on <a target="_blank" href="http://X.com/_udemezue">x.com/_udemezue</a></p>
<h3 id="heading-further-reading-and-tools">Further Reading and Tools</h3>
<ul>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/django-admin/#changepassword">Official Django change password documentation</a></p>
</li>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/topics/auth/passwords/">How Django stores passwords securely</a></p>
</li>
<li><p><a target="_blank" href="https://owasp.org/www-community/vulnerabilities/Using_Insufficiently_Random_Values">PBKDF2 explained on OWASP</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use a Foreign Key in Django ]]>
                </title>
                <description>
                    <![CDATA[ When you're building something in Django – whether it's a blog, a to-do app, or even something way more complex – at some point, you'll want to connect different pieces of data. That’s where ForeignKey comes in. It helps link one model to another, li... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-a-foreign-key-in-django/</link>
                <guid isPermaLink="false">6807a227b77713cc8e0f6059</guid>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Tue, 22 Apr 2025 14:05:27 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745330646960/e2fc7f1d-73f9-4e25-b870-e0928833e7a5.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you're building something in Django – whether it's a blog, a to-do app, or even something way more complex – at some point, you'll want to connect different pieces of data.</p>
<p>That’s where <code>ForeignKey</code> comes in. It helps link one model to another, like tying a comment to a post, or an order to a customer.</p>
<p>It’s one of those things in Django that can seem confusing at first, but once it clicks, you’ll wonder how you ever built apps without it.</p>
<p>So let’s break it all down. I’ll walk you through everything from what a ForeignKey is, to how to use it in your Django project.</p>
<h2 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-foreign-key-in-django">What is a Foreign Key in Django?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-use-a-foreignkey-instead-of-storing-ids-manually">Why Use a ForeignKey Instead of Storing IDs Manually?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-world-example-blog-posts-and-comments">Real-World Example: Blog Posts and Comments</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-ondelete-and-why-does-it-matter">What is on_delete and Why Does It Matter?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-access-related-objects-in-django">How to Access Related Objects in Django</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-foreign-key-relationships-in-django-admin">How to Create Foreign Key Relationships in Django Admin</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-what-happens-in-the-database">What Happens in the Database?</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-query-with-foreignkey">How to Query with ForeignKey</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-get-all-comments-for-a-post-with-id1">Get all comments for a post with id=1:</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-get-all-posts-that-have-at-least-one-comment-by-a-specific-user">Get all posts that have at least one comment by a specific user:</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-faqs">FAQs</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-can-a-foreignkey-be-optional">Can a ForeignKey be optional?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-a-foreignkey-point-to-the-same-model-self">Can a ForeignKey point to the same model (self)?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-a-model-have-more-than-one-foreignkey">Can a model have more than one ForeignKey?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-further-resources">Further Resources</a></li>
</ul>
</li>
</ul>
<h2 id="heading-what-is-a-foreign-key-in-django">What is a Foreign Key in Django?</h2>
<p>In the simplest terms, a Foreign Key in Django creates a many-to-one relationship between two models. This means many rows in one table can be related to a single row in another.</p>
<p>For example:</p>
<ul>
<li><p>One blog post can have <strong>many comments</strong></p>
</li>
<li><p>One customer can have <strong>many orders</strong></p>
</li>
<li><p>One author can write <strong>many books</strong></p>
</li>
</ul>
<p>If you're coming from a spreadsheet background, think of it like linking two sheets using a shared column. In Django, you do this in your model definitions.</p>
<h2 id="heading-why-use-a-foreignkey-instead-of-storing-ids-manually">Why Use a ForeignKey Instead of Storing IDs Manually?</h2>
<p>You might be wondering, “Why not just store the ID of the related object in a plain integer field?”</p>
<p>Well, you could – but you'd lose a ton of power. Without a ForeignKey:</p>
<ul>
<li><p>You don’t get automatic validation that the related object exists.</p>
</li>
<li><p>You can't follow relationships easily in queries (for example, <code>post.comments.all()</code> wouldn’t be possible).</p>
</li>
<li><p>The Django admin can’t provide dropdowns or inline forms for related data.</p>
</li>
<li><p>You lose out on helpful features like <code>on_delete</code> behaviour and related object naming.</p>
</li>
</ul>
<p>ForeignKey fields automate and enforce these relationships, making your code cleaner, more secure, and easier to maintain.</p>
<h2 id="heading-real-world-example-blog-posts-and-comments">Real-World Example: Blog Posts and Comments</h2>
<p>Let’s say you’re building a blog. You’ll probably have a <code>Post</code> model and a <code>Comment</code> model. Each comment needs to be linked to a specific post.</p>
<p>Here’s how that looks in code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span>(<span class="hljs-params">models.Model</span>):</span>
    title = models.CharField(max_length=<span class="hljs-number">200</span>)
    content = models.TextField()
    published_at = models.DateTimeField(auto_now_add=<span class="hljs-literal">True</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.title

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Comment</span>(<span class="hljs-params">models.Model</span>):</span>
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    author = models.CharField(max_length=<span class="hljs-number">100</span>)
    text = models.TextField()
    created_at = models.DateTimeField(auto_now_add=<span class="hljs-literal">True</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'Comment by <span class="hljs-subst">{self.author}</span>'</span>
</code></pre>
<p>Let me explain each part of that:</p>
<ul>
<li><p><code>models.ForeignKey(Post, on_delete=models.CASCADE)</code>: This line creates the connection. It means each comment is linked to one post. The <code>on_delete=models.CASCADE</code> part tells Django to delete all related comments if a post is deleted.</p>
</li>
<li><p><code>__str__</code> methods just make it easier to read things in the admin or shell.</p>
</li>
</ul>
<h2 id="heading-what-is-ondelete-and-why-does-it-matter">What is <code>on_delete</code> and Why Does It Matter?</h2>
<p>When you create a ForeignKey in Django, you have to include an <code>on_delete</code> argument. This controls what happens to the child rows (like comments) if the parent row (like a blog post) is deleted.</p>
<p>Here are the common options:</p>
<ul>
<li><p><code>models.CASCADE</code>: Delete the child rows, too (like deleting all comments when a post is deleted).</p>
</li>
<li><p><code>models.PROTECT</code>: Prevent deletion if there are related objects.</p>
</li>
<li><p><code>models.SET_NULL</code>: Set the ForeignKey to <code>NULL</code> instead of deleting.</p>
</li>
<li><p><code>models.SET_DEFAULT</code>: Set a default value.</p>
</li>
<li><p><code>models.DO_NOTHING</code>: Do nothing (not recommended unless you really know what you're doing).</p>
</li>
</ul>
<p>I usually go with <code>CASCADE</code> for simple apps, but it's worth thinking through depending on the situation.</p>
<h2 id="heading-how-to-access-related-objects-in-django">How to Access Related Objects in Django</h2>
<p>Once you’ve set up the ForeignKey, Django gives you a few nice tools to work with related data.</p>
<p>For example, let’s say you have a post object:</p>
<pre><code class="lang-python">post = Post.objects.get(id=<span class="hljs-number">1</span>)
</code></pre>
<p>You can get all comments for that post like this:</p>
<pre><code class="lang-python">comments = post.comment_set.all()
</code></pre>
<p>The <code>comment_set</code> is automatically created by Django, and you can customize the name with <code>related_name</code>:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Comment</span>(<span class="hljs-params">models.Model</span>):</span>
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name=<span class="hljs-string">'comments'</span>)
</code></pre>
<p>Now you can do:</p>
<pre><code class="lang-python">post.comments.all()
</code></pre>
<p>Much cleaner, right?</p>
<h2 id="heading-how-to-create-foreign-key-relationships-in-django-admin">How to Create Foreign Key Relationships in Django Admin</h2>
<p>The Django admin handles ForeignKeys well. If you’ve got both <code>Post</code> and <code>Comment</code> models registered in <code>admin.py</code>, you’ll get a dropdown in the comment form to select the post it belongs to.</p>
<p>You can also make inline forms, so you can add comments while editing a post. Here’s a quick example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Post, Comment

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CommentInline</span>(<span class="hljs-params">admin.TabularInline</span>):</span>
    model = Comment
    extra = <span class="hljs-number">1</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostAdmin</span>(<span class="hljs-params">admin.ModelAdmin</span>):</span>
    inlines = [CommentInline]

admin.site.register(Post, PostAdmin)
admin.site.register(Comment)
</code></pre>
<p>Now when you're editing a post, you can add or edit comments right there on the same page.</p>
<h3 id="heading-what-happens-in-the-database">What Happens in the Database?</h3>
<p>Django uses a relational database (like PostgreSQL, MySQL, or SQLite), and ForeignKey creates a column in the database table that holds the ID of the related object.</p>
<p>If you run <code>python manage.py makemigrations</code> and then <code>python manage.py migrate</code>, Django will create the actual database tables with the proper relationships behind the scenes.</p>
<h2 id="heading-how-to-query-with-foreignkey">How to Query with ForeignKey</h2>
<p>You can also filter or search based on ForeignKey relationships:</p>
<h3 id="heading-get-all-comments-for-a-post-with-id1">Get all comments for a post with id=1:</h3>
<pre><code class="lang-python">Comment.objects.filter(post_id=<span class="hljs-number">1</span>)
</code></pre>
<p>Or, using the post object:</p>
<pre><code class="lang-python">post = Post.objects.get(id=<span class="hljs-number">1</span>)
comments = Comment.objects.filter(post=post)
</code></pre>
<h3 id="heading-get-all-posts-that-have-at-least-one-comment-by-a-specific-user">Get all posts that have at least one comment by a specific user:</h3>
<pre><code class="lang-python">Post.objects.filter(comments__author=<span class="hljs-string">'John'</span>)
</code></pre>
<p>That <code>comments__author</code> part is thanks to the <code>related_name='comments'</code> I added earlier.</p>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-can-a-foreignkey-be-optional"><strong>Can a ForeignKey be optional?</strong></h3>
<p>Yes, just add <code>null=True, blank=True</code> like this:</p>
<pre><code class="lang-python">post = models.ForeignKey(Post, on_delete=models.SET_NULL, null=<span class="hljs-literal">True</span>, blank=<span class="hljs-literal">True</span>)
</code></pre>
<p>You might want this if the related object isn't always required. For example, a <code>Comment</code> might <em>optionally</em> belong to a <code>Post</code>, or a <code>Task</code> might optionally have a related <code>Project</code>. It’s useful when building drafts, soft deletes, or handling legacy data.</p>
<h3 id="heading-can-a-foreignkey-point-to-the-same-model-self"><strong>Can a ForeignKey point to the same model (self)?</strong></h3>
<p>Absolutely. That’s called a self-referential ForeignKey, often used for things like threaded comments or categories.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Category</span>(<span class="hljs-params">models.Model</span>):</span>
    name = models.CharField(max_length=<span class="hljs-number">100</span>)
    parent = models.ForeignKey(<span class="hljs-string">'self'</span>, null=<span class="hljs-literal">True</span>, blank=<span class="hljs-literal">True</span>, on_delete=models.SET_NULL)
</code></pre>
<h3 id="heading-can-a-model-have-more-than-one-foreignkey"><strong>Can a model have more than one ForeignKey?</strong></h3>
<p>Totally. For example, an Order model could have one ForeignKey to a Customer, and another to a ShippingAddress.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>If you’re building anything in Django that deals with more than one model, understanding ForeignKey is essential. It makes your app more structured, easier to query, and way more powerful.</p>
<p>At first, it might feel like a lot, but once you build one or two relationships and see it all working in the admin and your views, it clicks.</p>
<p>And if something’s still unclear, that’s normal. I had to build a few mini-projects before it started to feel natural.</p>
<h3 id="heading-further-resources">Further Resources</h3>
<ul>
<li><p>Django Docs on <a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/models/fields/#foreignkey">ForeignKey</a></p>
</li>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/models/fields/">Django Model Field Reference</a></p>
</li>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/topics/db/models/">Writing Models in Django</a></p>
</li>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/">Django Admin Docs</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use PostgreSQL in Django ]]>
                </title>
                <description>
                    <![CDATA[ If you’re building a Django project and wondering which database to use, PostgreSQL is a great choice. It’s reliable, fast, packed with powerful features, and works beautifully with Django. I’ve used it across multiple projects – from small web apps ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-postgresql-in-django/</link>
                <guid isPermaLink="false">68079d18a34a9e3143fe9e56</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PostgreSQL ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Tue, 22 Apr 2025 13:43:52 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745329406033/4d3cb010-d612-4ca8-8039-2d922e8b0337.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you’re building a Django project and wondering which database to use, PostgreSQL is a great choice. It’s reliable, fast, packed with powerful features, and works beautifully with Django.</p>
<p>I’ve used it across multiple projects – from small web apps to large-scale platforms – and it never disappoints.</p>
<p>In this post, I’ll walk you through how to connect PostgreSQL with Django step-by-step.</p>
<p>Let’s get started.</p>
<h3 id="heading-what-well-cover">What we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-why-use-postgresql-with-django">Why Use PostgreSQL with Django?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-youll-need">What You'll Need</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-postgresql-in-django">How to Use PostgreSQL in Django</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-step-1-install-postgresql">Step 1: Install PostgreSQL</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-install-the-postgresql-adapter-for-python">Step 2: Install the PostgreSQL Adapter for Python</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-create-a-django-project-if-you-havent-yet">Step 3: Create a Django Project (If You Haven’t Yet)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-4-create-a-postgresql-database">Step 4: Create a PostgreSQL Database</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-5-update-django-settings-to-use-postgresql">Step 5: Update Django Settings to Use PostgreSQL</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-6-run-migrations">Step 6: Run Migrations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-7-test-the-connection">Step 7: Test the Connection</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-common-issues-and-fixes">Common Issues (and Fixes)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-optional-use-dj-database-url-for-better-settings">Optional: Use dj-database-url for Better Settings</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-frequently-asked-questions">Frequently Asked Questions</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-is-postgresql-better-than-sqlite-for-django">Is PostgreSQL better than SQLite for Django?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-do-i-need-to-install-postgresql-on-my-production-server">Do I need to install PostgreSQL on my production server?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-is-psycopg2-binary-safe-to-use-in-production">Is psycopg2-binary safe to use in production?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-i-switch-from-sqlite-to-postgresql-mid-project">Can I switch from SQLite to PostgreSQL mid-project?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-further-resources">Further Resources</a></p>
</li>
</ol>
<h2 id="heading-why-use-postgresql-with-django">Why Use PostgreSQL with Django?</h2>
<p>PostgreSQL is a popular, open-source relational database that’s known for its performance, flexibility, and powerful features like:</p>
<ul>
<li><p>Advanced data types (JSON, arrays, and so on)</p>
</li>
<li><p>Full-text search</p>
</li>
<li><p>Support for complex queries</p>
</li>
<li><p>Data integrity and reliability</p>
</li>
</ul>
<p>Django officially recommends PostgreSQL as the most feature-complete database backend it supports. If you're planning to build a serious web application, PostgreSQL is usually the best database to pair with Django.</p>
<h2 id="heading-what-youll-need">What You’ll Need</h2>
<p>Before we begin, make sure you have the following:</p>
<ul>
<li><p>Python installed (3.7 or higher is best)</p>
</li>
<li><p>Django installed (I’ll be using version 4.x)</p>
</li>
<li><p>PostgreSQL installed and running</p>
</li>
<li><p><code>psycopg2</code> or <code>psycopg2-binary</code> (This is the adapter that lets Django talk to PostgreSQL)</p>
</li>
</ul>
<h2 id="heading-how-to-use-postgresql-in-django">How to Use PostgreSQL in Django</h2>
<p>Here is how to get started:</p>
<h3 id="heading-step-1-install-postgresql">Step 1: Install PostgreSQL</h3>
<p>If you haven’t installed PostgreSQL yet, you can grab it from the <a target="_blank" href="https://www.postgresql.org/download/">official PostgreSQL website</a>. It works on Windows, macOS, and Linux.</p>
<p>Make sure you remember the username, password, and database name when you set it up – you’ll need those later.</p>
<h3 id="heading-step-2-install-the-postgresql-adapter-for-python">Step 2: Install the PostgreSQL Adapter for Python</h3>
<p>Django needs a little help to connect with PostgreSQL. That’s where <code>psycopg2</code> comes in.</p>
<p>You can install it using pip:</p>
<pre><code class="lang-bash">pip install psycopg2-binary
</code></pre>
<p>Tip: The <code>-binary</code> version is easier to install and works for most people. If you run into issues later, you can switch to <code>psycopg2</code> (non-binary).</p>
<h3 id="heading-step-3-create-a-django-project-if-you-havent-yet">Step 3: Create a Django Project (If You Haven’t Yet)</h3>
<p>If you haven’t created a project yet, start with:</p>
<pre><code class="lang-bash">django-admin startproject myproject
<span class="hljs-built_in">cd</span> myproject
</code></pre>
<p>This will give you the basic project structure.</p>
<h3 id="heading-step-4-create-a-postgresql-database">Step 4: Create a PostgreSQL Database</h3>
<p>Now, open your PostgreSQL client (like <code>psql</code> or pgAdmin), and create a new database:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> mydatabase;
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">USER</span> myuser <span class="hljs-keyword">WITH</span> <span class="hljs-keyword">PASSWORD</span> <span class="hljs-string">'mypassword'</span>;
<span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">ROLE</span> myuser <span class="hljs-keyword">SET</span> client_encoding <span class="hljs-keyword">TO</span> <span class="hljs-string">'utf8'</span>;
<span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">ROLE</span> myuser <span class="hljs-keyword">SET</span> default_transaction_isolation <span class="hljs-keyword">TO</span> <span class="hljs-string">'read committed'</span>;
<span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">ROLE</span> myuser <span class="hljs-keyword">SET</span> timezone <span class="hljs-keyword">TO</span> <span class="hljs-string">'UTC'</span>;
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">ALL</span> <span class="hljs-keyword">PRIVILEGES</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">DATABASE</span> mydatabase <span class="hljs-keyword">TO</span> myuser;
</code></pre>
<p>This sets up a database and user with the right permissions. Replace <code>mydatabase</code>, <code>myuser</code>, and <code>mypassword</code> with whatever values you prefer.</p>
<h3 id="heading-step-5-update-django-settings-to-use-postgresql">Step 5: Update Django Settings to Use PostgreSQL</h3>
<p>Now it’s time to tell Django to use your new PostgreSQL database.</p>
<p>Open <code>myproject/settings.py</code> and look for the <code>DATABASES</code> setting. Replace the default <code>sqlite3</code> section with this:</p>
<pre><code class="lang-python">DATABASES = {
    <span class="hljs-string">'default'</span>: {
        <span class="hljs-string">'ENGINE'</span>: <span class="hljs-string">'django.db.backends.postgresql'</span>,
        <span class="hljs-string">'NAME'</span>: <span class="hljs-string">'mydatabase'</span>,
        <span class="hljs-string">'USER'</span>: <span class="hljs-string">'myuser'</span>,
        <span class="hljs-string">'PASSWORD'</span>: <span class="hljs-string">'mypassword'</span>,
        <span class="hljs-string">'HOST'</span>: <span class="hljs-string">'localhost'</span>,
        <span class="hljs-string">'PORT'</span>: <span class="hljs-string">'5432'</span>,
    }
}
</code></pre>
<p>This tells Django to:</p>
<ul>
<li><p>Use PostgreSQL (<code>django.db.backends.postgresql</code>)</p>
</li>
<li><p>Connect to a local database called <code>mydatabase</code></p>
</li>
<li><p>Use the user and password you set up earlier</p>
</li>
</ul>
<h3 id="heading-step-6-run-migrations">Step 6: Run Migrations</h3>
<p>Now that everything’s connected, let’s create the database tables Django needs:</p>
<pre><code class="lang-bash">python manage.py migrate
</code></pre>
<p>If everything’s working, you’ll see Django creating tables in PostgreSQL. No errors? You’re good to go!</p>
<h3 id="heading-step-7-test-the-connection">Step 7: Test the Connection</h3>
<p>Let’s test it all by creating a superuser (admin account):</p>
<pre><code class="lang-bash">python manage.py createsuperuser
</code></pre>
<p>Follow the prompts, then run:</p>
<pre><code class="lang-bash">python manage.py runserver
</code></pre>
<p>Open your browser and go to <code>http://127.0.0.1:8000/admin</code>. Log in with your superuser account. You’ll be in the Django admin dashboard – and yes, all of this is backed by PostgreSQL now!</p>
<h2 id="heading-common-issues-and-fixes">Common Issues (and Fixes)</h2>
<p>Here are a few things that might trip you up:</p>
<ul>
<li><p><strong>Error:</strong> <code>psycopg2.errors.UndefinedTable</code>: This usually means you forgot to run <code>migrate</code>.</p>
</li>
<li><p><strong>Can’t connect to database:</strong> Double-check your database name, user, and password. Make sure PostgreSQL is running.</p>
</li>
<li><p><strong>Role doesn’t exist:</strong> You might’ve forgotten to create the user in PostgreSQL, or you used the wrong name in <code>settings.py</code>.</p>
</li>
</ul>
<h2 id="heading-optional-use-dj-database-url-for-better-settings">Optional: Use <code>dj-database-url</code> for Better Settings</h2>
<p>If you’re planning to deploy your app later (especially on services like Heroku), managing your database settings through a URL is cleaner.</p>
<p>Install the helper package:</p>
<pre><code class="lang-bash">pip install dj-database-url
</code></pre>
<p>Then in your <code>settings.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> dj_database_url

DATABASES = {
    <span class="hljs-string">'default'</span>: dj_database_url.config(default=<span class="hljs-string">'postgres://myuser:mypassword@localhost:5432/mydatabase'</span>)
}
</code></pre>
<p>This lets you control your database config from an environment variable, which is more secure and flexible.</p>
<h2 id="heading-frequently-asked-questions">Frequently Asked Questions</h2>
<h3 id="heading-is-postgresql-better-than-sqlite-for-django"><strong>Is PostgreSQL better than SQLite for Django?</strong></h3>
<p>For learning or small projects, SQLite is fine. But for serious apps with lots of users or advanced queries, PostgreSQL is much better.</p>
<h3 id="heading-do-i-need-to-install-postgresql-on-my-production-server"><strong>Do I need to install PostgreSQL on my production server?</strong></h3>
<p>Yes – unless you’re using a hosted PostgreSQL solution like <a target="_blank" href="https://aws.amazon.com/rds/postgresql/">Amazon RDS</a>, <a target="_blank" href="https://devcenter.heroku.com/articles/heroku-postgresql">Heroku Postgres</a>, or <a target="_blank" href="https://supabase.com/">Supabase</a>.</p>
<h3 id="heading-is-psycopg2-binary-safe-to-use-in-production"><strong>Is psycopg2-binary safe to use in production?</strong></h3>
<p>Yes, for most cases. But some recommend switching to the non-binary version (<code>psycopg2</code>) in production for better control.</p>
<h3 id="heading-can-i-switch-from-sqlite-to-postgresql-mid-project"><strong>Can I switch from SQLite to PostgreSQL mid-project?</strong></h3>
<p>Yes, but you’ll need to migrate your data. Tools like <a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/django-admin/#dumpdata">Django’s <code>dumpdata</code> and <code>loaddata</code></a> can help with that.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Using PostgreSQL in Django is a great step forward when you want to build real, production-ready apps.</p>
<p>The setup is pretty straightforward once you know the steps, and the performance gains are worth it.</p>
<p>Come say hey on <a target="_blank" href="http://X.com/_udemezue">X.com/_udemezue</a> and check out my <a target="_blank" href="https://Tchelete.com">blog</a> while you're at it!</p>
<h3 id="heading-further-resources">Further Resources</h3>
<p>If you want to dive deeper, here are a few links I recommend:</p>
<ul>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/settings/#databases">Django Database Settings Docs</a></p>
</li>
<li><p><a target="_blank" href="https://www.postgresql.org/docs/">PostgreSQL Official Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://realpython.com/django-setup/#databases">Using PostgreSQL with Django (Real Python)</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Export Your Database in Django ]]>
                </title>
                <description>
                    <![CDATA[ When you're working on a Django project – whether it's a small side project or a growing web app – there comes a point where you need to export your database. Maybe you’re switching hosting providers. Maybe you're backing things up or sharing data wi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-export-your-database-in-django/</link>
                <guid isPermaLink="false">680663026f6aa321e86950fd</guid>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Mon, 21 Apr 2025 15:23:46 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745248996492/6d3f5665-3329-4894-9f99-3ba257867e0d.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you're working on a Django project – whether it's a small side project or a growing web app – there comes a point where you need to export your database.</p>
<p>Maybe you’re switching hosting providers. Maybe you're backing things up or sharing data with someone. Or maybe you just want to peek at your data in a different format.</p>
<p>Exporting a database sounds technical (and yeah, it kind of is), but it doesn’t have to be hard. Django gives you built-in tools that make the process much easier than most people expect.</p>
<p>I’ve worked with Django for a while now, and I’ve helped developers, from beginners to pros, deal with database exports.</p>
<p>In this tutorial, I’m going to walk you through all the ways you can export your database in Django.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-would-you-want-to-export-your-database">Why Would You Want To Export Your Database?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-first-things-first-know-your-database">First Things First: Know Your Database</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-method-1-use-djangos-dumpdata-command">Method 1: Use Django’s dumpdata Command</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-quick-tip-about-fixtures">A Quick Tip About Fixtures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-method-2-use-your-databases-tools">Method 2: Use Your Database’s Tools</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-method-3-export-to-csv-for-excel-or-google-sheets">Method 3: Export to CSV for Excel or Google Sheets</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-method-4-use-django-admin-actions">Method 4: Use Django Admin Actions</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-faqs">FAQs</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-can-i-export-data-in-xml-format-instead-of-json">Can I export data in XML format instead of JSON?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-whats-the-best-format-for-backups">What’s the best format for backups?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-i-automate-backups">Can I automate backups?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-further-reading">Further Reading</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-why-would-you-want-to-export-your-database">Why Would You Want To Export Your Database?</h2>
<p>There are a bunch of reasons you might want to export your Django database:</p>
<ul>
<li><p><strong>Backup</strong>: Before making big changes, it's smart to save a copy.</p>
</li>
<li><p><strong>Migration</strong>: Moving to another server or switching from SQLite to PostgreSQL.</p>
</li>
<li><p><strong>Sharing data</strong>: Giving a snapshot of the data to teammates or analysts.</p>
</li>
<li><p><strong>Testing</strong>: Populating a test or staging environment with real data.</p>
</li>
<li><p><strong>Compliance</strong>: Legal or policy reasons for storing data outside your app.</p>
</li>
</ul>
<p>The good news? Django has solid tools to help you do all this quickly and cleanly.</p>
<h2 id="heading-first-things-first-know-your-database">First Things First: Know Your Database</h2>
<p>Django supports several types of databases: SQLite (the default), PostgreSQL, MySQL, and more. Depending on what you’re using, your export process might look a little different.</p>
<p>But for most common cases, especially if you’re using SQLite or PostgreSQL, the methods I’m about to show you will work great.</p>
<h3 id="heading-method-1-use-djangos-dumpdata-command">Method 1: Use Django’s <code>dumpdata</code> Command</h3>
<p>This is the easiest and most common way to export your data.</p>
<h4 id="heading-step-by-step">Step-by-step:</h4>
<ol>
<li><p>Open your terminal.</p>
</li>
<li><p>Navigate to your Django project folder.</p>
</li>
<li><p>Run the following command:</p>
</li>
</ol>
<pre><code class="lang-bash">python manage.py dumpdata &gt; db.json
</code></pre>
<p>That’s it. You’ve just exported all your data into a JSON file called <code>db.json</code>.</p>
<h4 id="heading-whats-happening-here">What’s happening here?</h4>
<ul>
<li><p><code>dumpdata</code> is a Django management command that goes through your database and exports the data from all the models.</p>
</li>
<li><p>The <code>&gt;</code> the symbol means "send the output into a file" instead of printing it on the screen.</p>
</li>
</ul>
<h4 id="heading-want-to-export-just-one-app">Want to export just one app?</h4>
<p>You can be more specific:</p>
<pre><code class="lang-bash">python manage.py dumpdata myapp &gt; myapp_data.json
</code></pre>
<p>Or even one model:</p>
<pre><code class="lang-bash">python manage.py dumpdata myapp.MyModel &gt; model_data.json
</code></pre>
<p>This is useful if your database is big and you only need a slice of it.</p>
<h4 id="heading-a-quick-tip-about-fixtures">A Quick Tip About Fixtures</h4>
<p>The file you just created (<code>db.json</code>) is called a <em>fixture</em> in Django. You can use it to load data into another project using:</p>
<pre><code class="lang-bash">python manage.py loaddata db.json
</code></pre>
<p>So yeah, <code>dumpdata</code> + <code>loaddata</code> is a super handy combo for moving data around.</p>
<h3 id="heading-method-2-use-your-databases-tools">Method 2: Use Your Database’s Tools</h3>
<p>Depending on what database you're using, you can also use tools that work outside of Django.</p>
<h4 id="heading-for-sqlite-djangos-default">For SQLite (Django’s default)</h4>
<p>Your database is just a file, usually named <code>db.sqlite3</code>.</p>
<p>You can copy it like any other file:</p>
<pre><code class="lang-bash">cp db.sqlite3 db_backup.sqlite3
</code></pre>
<p>If you want to export the data as SQL statements, you can use the <code>sqlite3</code> command-line tool:</p>
<pre><code class="lang-bash">sqlite3 db.sqlite3 .dump &gt; db_dump.sql
</code></pre>
<p>This creates a file with all the SQL commands needed to recreate your database. Pretty handy for backups.</p>
<h4 id="heading-for-postgresql">For PostgreSQL</h4>
<p>You’ll need access to <code>pg_dump</code>, which is PostgreSQL's built-in export tool.</p>
<p>Here’s an example:</p>
<pre><code class="lang-bash">pg_dump -U your_username your_database &gt; backup.sql
</code></pre>
<p>You might need to enter your password, depending on how your database is set up.</p>
<p>You can <a target="_blank" href="https://www.postgresql.org/docs/current/app-pgdump.html">find more info on <code>pg_dump</code> here</a>.</p>
<h3 id="heading-method-3-export-to-csv-for-excel-or-google-sheets">Method 3: Export to CSV for Excel or Google Sheets</h3>
<p>If you want your data in a spreadsheet, you can export it to CSV format.</p>
<p>Django doesn’t have a built-in command for this, but you can write a simple script.</p>
<p>Here’s an example that exports all entries from a model:</p>
<h4 id="heading-example">Example:</h4>
<p>Let’s say you have a model like this:</p>
<pre><code class="lang-python"><span class="hljs-comment"># models.py</span>
<span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
    title = models.CharField(max_length=<span class="hljs-number">200</span>)
    author = models.CharField(max_length=<span class="hljs-number">100</span>)
</code></pre>
<p>To export it to CSV:</p>
<pre><code class="lang-python"><span class="hljs-comment"># export_books.py</span>
<span class="hljs-keyword">import</span> csv
<span class="hljs-keyword">from</span> myapp.models <span class="hljs-keyword">import</span> Book

<span class="hljs-keyword">with</span> open(<span class="hljs-string">'books.csv'</span>, <span class="hljs-string">'w'</span>, newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> file:
    writer = csv.writer(file)
    writer.writerow([<span class="hljs-string">'Title'</span>, <span class="hljs-string">'Author'</span>])

    <span class="hljs-keyword">for</span> book <span class="hljs-keyword">in</span> Book.objects.all():
        writer.writerow([book.title, book.author])
</code></pre>
<p>Run this script with Django’s shell:</p>
<pre><code class="lang-bash">python manage.py shell &lt; export_books.py
</code></pre>
<p>Now you have a <code>books.csv</code> file you can open in Excel or Google Sheets.</p>
<h3 id="heading-method-4-use-django-admin-actions">Method 4: Use Django Admin Actions</h3>
<p>If your model is registered in the Django admin, you can create a custom admin action that lets you export data directly from the interface.</p>
<p>Here’s a quick example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># admin.py</span>
<span class="hljs-keyword">import</span> csv
<span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> HttpResponse
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Book

<span class="hljs-meta">@admin.action(description='Export selected books to CSV')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">export_to_csv</span>(<span class="hljs-params">modeladmin, request, queryset</span>):</span>
    response = HttpResponse(content_type=<span class="hljs-string">'text/csv'</span>)
    response[<span class="hljs-string">'Content-Disposition'</span>] = <span class="hljs-string">'attachment; filename=books.csv'</span>
    writer = csv.writer(response)
    writer.writerow([<span class="hljs-string">'Title'</span>, <span class="hljs-string">'Author'</span>])

    <span class="hljs-keyword">for</span> book <span class="hljs-keyword">in</span> queryset:
        writer.writerow([book.title, book.author])

    <span class="hljs-keyword">return</span> response

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BookAdmin</span>(<span class="hljs-params">admin.ModelAdmin</span>):</span>
    actions = [export_to_csv]

admin.site.register(Book, BookAdmin)
</code></pre>
<p>Now you can select rows in the Django admin and export them. Easy and user-friendly.</p>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-can-i-export-data-in-xml-format-instead-of-json"><strong>Can I export data in XML format instead of JSON?</strong></h3>
<p>Yes! Just add the <code>--format</code> option:</p>
<pre><code class="lang-bash">python manage.py dumpdata --format=xml &gt; db.xml
</code></pre>
<h3 id="heading-whats-the-best-format-for-backups"><strong>What’s the best format for backups?</strong></h3>
<p>JSON is great for Django-to-Django transfers. SQL (using <code>pg_dump</code> or <code>sqlite3 .dump</code>) is better for full database backups.</p>
<h3 id="heading-can-i-automate-backups"><strong>Can I automate backups?</strong></h3>
<p>Totally. Set up a cron job or a simple Python script that runs <code>dumpdata</code> on a schedule and saves the file to cloud storage.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Exporting your database in Django doesn’t have to be a big deal. With built-in commands like <code>dumpdata</code>, or even custom scripts for CSV exports, you can handle data safely and with confidence. And once you get the hang of it, you’ll probably use these tools all the time.</p>
<h3 id="heading-further-reading">Further Reading</h3>
<ul>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/django-admin/#dumpdata">Django dumpdata documentation</a></p>
</li>
<li><p><a target="_blank" href="https://www.postgresql.org/docs/current/app-pgdump.html">PostgreSQL pg_dump</a></p>
</li>
<li><p><a target="_blank" href="https://www.sqlite.org/backup.html">Backing up SQLite databases</a></p>
</li>
<li><p><a target="_blank" href="https://docs.djangoproject.com/en/stable/ref/django-admin/#loaddata">Django loaddata command</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Dockerize Your Django Project ]]>
                </title>
                <description>
                    <![CDATA[ If you're working on a Django project and you want to make your life easier – especially when it comes to running your app across different environments – Docker is your new best friend. Docker makes it possible to package your Django app, along with... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-dockerize-your-django-project/</link>
                <guid isPermaLink="false">68027fe54ea28168254d68b0</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Docker ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Fri, 18 Apr 2025 16:37:57 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744994272728/248cef70-5f8e-46fd-a640-66852ffda7d2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're working on a Django project and you want to make your life easier – especially when it comes to running your app across different environments – Docker is your new best friend.</p>
<p>Docker makes it possible to package your Django app, along with all its dependencies, into something called a “container.”</p>
<p>That way, it runs the same on your computer, your teammate’s computer, a testing server, or even in production.</p>
<p>When I first started using Docker, it felt a little overwhelming. But after setting it up for a few Django apps, it all clicked.</p>
<p>The good news? I’m going to walk you through it, step by step, in a way that’s easy to follow, even if you’re brand new to Docker.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-youll-need">What You’ll Need</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-dockerize-your-django-project">How to Dockerize Your Django Project</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-step-1-start-a-django-project">Step 1: Start a Django Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-create-a-dockerfile">Step 2: Create a Dockerfile</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-add-a-requirementstxt">Step 3: Add a requirements.txt</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-4-create-docker-composeyml">Step 4: Create docker-compose.yml</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-5-run-it">Step 5: Run It!</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-common-issues">Common Issues</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-port-already-in-use">Port Already in Use?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-database-not-working">Database Not Working?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-faqs">FAQs</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-do-i-need-docker-for-development">Do I need Docker for development?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-i-run-migrations-inside-docker">Can I run migrations inside Docker?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-do-i-stop-everything">How do I stop everything?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-extra-tip-use-dockerignore">Extra Tip: Use .dockerignore</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-youve-built">What You’ve Built</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-want-to-go-deeper">Want to Go Deeper?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-further-reading">Further Reading</a></p>
</li>
</ol>
<h2 id="heading-what-youll-need">What You’ll Need</h2>
<p>Before we begin, make sure you’ve got a few things installed:</p>
<ul>
<li><p><strong>Python 3</strong> (any version that Django supports)</p>
</li>
<li><p><strong>Django</strong> (of course)</p>
</li>
<li><p><strong>Docker and Docker Compose</strong><br>  👉 <a target="_blank" href="https://docs.docker.com/engine/install/">Install Docker</a><br>  👉 <a target="_blank" href="https://docs.docker.com/compose/install/linux/">Install Docker Compose</a></p>
</li>
</ul>
<p>You don’t need to be an expert in Docker. I’ll explain what each part does as we build it together.</p>
<h2 id="heading-how-to-dockerize-your-django-project">How to Dockerize Your Django Project</h2>
<h3 id="heading-step-1-start-a-django-project">Step 1: Start a Django Project</h3>
<p>If you already have a Django project, you can skip this part.</p>
<p>Otherwise, open your terminal and run:</p>
<pre><code class="lang-bash">django-admin startproject myproject
<span class="hljs-built_in">cd</span> myproject
</code></pre>
<p>This will create a new Django project called <code>myproject</code>. You’ll see a structure like this:</p>
<pre><code class="lang-markdown">myproject/
├── manage.py
└── myproject/
<span class="hljs-code">    ├── __init__.py
    ├── asgi.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py</span>
</code></pre>
<p>Let’s say this is your app that you want to run inside Docker.</p>
<h3 id="heading-step-2-create-a-dockerfile">Step 2: Create a Dockerfile</h3>
<p>In the root of your project (same folder as <code>manage.py</code>), create a file called <code>Dockerfile</code>. No file extension –just <code>Dockerfile</code>.</p>
<p>Here’s what goes inside:</p>
<pre><code class="lang-dockerfile"><span class="hljs-comment"># Use the official Python image</span>
<span class="hljs-keyword">FROM</span> python:<span class="hljs-number">3.10</span>-slim

<span class="hljs-comment"># Set environment variables</span>
<span class="hljs-keyword">ENV</span> PYTHONDONTWRITEBYTECODE=<span class="hljs-number">1</span>
<span class="hljs-keyword">ENV</span> PYTHONUNBUFFERED=<span class="hljs-number">1</span>

<span class="hljs-comment"># Set the working directory in the container</span>
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>

<span class="hljs-comment"># Install dependencies</span>
<span class="hljs-keyword">COPY</span><span class="bash"> requirements.txt /app/</span>
<span class="hljs-keyword">RUN</span><span class="bash"> pip install --upgrade pip &amp;&amp; pip install -r requirements.txt</span>

<span class="hljs-comment"># Copy the rest of the code</span>
<span class="hljs-keyword">COPY</span><span class="bash"> . /app/</span>
</code></pre>
<p>Let me break that down:</p>
<ul>
<li><p><code>FROM python:3.10-slim</code>: This tells Docker to use a lightweight version of Python 3.10.</p>
</li>
<li><p><code>ENV</code>: These just help with cleaner logs and better performance.</p>
</li>
<li><p><code>WORKDIR /app</code>: This sets the default working directory inside the container.</p>
</li>
<li><p><code>COPY</code> and <code>RUN</code>: These lines copy your code into the container and install your Python packages.</p>
</li>
</ul>
<h3 id="heading-step-3-add-a-requirementstxt">Step 3: Add a <code>requirements.txt</code></h3>
<p>You’ll need a file listing your Python packages.</p>
<p>Create a file called <code>requirements.txt</code> in the root folder and add:</p>
<pre><code class="lang-plaintext">Django&gt;=4.0,&lt;5.0
</code></pre>
<p>You can add more later if your project grows. For now, that’s enough.</p>
<p>To generate a full list of dependencies from your local virtual environment, run:</p>
<pre><code class="lang-bash">pip freeze &gt; requirements.txt
</code></pre>
<h3 id="heading-step-4-create-docker-composeyml">Step 4: Create <code>docker-compose.yml</code></h3>
<p>Now let’s create the file that tells Docker how to run everything together.</p>
<p>In your root folder, create <code>docker-compose.yml</code>:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3.9'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">build:</span> <span class="hljs-string">.</span>
    <span class="hljs-attr">command:</span> <span class="hljs-string">python</span> <span class="hljs-string">manage.py</span> <span class="hljs-string">runserver</span> <span class="hljs-number">0.0</span><span class="hljs-number">.0</span><span class="hljs-number">.0</span><span class="hljs-string">:8000</span>
    <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">.:/app</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"8000:8000"</span>
</code></pre>
<p>Let’s go line-by-line:</p>
<ul>
<li><p><code>build: .</code>: This tells Docker to use the <code>Dockerfile</code> in the current folder.</p>
</li>
<li><p><code>command</code>: This runs Django’s development server inside the container.</p>
</li>
<li><p><code>volumes</code>: This mounts your code into the container so changes are reflected live.</p>
</li>
<li><p><code>ports</code>: This maps port 8000 inside Docker to port 8000 on your machine.</p>
</li>
</ul>
<p>So if you go to <code>http://localhost:8000</code>, you’ll see your app.</p>
<h3 id="heading-step-5-run-it">Step 5: Run It!</h3>
<p>Now the fun part. From your terminal, run:</p>
<pre><code class="lang-bash">docker-compose up --build
</code></pre>
<p>This tells Docker to:</p>
<ul>
<li><p>Build the container</p>
</li>
<li><p>Install dependencies</p>
</li>
<li><p>Run the Django server</p>
</li>
</ul>
<p>If everything goes well, you’ll see logs from the Django server, and you can open your browser and go to <code>http://localhost:8000</code>.</p>
<p>You should see the Django welcome screen.</p>
<h2 id="heading-common-issues">Common Issues</h2>
<h3 id="heading-port-already-in-use">Port Already in Use?</h3>
<p>If port 8000 is busy, change this line in <code>docker-compose.yml</code>:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">ports:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">"8001:8000"</span>
</code></pre>
<p>Then go to <code>http://localhost:8001</code>.</p>
<h3 id="heading-database-not-working">Database Not Working?</h3>
<p>If you need a database (like PostgreSQL), you can add another service to <code>docker-compose.yml</code>. Here's an example with PostgreSQL:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">services:</span>
  <span class="hljs-attr">db:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">postgres</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-attr">POSTGRES_DB:</span> <span class="hljs-string">mydb</span>
      <span class="hljs-attr">POSTGRES_USER:</span> <span class="hljs-string">user</span>
      <span class="hljs-attr">POSTGRES_PASSWORD:</span> <span class="hljs-string">password</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">build:</span> <span class="hljs-string">.</span>
    <span class="hljs-attr">command:</span> <span class="hljs-string">python</span> <span class="hljs-string">manage.py</span> <span class="hljs-string">runserver</span> <span class="hljs-number">0.0</span><span class="hljs-number">.0</span><span class="hljs-number">.0</span><span class="hljs-string">:8000</span>
    <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">.:/app</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"8000:8000"</span>
    <span class="hljs-attr">depends_on:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">db</span>
</code></pre>
<p>Then, update your <code>settings.py</code> in Django to use that database.</p>
<h2 id="heading-faqs">FAQs</h2>
<h3 id="heading-do-i-need-docker-for-development"><strong>Do I need Docker for development?</strong></h3>
<p>No, but it helps keep your environment clean and consistent. If it works in Docker, it'll work anywhere.</p>
<h3 id="heading-can-i-run-migrations-inside-docker"><strong>Can I run migrations inside Docker?</strong></h3>
<p>Yes! Just run:</p>
<pre><code class="lang-bash">docker-compose run web python manage.py migrate
</code></pre>
<h3 id="heading-how-do-i-stop-everything"><strong>How do I stop everything?</strong></h3>
<p>Press <code>Ctrl+C</code> to stop the running server, and if you want to remove containers:</p>
<pre><code class="lang-bash">docker-compose down
</code></pre>
<h2 id="heading-extra-tip-use-dockerignore">Extra Tip: Use <code>.dockerignore</code></h2>
<p>Just like <code>.gitignore</code>, you can create a <code>.dockerignore</code> file to avoid copying unnecessary files into the Docker container. Here’s a simple one:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">__pycache__</span>
<span class="hljs-regexp">*.pyc</span>
<span class="hljs-regexp">*.pyo</span>
<span class="hljs-regexp">*.pyd</span>
.env
.git
</code></pre>
<h2 id="heading-what-youve-built">What You’ve Built</h2>
<p>By now, you’ve:</p>
<ul>
<li><p>Created a Django project</p>
</li>
<li><p>Built a Docker container for it</p>
</li>
<li><p>Set up <code>docker-compose</code> to run everything</p>
</li>
<li><p>Learned how to manage it all easily</p>
</li>
</ul>
<p>Once you’re comfortable, you can expand this setup with static files, NGINX, Gunicorn, or even production-ready Docker builds.</p>
<h2 id="heading-want-to-go-deeper">Want to Go Deeper?</h2>
<p>If this feels like a lot, that’s ok. It takes a little practice, but once you’ve done it a few times, Docker becomes second nature.</p>
<p>You’ll spend less time debugging setup issues and more time coding your app.</p>
<h3 id="heading-further-reading">Further Reading</h3>
<ul>
<li><p><a target="_blank" href="https://docs.docker.com/">Docker Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://docs.djangoproject.com/">Django Official Docs</a></p>
</li>
<li><p><a target="_blank" href="https://docs.docker.com/reference/compose-file/">Compose File Reference</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Celery in Django ]]>
                </title>
                <description>
                    <![CDATA[ You’ve probably noticed that some tasks in your Django app seem to take a long time. For example, maybe sending confirmation emails, resizing images, or processing large data files slows things down. The good news? You don’t have to sit around waitin... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-celery-in-django/</link>
                <guid isPermaLink="false">68027fc44d4422c6f797b252</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ celery ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Udemezue John ]]>
                </dc:creator>
                <pubDate>Fri, 18 Apr 2025 16:37:24 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744994231247/63228755-1929-4474-9930-15f8ff1a5631.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You’ve probably noticed that some tasks in your Django app seem to take a long time. For example, maybe sending confirmation emails, resizing images, or processing large data files slows things down.</p>
<p>The good news? You don’t have to sit around waiting. You can hand those tasks off to something else and let your app keep doing its thing. That "something else" is Celery.</p>
<p>Celery lets you run time-consuming tasks in the background while your app stays fast. And if you're using Django, it's actually not that hard to plug it in – once you understand how the pieces work together.</p>
<p>In this guide, I’ll walk you through what Celery is, why it’s useful, and exactly how to set it up with Django step by step.</p>
<h2 id="heading-table-of-contents">Table Of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-celery-and-why-should-you-use-it-in-django">What Is Celery and Why Should You Use It in Django?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-celery-works-the-simple-version">How Celery Works (The Simple Version)</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-use-celery-in-django">How to Use Celery in Django</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-install-the-right-packages">1. Install the right packages</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-create-a-celerypy-file-in-your-project-folder">2. Create a</a> <a target="_blank" href="http://celery.py">celery.py</a> <a class="post-section-overview" href="#heading-2-create-a-celerypy-file-in-your-project-folder">file in your project folder</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-add-celery-to-initpy">3. Add Celery to</a> <a target="_blank" href="http://init.py"><strong>init</strong>.py</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-set-the-broker-url-in-your-settings">4. Set the broker URL in your settings</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-write-your-first-task">5. Write your first task</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-call-the-task-from-your-views">6. Call the task from your views</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-7-run-the-celery-worker">7. Run the Celery worker</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-optional-using-django-admin-to-monitor-tasks">Optional: Using Django Admin to Monitor Tasks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-faq">FAQ</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-happens-if-redis-goes-down">What happens if Redis goes down?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-i-retry-failed-tasks">Can I retry failed tasks?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-is-celery-the-only-option">Is Celery the only option?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-it-up">Wrapping It Up</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-further-reading-and-resources">Further Reading and Resources</a></p>
</li>
</ol>
<h2 id="heading-what-is-celery-and-why-should-you-use-it-in-django">What Is Celery and Why Should You Use It in Django?</h2>
<p>Imagine you’re running an online shop. Someone places an order. You want to:</p>
<ul>
<li><p>Save the order to the database</p>
</li>
<li><p>Send them an invoice by email</p>
</li>
<li><p>Notify your warehouse</p>
</li>
<li><p>Maybe even start printing a shipping label</p>
</li>
</ul>
<p>If your app tries to do all this at once, your user is going to be stuck staring at a loading screen. Instead, what if you only saved the order right away – and passed the rest to Celery to handle in the background?</p>
<p>That’s exactly what Celery does.</p>
<p>It’s a task queue — which just means it runs things later, so your main app doesn’t have to wait. It’s especially helpful for:</p>
<ul>
<li><p>Sending emails</p>
</li>
<li><p>Data imports/exports</p>
</li>
<li><p>Running machine learning models</p>
</li>
<li><p>Scraping data</p>
</li>
<li><p>Generating reports</p>
</li>
</ul>
<p>And yeah, it works really well with Django.</p>
<h2 id="heading-how-celery-works-the-simple-version">How Celery Works (The Simple Version)</h2>
<p>Celery is made up of a few parts:</p>
<ol>
<li><p><strong>Task producer (your Django app)</strong> – This is where you call a task.</p>
</li>
<li><p><strong>Broker (usually Redis)</strong> – This is the middleman. It takes the task and holds it until a worker can grab it.</p>
</li>
<li><p><strong>Worker</strong> – This is Celery’s background process that grabs tasks from the broker and runs them.</p>
</li>
</ol>
<p>Here’s the flow:</p>
<pre><code class="lang-plaintext">Django app → Redis → Celery Worker → Done ✅
</code></pre>
<p>Now let’s actually set this up.</p>
<h2 id="heading-how-to-use-celery-in-django">How to Use Celery in Django</h2>
<h3 id="heading-1-install-the-right-packages">1. Install the right packages</h3>
<p>You’ll need <code>celery</code> and a message broker. Redis is a popular choice.</p>
<pre><code class="lang-bash">pip install celery redis
</code></pre>
<p>Also make sure you have Redis running. You can install it locally via Homebrew (<code>brew install redis</code>) or use a Docker container.</p>
<p>If you’re using Docker:</p>
<pre><code class="lang-bash">docker run -p 6379:6379 redis
</code></pre>
<h3 id="heading-2-create-a-celerypy-file-in-your-project-folder">2. Create a <code>celery.py</code> file in your project folder</h3>
<p>Let’s say your Django project is called <code>myproject</code>. Inside that same folder (where <code>settings.py</code> is), create a file called <code>celery.py</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># myproject/celery.py</span>
<span class="hljs-keyword">import</span> os
<span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

os.environ.setdefault(<span class="hljs-string">"DJANGO_SETTINGS_MODULE"</span>, <span class="hljs-string">"myproject.settings"</span>)

app = Celery(<span class="hljs-string">"myproject"</span>)

app.config_from_object(<span class="hljs-string">"django.conf:settings"</span>, namespace=<span class="hljs-string">"CELERY"</span>)
app.autodiscover_tasks()
</code></pre>
<p>Here’s what’s happening:</p>
<ul>
<li><p><code>os.environ...</code> sets up Django’s settings.</p>
</li>
<li><p><code>Celery("myproject")</code> creates a new Celery app with your project name.</p>
</li>
<li><p><code>app.config_from_object(...)</code> tells Celery to read config from Django’s settings file.</p>
</li>
<li><p><code>autodiscover_tasks()</code> tells Celery to find tasks in your Django apps automatically.</p>
</li>
</ul>
<h3 id="heading-3-add-celery-to-initpy">3. Add Celery to <code>__init__.py</code></h3>
<p>Still in your <code>myproject/</code> folder, open <code>__init__.py</code> and add:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> .celery <span class="hljs-keyword">import</span> app <span class="hljs-keyword">as</span> celery_app

__all__ = (<span class="hljs-string">"celery_app"</span>,)
</code></pre>
<p>This makes sure Celery starts with Django.</p>
<h3 id="heading-4-set-the-broker-url-in-your-settings">4. Set the broker URL in your settings</h3>
<p>Open <code>settings.py</code> and add:</p>
<pre><code class="lang-python">CELERY_BROKER_URL = <span class="hljs-string">'redis://localhost:6379/0'</span>
</code></pre>
<p>This tells Celery to use Redis as the broker.</p>
<h3 id="heading-5-write-your-first-task">5. Write your first task</h3>
<p>Go to one of your Django apps (say you’ve got an app called <code>shop</code>), and create a file called <code>tasks.py</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># shop/tasks.py</span>
<span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> shared_task

<span class="hljs-meta">@shared_task</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_invoice_email</span>(<span class="hljs-params">order_id</span>):</span>
    <span class="hljs-comment"># Imagine this sends an email</span>
    print(<span class="hljs-string">f"Sending invoice email for order <span class="hljs-subst">{order_id}</span>"</span>)
</code></pre>
<p>The <code>@shared_task</code> decorator tells Celery this is a background task.</p>
<h3 id="heading-6-call-the-task-from-your-views">6. Call the task from your views</h3>
<p>Here’s how you’d use it in a Django view:</p>
<pre><code class="lang-python"><span class="hljs-comment"># shop/views.py</span>

<span class="hljs-keyword">from</span> .tasks <span class="hljs-keyword">import</span> send_invoice_email
<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">place_order</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-comment"># pretend this saves an order</span>
    order_id = <span class="hljs-number">1234</span>  <span class="hljs-comment"># this would come from your model</span>

    <span class="hljs-comment"># run the task in the background</span>
    send_invoice_email.delay(order_id)

    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">"order_complete.html"</span>)
</code></pre>
<p>Notice the <code>.delay()</code> – this is what sends the task to Celery.</p>
<h3 id="heading-7-run-the-celery-worker">7. Run the Celery worker</h3>
<p>Now open a terminal and start the worker:</p>
<pre><code class="lang-bash">celery -A myproject worker --loglevel=info
</code></pre>
<p>You should see the worker start and wait for tasks. When you place an order, it’ll print something like:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">Sending</span> <span class="hljs-selector-tag">invoice</span> <span class="hljs-selector-tag">email</span> <span class="hljs-selector-tag">for</span> <span class="hljs-selector-tag">order</span> 1234
</code></pre>
<h2 id="heading-optional-using-django-admin-to-monitor-tasks">Optional: Using Django Admin to Monitor Tasks</h2>
<p>If you want to monitor task status in the admin, you can use <a target="_blank" href="https://github.com/celery/django-celery-results">django-celery-results</a>.</p>
<pre><code class="lang-bash">pip install django-celery-results
</code></pre>
<p>Then update your <code>settings.py</code>:</p>
<pre><code class="lang-python">INSTALLED_APPS += [<span class="hljs-string">"django_celery_results"</span>]

CELERY_RESULT_BACKEND = <span class="hljs-string">"django-db"</span>
</code></pre>
<p>Run migrations:</p>
<pre><code class="lang-bash">python manage.py migrate
</code></pre>
<p>Now Celery will save task results in your database, and you can see them in Django admin.</p>
<h2 id="heading-faq">FAQ</h2>
<h3 id="heading-what-happens-if-redis-goes-down"><strong>What happens if Redis goes down?</strong></h3>
<p>Your tasks won’t be sent or picked up. But once Redis comes back, things should resume.</p>
<h3 id="heading-can-i-retry-failed-tasks"><strong>Can I retry failed tasks?</strong></h3>
<p>Yes! Celery supports retries. You can set how many times a task should retry and how often. Example:</p>
<pre><code class="lang-python"><span class="hljs-meta">@shared_task(bind=True, max_retries=3)</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">risky_task</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-keyword">try</span>:
        <span class="hljs-comment"># Do something risky</span>
        <span class="hljs-keyword">pass</span>
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        <span class="hljs-keyword">raise</span> self.retry(exc=e, countdown=<span class="hljs-number">60</span>)
</code></pre>
<h3 id="heading-is-celery-the-only-option"><strong>Is Celery the only option?</strong></h3>
<p>No. There’s also Django Q, Dramatiq, and Huey. But Celery is the most mature and has the biggest community.</p>
<h2 id="heading-wrapping-it-up">Wrapping It Up</h2>
<p>Using Celery in Django doesn’t just speed things up – it also helps improve the experience for your users.</p>
<p>Offloading heavy or slow tasks makes your app feel snappier and more reliable.</p>
<p>Once you get the basics down, you’ll find yourself using it for all kinds of things.</p>
<h3 id="heading-further-reading-and-resources">Further Reading and Resources</h3>
<ul>
<li><p><a target="_blank" href="https://docs.celeryq.dev/en/stable/">Celery Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://redis.io/docs/latest/develop/get-started/">Redis Quickstart</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/celery/django-celery-results">django-celery-results</a></p>
</li>
<li><p><a target="_blank" href="https://realpython.com/asynchronous-tasks-with-django-and-celery/">Asynchronous Tasks in Django (Real Python)</a></p>
</li>
<li><p><a target="_blank" href="https://flower.readthedocs.io/en/latest/">Celery Monitoring with Flower</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
