<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bharath on Medium]]></title>
        <description><![CDATA[Stories by Bharath on Medium]]></description>
        <link>https://medium.com/@bharathofficial05?source=rss-5fa5ae546213------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1NuoBXYaXdpu2BCjamfRZQ.jpeg</url>
            <title>Stories by Bharath on Medium</title>
            <link>https://medium.com/@bharathofficial05?source=rss-5fa5ae546213------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:10:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bharathofficial05/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Getting Started with Django REST Framework -A Beginner’s Guide]]></title>
            <link>https://medium.com/@bharathofficial05/getting-started-with-django-rest-framework-a-beginners-guide-7ec01d5c7c56?source=rss-5fa5ae546213------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ec01d5c7c56</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-admin]]></category>
            <category><![CDATA[django-framework]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 17:59:43 GMT</pubDate>
            <atom:updated>2026-04-28T18:03:23.943Z</atom:updated>
            <content:encoded><![CDATA[<p>No fluff. No theory. Just the stuff that works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VerKUH2StMea8YFvBnzvBg.jpeg" /></figure><p>when I first tried to learn Django REST Framework, I spent like three hours reading docs and still had no idea what a serializer was or why I needed one. Every tutorial either assumed I already knew things I didn’t, or buried me in so much theory that I gave up before writing a single line of code.</p><p>So this is the article I wish someone had handed me back then.</p><p>If you know basic Python and you’ve maybe touched Django once or twice, you’re ready for this. We’re going to build a real API together — one that lists products, creates them, updates them, deletes them — the whole thing. And by the time you’re done, it’ll actually make sense.</p><p>Alright, let’s go.</p><h3>Before You Start — What You’ll Need</h3><p>Nothing fancy, honestly:</p><ul><li>Python 3.8+ on your machine</li><li>A terminal you’re not terrified of</li><li>About an hour</li></ul><p>That’s genuinely it. No prior API experience needed.</p><h3>First Things First — Virtual Environment</h3><p>I know, Everyone says <strong>“set up a virtual environment”</strong> and nobody explains why. Here’s why: without it, all your packages get installed globally on your machine and they start conflicting with each other in weird ways. It’s a headache you don’t want. Just do it once and you’ll thank yourself later.</p><pre>mkdir my_drf_project<br>cd my_drf_project<br>python -m venv venv <br># Create an isolated Python environment named &quot;venv&quot;; <br># &quot;-m&quot; tells Python to run the built-in &quot;venv&quot; module as a script <br># (powerful because it uses Python’s module system instead of external tools,# ensuring consistency across environments)</pre><p>Now activate it:</p><pre># If you&#39;re on Mac or Linux<br>source venv/bin/activate<br><br># If you&#39;re on Windows<br>venv\Scripts\activate</pre><p>You’ll see (venv) pop up in your terminal. That means it&#39;s working. Good.</p><h3>Install the Two Things You Need</h3><p>Simple:</p><pre>pip install django djangorestframework</pre><p>django is the core framework. djangorestframework is what sits on top of it and gives you all the API superpowers. While you&#39;re at it, install Pillow too — it handles image fields and Django quietly needs it sometimes:</p><pre>pip install pillow</pre><p>Now save your dependencies so you (or anyone else) can reinstall them later with one command:</p><pre>pip freeze &gt; requirements.txt</pre><h3>Create the Django Project</h3><p>Here’s where it gets real. Run this:</p><pre>django-admin startproject core .</pre><p>Don’t skip the dot at the end. A lot of people do and then wonder why they have a weird extra nested folder. The dot tells Django to put everything right here in the current folder.</p><p>After this, your project looks like:</p><pre>my_drf_project/<br>│<br>├── core/<br>│   ├── __init__.py<br>│   ├── asgi.py<br>│   ├── settings.py       ← this is your main config file<br>│   ├── urls.py           ← the front door for all your URLs<br>│   └── wsgi.py<br>│<br>├── venv/<br>├── manage.py<br>└── requirements.txt</pre><p>The core folder is basically the control center of your whole project. settings.py is where you configure everything and urls.py is where all incoming requests enter before getting routed to the right place.</p><h3>Tell Django About REST Framework</h3><p>Open up core/settings.py and find INSTALLED_APPS. It&#39;ll already have a bunch of stuff in it — just add rest_framework to the list:</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br><br>     # this is the one you&#39;re adding<br>    &#39;rest_framework&#39;,<br>]</pre><p>Then, somewhere below that, paste this block in:</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: [<br>        &#39;rest_framework.permissions.AllowAny&#39;,<br>    ],<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;rest_framework.authentication.SessionAuthentication&#39;,<br>        &#39;rest_framework.authentication.BasicAuthentication&#39;,<br>    ],<br>    &#39;DEFAULT_PAGINATION_CLASS&#39;: &#39;rest_framework.pagination.PageNumberPagination&#39;,<br>    &#39;PAGE_SIZE&#39;: 10,<br>}</pre><p>What this does: it sets the rules for your whole API in one place. Who’s allowed to access it, how they log in, and whether responses come back paginated. Right now we’re setting permissions to AllowAny, which means no authentication required — that&#39;s fine for development, we&#39;d lock it down before going to production.</p><h3>Create Your First App</h3><p>In Django, a “project” holds everything together, but the actual features live inside “apps.” If you were building Twitter, you might have a tweets app, a users app, a notifications app — each one handles its own thing.</p><p>We’re building a products app:</p><pre>python manage.py startapp products</pre><p>Your folder now has this inside it:</p><pre>products/<br>├── migrations/<br>├── __init__.py<br>├── admin.py<br>├── apps.py<br>├── models.py       ← your database structure goes here<br>├── tests.py<br>└── views.py        ← your API logic goes here</pre><p>Now go back to core/settings.py and register the app you just made:</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;rest_framework&#39;,<br>    &#39;products&#39;,   # ← add this<br>]</pre><p>Django won’t know your app exists until you do this. Forgetting it is one of the most common beginner mistakes, so just make it a habit every time you create an app.</p><h3>Build Your Model</h3><p>A model is just a Python class that becomes a table in your database. Open products/models.py and write this:</p><pre>from django.db import models<br><br>class Product(models.Model):<br>    name = models.CharField(max_length=200)<br>    description = models.TextField(blank=True)<br>    price = models.DecimalField(max_digits=10, decimal_places=2)<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    def __str__(self):<br>        return self.name</pre><p>Each line is a column in your database table. <br>CharField is for short text like a product name. <br>TextField is for longer text like a description. <br>DecimalField handles money properly without floating point weirdness. And auto_now_add=True on the <br>DateTimeField means Django fills in the timestamp automatically when a product gets created — you never have to worry about it.</p><p>Now run two commands to actually create that table in your database:</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>The first one generates a migration file — basically a recipe for the database change. The second one actually runs it. You’ll see something like this:</p><pre>Migrations for &#39;products&#39;:<br>  products/migrations/0001_initial.py<br>    - Create model Product</pre><p>That means it worked.</p><h3>The Serializer — Don’t Skip This Part</h3><p>Okay, this is the thing that trips up almost every beginner. What even is a serializer?</p><p>Here’s the simplest way I can explain it: your API sends and receives <strong><em>JSON</em></strong>. Your Django app works with <strong><em>Python object</em></strong><em>s</em>. A serializer sits in the middle and translates between the two. <strong><em>Python object</em></strong> goes in → <strong><em>JSON </em></strong>comes out. JSON comes in → Python object comes out. It also validates the data along the way so garbage doesn’t end up in your database.</p><p>Create a new file called serializers.py inside the products folder:</p><pre>touch products/serializers.py</pre><p>Open it and write:</p><pre>from rest_framework import serializers<br>from .models import Product<br><br>class ProductSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Product<br>        fields = [&#39;id&#39;, &#39;name&#39;, &#39;description&#39;, &#39;price&#39;, &#39;created_at&#39;]</pre><p>The ModelSerializer figures out all the field types from your model automatically. You just tell it which fields to expose in fields. If you don&#39;t want created_at showing up in API responses, just remove it from the list. That&#39;s how much control you have with barely any code.</p><h3>Write Your Views</h3><p>Views are where the actual logic happens — they receive a request, do something with it, and send back a response.</p><p>Open products/views.py and replace whatever&#39;s in there with this:</p><pre>from rest_framework import generics<br>from .models import Product<br>from .serializers import ProductSerializer<br><br>class ProductListCreateView(generics.ListCreateAPIView):<br>    queryset = Product.objects.all()<br>    serializer_class = ProductSerializer<br><br>class ProductDetailView(generics.RetrieveUpdateDestroyAPIView):<br>    queryset = Product.objects.all()<br>    serializer_class = ProductSerializer</pre><p>I want you to appreciate how short this is. Four lines per view. And yet:</p><p>ProductListCreateView will handle both listing all your products (GET) and creating a new one (POST). DRF figures out which to do based on the HTTP method of the incoming request.</p><p>ProductDetailView will handle fetching one product by its ID (GET), updating it (PUT or PATCH), and deleting it (DELETE).</p><p>You didn’t write a single if/else for any of that. That’s the magic of DRF’s generic views.</p><p>A <strong>generic view</strong> in Django REST Framework is a <strong>ready-made class that already knows how to handle common API actions</strong>, so you don’t have to write the logic yourself.</p><p>Instead of writing:</p><ul><li>how to fetch data</li><li>how to validate it</li><li>how to handle GET, POST, PUT, DELETE</li></ul><p>DRF gives you a class that already does all of this. You just plug in:</p><ul><li><strong>what data</strong> (queryset)</li><li><strong>how to convert it</strong> (serializer_class)</li></ul><h4>Simple idea</h4><p>Think of a generic view like a <strong>pre-built engine</strong>.<br> You don’t build the engine — you just attach it to your model and it runs.</p><pre># -------------------------------<br># GENERIC VIEWS (LESS CODE, MORE POWER)<br># -------------------------------<br><br>from rest_framework import generics<br>from .models import Product<br>from .serializers import ProductSerializer<br><br><br>class ProductListCreateView(generics.ListCreateAPIView):<br>    # queryset → defines WHAT data this view will work with<br>    queryset = Product.objects.all()<br><br>    # serializer_class → defines HOW data is converted (JSON &lt;-&gt; Model)<br>    serializer_class = ProductSerializer<br><br>    # Behind the scenes DRF already provides:<br>    # GET  → list all products<br>    # POST → create a new product<br>    # No need to write methods like get() or post()<br><br><br>class ProductDetailView(generics.RetrieveUpdateDestroyAPIView):<br>    queryset = Product.objects.all()<br>    serializer_class = ProductSerializer<br><br>    # Behind the scenes DRF already provides:<br>    # GET     → retrieve a single product (by ID)<br>    # PUT     → update entire product<br>    # PATCH   → partial update<br>    # DELETE  → delete product<br>    # All handled automatically based on HTTP method<br><br><br># -------------------------------<br># WITHOUT GENERIC VIEWS (MANUAL WORK)<br># -------------------------------<br><br>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework import status<br><br><br>class ProductView(APIView):<br><br>    def get(self, request):<br>        # Manually fetch data from database<br>        products = Product.objects.all()<br><br>        # Convert model objects → JSON using serializer<br>        serializer = ProductSerializer(products, many=True)<br><br>        # Return response manually<br>        return Response(serializer.data)<br><br><br>    def post(self, request):<br>        # Convert incoming JSON → model data<br>        serializer = ProductSerializer(data=request.data)<br><br>        # Manually validate input<br>        if serializer.is_valid():<br>            # Save data to database<br>            serializer.save()<br><br>            # Return created object<br>            return Response(serializer.data, status=status.HTTP_201_CREATED)<br><br>        # If validation fails, return errors<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br><br># -------------------------------<br># CORE DIFFERENCE<br># -------------------------------<br># APIView:<br>#   You write:<br>#   - get()<br>#   - post()<br>#   - validation<br>#   - saving<br>#   - responses<br><br># GenericAPIView:<br>#   You only declare:<br>#   - queryset<br>#   - serializer<br>#   DRF internally handles:<br>#   - HTTP method routing<br>#   - validation<br>#   - DB operations<br>#   - responses</pre><h3>Hook Up Your URLs</h3><p>Two files to update here. First, create a urls.py file inside the products folder:</p><pre>touch products/urls.py</pre><p>Add this inside it:</p><pre>from django.urls import path<br>from .views import ProductListCreateView, ProductDetailView<br><br>urlpatterns = [<br>    path(&#39;&#39;, ProductListCreateView.as_view(), name=&#39;product-list&#39;),<br>    path(&#39;&lt;int:pk&gt;/&#39;, ProductDetailView.as_view(), name=&#39;product-detail&#39;),<br>]</pre><p>Then open core/urls.py — this is the main URL file — and connect everything:</p><pre>from django.contrib import admin<br>from django.urls import path, include<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;api/products/&#39;, include(&#39;products.urls&#39;)),<br>]</pre><p>So now your API looks like this:</p><p>URL and What it does</p><p>GET /api/products/Returns all products</p><p>POST /api/products/Creates a new product</p><p>GET /api/products/1/Returns product with id 1</p><p>PUT /api/products/1/Updates product with id 1</p><p>DELETE /api/products/1/Deletes product with id 1</p><p>No extra code needed for any of that. It all comes from the two view classes you wrote.</p><h3>Run It</h3><pre>python manage.py runserver</pre><p>Go to http://127.0.0.1:8000/api/products/ in your browser.</p><p>You’ll see DRF’s browsable API — a proper web interface where you can try out your endpoints without needing Postman or any other tool. Click around, add a product using the form at the bottom, hit GET, try deleting something. It’s all there.</p><h3>One More Thing — Set Up Admin</h3><p>This is optional but genuinely useful. Open products/admin.py and add:</p><pre>from django.contrib import admin<br>from .models import Product<br><br>admin.site.register(Product)</pre><p>Then create an admin account:</p><pre>python manage.py createsuperuser</pre><p>It’ll ask for a username, email, and password. After that, go to http://127.0.0.1:8000/admin/, log in, and you&#39;ll have a full dashboard to manage your products data without touching the API at all. Great for testing or managing data while you&#39;re building.</p><h3>Commands — All in One Place</h3><pre># Environment setup<br>python -m venv venv<br>source venv/bin/activate        # Mac/Linux<br>venv\Scripts\activate           # Windows<br><br># Install packages<br>pip install django djangorestframework pillow<br>pip freeze &gt; requirements.txt<br><br># Create project and app<br>django-admin startproject core .<br>python manage.py startapp products<br><br># Database<br>python manage.py makemigrations<br>python manage.py migrate<br><br># Create admin user<br>python manage.py createsuperuser<br><br># Start the server<br>python manage.py runserver</pre><h3>Your Final Folder Structure</h3><pre>my_drf_project/<br>│<br>├── core/<br>│   ├── settings.py        ← REST_FRAMEWORK config + INSTALLED_APPS<br>│   └── urls.py            ← include(&#39;products.urls&#39;) lives here<br>│<br>├── products/<br>│   ├── migrations/<br>│   ├── admin.py           ← register Product here<br>│   ├── models.py          ← Product model<br>│   ├── serializers.py     ← ProductSerializer<br>│   ├── urls.py            ← list and detail URL patterns<br>│   └── views.py           ← ListCreateView + DetailView<br>│<br>├── manage.py<br>├── requirements.txt<br>└── venv/</pre><h3>Where to Go From Here</h3><p>You’ve got a working REST API. That’s not nothing — a lot of people get stuck way before this point.</p><p>The natural next steps from here are JWT authentication (the djangorestframework-simplejwt package makes it pretty painless), adding filtering and search to your list endpoints, writing custom permissions so only owners can edit their own data, and eventually deploying to something like Railway or Render.</p><p>But don’t rush any of that. Spend time with what you’ve built here. Add more fields to the model. Create a second app. Break things on purpose and fix them. That’s genuinely how this stuff sticks.</p><p>You’ve got the foundation. Everything else is just building on top of it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ec01d5c7c56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django QuerySets Deep Dive]]></title>
            <link>https://medium.com/@bharathofficial05/django-querysets-deep-dive-74c86f3b8eb5?source=rss-5fa5ae546213------2</link>
            <guid isPermaLink="false">https://medium.com/p/74c86f3b8eb5</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[queryset]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 04:12:27 GMT</pubDate>
            <atom:updated>2026-03-12T04:12:27.655Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Django · Python · Backend</strong></p><p>Everything you need to know about QuerySets — from lazy evaluation to advanced optimizations — explained for beginners and developers alike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuoYqhpTpQnUXTJK4PEspA.png" /></figure><h3>Table of Contents</h3><ol><li>What is a QuerySet?</li><li>Lazy Evaluation — The Key Concept</li><li>Basic QuerySet Methods</li><li>Filtering &amp; Lookups</li><li>Chaining QuerySets</li><li>Related Objects &amp; Joins</li><li>Optimization: select_related &amp; prefetch_related</li><li>Aggregation &amp; Annotation</li><li>Common Pitfalls &amp; Pro Tips</li></ol><h3>1. What is a QuerySet?</h3><p>A <strong>QuerySet</strong> is Django’s way of representing a collection of objects from your database. Think of it as a smart list that knows how to talk to your database — but cleverly waits until you actually need the data before making any queries.</p><p>Every Django model comes with a built-in <strong>manager</strong> called objects that gives you access to QuerySets.</p><h3>Example</h3><pre># Your model<br>class Article(models.Model):<br>    title   = models.CharField(max_length=200)<br>    author  = models.CharField(max_length=100)<br>    published = models.BooleanField(default=False)<br>    created = models.DateTimeField(auto_now_add=True)<br><br># Getting a QuerySet (no DB hit yet!)<br>articles = Article.objects.all()<br>print(type(articles))<br># &lt;class &#39;django.db.models.query.QuerySet&#39;&gt;</pre><h3>Key Characteristics</h3><p><strong>Database Abstraction</strong><br>QuerySets work with any database Django supports — PostgreSQL, MySQL, SQLite, Oracle.</p><p><strong>Chainable</strong><br>You can layer filters, annotations, and orderings on top of each other fluidly.</p><p><strong>Lazy by Default</strong><br>No database query is executed until you evaluate the QuerySet.</p><p><strong>Cacheable</strong><br>Once evaluated, results are cached in memory.</p><h3>2. Lazy Evaluation — The Key Concept</h3><p>This is the <strong>most important concept</strong> to understand.</p><p>Creating a QuerySet <strong>does not hit the database</strong>. Django waits until you actually need the results.</p><h3>Why Laziness is Great</h3><p>You can build complex queries step by step without wasting database calls. Django compiles everything into <strong>one optimized SQL query</strong>.</p><h3>Example</h3><pre># Step 1 — No DB hit<br>qs = Article.objects.filter(published=True)<br><br># Step 2 - Still no DB hit<br>qs = qs.filter(author=&quot;Alice&quot;).order_by(&quot;-created&quot;)<br># DB hit happens here<br>for article in qs:<br>    print(article.title)<br># DB hit<br>top5 = list(qs[:5])<br># DB hit<br>count = len(qs)<br># DB hit<br>if qs:<br>    print(&quot;Found articles!&quot;)</pre><p>⚠️ <strong>Beginner Trap</strong></p><p>Using:</p><pre>len(qs)</pre><p>loads all rows into memory.</p><p>Instead use:</p><pre>qs.count()</pre><p>This executes a fast SQL:</p><pre>SELECT COUNT(*)</pre><h3>3. Basic QuerySet Methods</h3><p>These are the core methods you’ll use constantly.</p><h3>Retrieval Methods</h3><pre># Get ALL records<br>Article.objects.all()<br><br># Get ONE record<br>article = Article.objects.get(id=1)<br># Safer<br>from django.shortcuts import get_object_or_404<br>article = get_object_or_404(Article, id=1)<br># Get first / last<br>first = Article.objects.first()<br>last  = Article.objects.last()<br># Count records<br>total = Article.objects.count()<br># Check if records exist<br>has_articles = Article.objects.exists()</pre><h3>Create, Update &amp; Delete</h3><pre># Create<br>a = Article(title=&quot;Hello Django&quot;, author=&quot;Alice&quot;)<br>a.save()<br><br># Create (one line)<br>a = Article.objects.create(title=&quot;Hello&quot;, author=&quot;Bob&quot;)<br># Get or create<br>a, created = Article.objects.get_or_create(<br>    title=&quot;Unique Title&quot;,<br>    defaults={&quot;author&quot;: &quot;Charlie&quot;}<br>)<br># Bulk update<br>Article.objects.filter(author=&quot;Bob&quot;).update(published=True)<br># Delete<br>Article.objects.filter(published=False).delete()</pre><h3>4. Filtering &amp; Lookups</h3><p>Django allows powerful SQL filtering using __ lookups.</p><h3>Examples</h3><pre># Exact match<br>Article.objects.filter(author=&quot;Alice&quot;)<br><br># Case insensitive<br>Article.objects.filter(author__iexact=&quot;alice&quot;)<br># Contains<br>Article.objects.filter(title__contains=&quot;Django&quot;)<br>Article.objects.filter(title__icontains=&quot;django&quot;)<br># Starts / Ends with<br>Article.objects.filter(title__startswith=&quot;How&quot;)<br>Article.objects.filter(title__endswith=&quot;Django&quot;)<br># Numeric comparisons<br>Article.objects.filter(views__gt=100)<br>Article.objects.filter(views__gte=100)<br>Article.objects.filter(views__lt=50)<br># Range<br>Article.objects.filter(views__range=(10, 100))<br># In list<br>Article.objects.filter(author__in=[&quot;Alice&quot;, &quot;Bob&quot;])<br># Null check<br>Article.objects.filter(published_at__isnull=True)<br># Exclude<br>Article.objects.exclude(author=&quot;Alice&quot;)</pre><h3>Complex Queries with Q Objects</h3><p>Use Q objects for OR and complex logic.</p><pre>from django.db.models import Q<br><br># OR<br>Article.objects.filter(<br>    Q(author=&quot;Alice&quot;) | Q(author=&quot;Bob&quot;)<br>)<br># AND<br>Article.objects.filter(<br>    Q(published=True) &amp; Q(views__gt=100)<br>)<br># NOT<br>Article.objects.filter(~Q(author=&quot;Alice&quot;))<br># Complex combination<br>Article.objects.filter(<br>    (Q(author=&quot;Alice&quot;) | Q(author=&quot;Bob&quot;))<br>    &amp; Q(published=True)<br>)</pre><h3>5. Chaining QuerySets</h3><p>QuerySets are <strong>chainable</strong>.</p><p>Django compiles them into <strong>one SQL query</strong>.</p><pre>articles = (<br>    Article.objects<br>    .filter(published=True)<br>    .exclude(author=&quot;Spam Bot&quot;)<br>    .filter(views__gte=50)<br>    .order_by(&quot;-created&quot;)<br>    .distinct()<br>    [:10]<br>)</pre><h3>Ordering</h3><pre>Article.objects.order_by(&quot;title&quot;)<br>Article.objects.order_by(&quot;-created&quot;)</pre><h3>Retrieve Specific Fields</h3><pre>Article.objects.values(&quot;id&quot;, &quot;title&quot;)<br><br>Article.objects.values_list(&quot;id&quot;, flat=True)</pre><p>💡 <strong>Pro Tip</strong></p><p>Use values() when you only need a few fields.<br>This avoids loading full model objects and improves performance.</p><h3>6. Related Objects &amp; Joins</h3><p>Django can traverse relationships using __.</p><h3>Example Models</h3><pre>class Category(models.Model):<br>    name = models.CharField(max_length=100)<br><br>class Article(models.Model):<br>    title = models.CharField(max_length=200)<br>    category = models.ForeignKey(Category, on_delete=models.CASCADE)<br>    tags = models.ManyToManyField(&quot;Tag&quot;)</pre><h3>Filtering Through Relationships</h3><pre>Article.objects.filter(category__name=&quot;Tech&quot;)<br><br>Article.objects.filter(category__name__icontains=&quot;tech&quot;)</pre><h3>Reverse Relations</h3><pre>tech = Category.objects.get(name=&quot;Tech&quot;)<br><br>tech.article_set.all()<br>tech.article_set.filter(published=True)</pre><h3>7. Optimization: select_related &amp; prefetch_related</h3><p>One of the biggest performance problems in Django is the <strong>N+1 query problem</strong>.</p><h3>The N+1 Problem</h3><pre>articles = Article.objects.all()[:20]<br><br>for article in articles:<br>    print(article.category.name)</pre><p>This executes <strong>21 queries</strong>.</p><h3>Fix with select_related</h3><p>Use for <strong>ForeignKey / OneToOne</strong></p><pre>articles = Article.objects.select_related(&quot;category&quot;)[:20]<br><br>for article in articles:<br>    print(article.category.name)</pre><p>Now Django uses <strong>one SQL JOIN query</strong>.</p><h3>Fix with prefetch_related</h3><p>Use for <strong>ManyToMany</strong></p><pre>articles = Article.objects.prefetch_related(&quot;tags&quot;)[:20]</pre><pre>for article in articles:<br>    for tag in article.tags.all():<br>        print(tag.name)</pre><h3>Comparison</h3><p>MethodUse CaseBehaviorselect_relatedForeignKey / OneToOneSQL JOINprefetch_relatedManyToManySeparate query + Python join</p><h3>8. Aggregation &amp; Annotation</h3><p>Django supports powerful database calculations.</p><h3>Aggregate (Whole QuerySet)</h3><pre>from django.db.models import Count, Avg, Max<br><br>result = Article.objects.aggregate(<br>    total=Count(&quot;id&quot;),<br>    avg_views=Avg(&quot;views&quot;),<br>    max_views=Max(&quot;views&quot;),<br>)</pre><p>Output:</p><pre>{&#39;total&#39;: 42, &#39;avg_views&#39;: 134.7, &#39;max_views&#39;: 9800}</pre><h3>Annotate (Per Object)</h3><pre>categories = Category.objects.annotate(<br>    article_count=Count(&quot;article&quot;)<br>)<br><br>for cat in categories:<br>    print(cat.name, cat.article_count)</pre><p>You can also filter on annotations.</p><pre>Category.objects.annotate(<br>    article_count=Count(&quot;article&quot;)<br>).filter(article_count__gte=5)</pre><h3>9. Common Pitfalls &amp; Pro Tips</h3><p>⚠️ <strong>Re-evaluating QuerySets</strong></p><p>Calling the same QuerySet repeatedly may trigger new queries.</p><p>Use:</p><pre>cached = list(qs)</pre><p>⚠️ <strong>Forgetting </strong><strong>.save()</strong></p><p>Modifying a model does NOT update the database until:</p><pre>obj.save()</pre><p>✅ <strong>Use Django Debug Toolbar</strong></p><p>It shows all SQL queries executed by a page.</p><p>✅ <strong>Use </strong><strong>only() and </strong><strong>defer() for large models</strong></p><pre>Article.objects.only(&quot;id&quot;, &quot;title&quot;)<br><br>Article.objects.defer(&quot;large_text_field&quot;)</pre><h3>Quick Cheat Sheet</h3><pre># Efficient counting<br>Article.objects.count()<br>len(Article.objects.all())   # Avoid<br><br># Efficient existence check<br>Article.objects.filter(...).exists()<br># Load specific fields<br>Article.objects.only(&quot;id&quot;, &quot;title&quot;)<br># Cache a QuerySet<br>cached = list(Article.objects.filter(published=True))<br># Bulk insert<br>articles = [Article(title=f&quot;Article {i}&quot;) for i in range(100)]<br>Article.objects.bulk_create(articles)</pre><h3>Key Takeaways</h3><p>Master these concepts and your Django apps will become <strong>faster and more maintainable</strong>.</p><p>✓ QuerySets are lazy<br>✓ QuerySets are chainable<br>✓ Use filter() with lookups<br>✓ Use Q objects for complex logic<br>✓ Use select_related for ForeignKey<br>✓ Use prefetch_related for ManyToMany<br>✓ Use .count() instead of len()<br>✓ Use .exists() instead of if qs<br>✓ Use aggregate() for calculations<br>✓ Use annotate() for per-row fields<br>✓ Use bulk_create() for mass inserts<br>✓ Use Django Debug Toolbar to inspect queries</p><p><strong>Happy querying! 🐍</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74c86f3b8eb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Models Explained
ORM vs Raw SQL vs Sequelize]]></title>
            <link>https://medium.com/@bharathofficial05/django-models-explained-orm-vs-raw-sql-vs-sequelize-d37341aa5260?source=rss-5fa5ae546213------2</link>
            <guid isPermaLink="false">https://medium.com/p/d37341aa5260</guid>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 07:18:23 GMT</pubDate>
            <atom:updated>2026-03-11T07:18:23.518Z</atom:updated>
            <content:encoded><![CDATA[<p>A frontend-friendly guide to understanding how databases talk to your code — with side-by-side comparisons you can actually use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3C43NvcYYwEHzyoDo2ULSg.png" /></figure><p><strong>TL;DR — Skip here if you’re in a hurry</strong></p><ul><li>A Django Model = a Python class that maps directly to a database table</li><li>ORM lets you write Python (or JS) instead of SQL — no SQL knowledge required</li><li>Django ORM (Python) ≈ Sequelize (JavaScript/Node) — same concept, different language</li><li>Raw SQL is faster to write for one-offs, but ORMs win at maintainability &amp; safety</li><li>You can mix both in Django — ORM for most queries, raw SQL when you really need it</li></ul><h3>1. Why Does This Even Exist?</h3><p>Imagine you’re building a blog app. You need to store posts somewhere — a database. Now, databases speak a language called SQL (Structured Query Language). It looks like this:</p><p>SQL</p><pre>-- Raw SQL to create a blog post table<br>CREATE TABLE blog_post (<br>  id         INTEGER PRIMARY KEY AUTOINCREMENT,<br>  title      VARCHAR(200) NOT NULL,<br>  content    TEXT,<br>  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,<br>  author_id  INTEGER REFERENCES auth_user(id)<br>);</pre><p>That’s fine for one table. But what about when you have 20 tables, complex joins, and you need to refactor a column name? You’d be rewriting SQL everywhere. Error-prone, tedious, and very hard to test.</p><p>This is exactly the problem an ORM (Object-Relational Mapper) solves.</p><blockquote><em>An ORM lets you define your database structure in the same language as the rest of your app — and write queries using that language too.</em></blockquote><h3>2. What Is a Django Model?</h3><p>In Django, a Model is a Python class that inherits from django.db.models.Model. Each class becomes a table. Each attribute becomes a column. That&#39;s it — no SQL needed.</p><p>Python · Django Model</p><pre>from django.db import models</pre><pre>class Post(models.Model):<br>    title      = models.CharField(max_length=200)<br>    content    = models.TextField()<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    author     = models.ForeignKey(<br>        &#39;auth.User&#39;,<br>        on_delete=models.CASCADE<br>    )</pre><pre>    class Meta:<br>        ordering = [&#39;-created_at&#39;]  # newest first</pre><pre>    def __str__(self):<br>        return self.title</pre><p>💡Notice what you didn’t write</p><p><em>No </em><em>CREATE TABLE. No data types like </em><em>VARCHAR(200). No </em><em>PRIMARY KEY. Django handles all of that when you run </em><em>python manage.py migrate</em>.</p><p>Once you define your model, Django generates and runs the SQL automatically. The model class is your single source of truth.</p><h3>3. Querying: ORM vs Raw SQL vs Sequelize</h3><p>Now let’s look at the real meat — how you fetch, create, and update data. We’ll compare the same operations across all three approaches side by side.</p><h3>① Get all posts</h3><p>Django ORM · Python</p><pre># Clean, readable, chainable<br>posts = Post.objects.all()<br><br># With a filter<br>posts = Post.objects.filter(author__username=&#39;alice&#39;)</pre><p>Raw SQL · Python (Django cursor)</p><pre>from django.db import connection<br><br>with connection.cursor() as cursor:<br>    cursor.execute(&quot;SELECT * FROM blog_post WHERE author_id = %s&quot;, [author_id])<br>    rows = cursor.fetchall()</pre><p>Sequelize · JavaScript (Node.js)</p><pre>// Sequelize is the Node.js equivalent of Django ORM<br>const posts = await Post.findAll();<br><br>// With a filter<br>const posts = await Post.findAll({<br>  where: { authorUsername: &#39;alice&#39; }<br>});</pre><h3>② Create a new post</h3><p>Django ORM · Python</p><pre># Option A — two steps<br>post = Post(title=&quot;Hello World&quot;, content=&quot;My first post&quot;, author=user)<br>post.save()<br><br># Option B - one line<br>post = Post.objects.create(<br>    title=&quot;Hello World&quot;,<br>    content=&quot;My first post&quot;,<br>    author=user<br>)</pre><p>Raw SQL · Python</p><pre>with connection.cursor() as cursor:<br>    cursor.execute(<br>        &quot;&quot;&quot;INSERT INTO blog_post (title, content, author_id, created_at)<br>           VALUES (%s, %s, %s, NOW())&quot;&quot;&quot;,<br>        [&quot;Hello World&quot;, &quot;My first post&quot;, user.id]<br>    )</pre><p>Sequelize · JavaScript</p><pre>const post = await Post.create({<br>  title: &#39;Hello World&#39;,<br>  content: &#39;My first post&#39;,<br>  authorId: user.id<br>});</pre><h3>③ Update a record</h3><p>Django ORM · Python</p><pre># Fetch → modify → save<br>post = Post.objects.get(id=1)<br>post.title = &quot;Updated Title&quot;<br>post.save()<br><br># Or bulk update without fetching<br>Post.objects.filter(author=user).update(title=&quot;Updated&quot;)</pre><p>Sequelize · JavaScript</p><pre>await Post.update(<br>  { title: &#39;Updated Title&#39; },<br>  { where: { id: 1 } }<br>);</pre><h3>4. Relationships: The Tricky Part</h3><p>Most databases have related tables — users have posts, posts have comments, etc. Joining them in raw SQL is notoriously verbose. ORMs make this elegant.</p><p>Django ORM · Models with relationships</p><pre>class Author(models.Model):<br>    name  = models.CharField(max_length=100)<br>    email = models.EmailField(unique=True)<br><br>class Post(models.Model):<br>    title  = models.CharField(max_length=200)<br>    author = models.ForeignKey(Author, on_delete=models.CASCADE,<br>                                related_name=&#39;posts&#39;)<br>    tags   = models.ManyToManyField(&#39;Tag&#39;)   # many-to-many<br>class Comment(models.Model):<br>    post    = models.ForeignKey(Post, on_delete=models.CASCADE,<br>                                related_name=&#39;comments&#39;)<br>    body    = models.TextField()<br>    created = models.DateTimeField(auto_now_add=True)</pre><p>Django ORM · Traversing relationships (no SQL needed)</p><pre># Get all posts by an author<br>author = Author.objects.get(name=&quot;Alice&quot;)<br>posts = author.posts.all()     # uses related_name=&#39;posts&#39;<br><br># Get comments for a post<br>post = Post.objects.get(id=5)<br>comments = post.comments.all()  # uses related_name=&#39;comments&#39;<br><br># Eager load to avoid N+1 queries (important!)<br>posts = Post.objects.select_related(&#39;author&#39;).prefetch_related(&#39;comments&#39;)</pre><p>Raw SQL · same query with a JOIN</p><pre>SELECT<br>    p.id, p.title, p.content,<br>    a.name AS author_name,<br>    c.body AS comment_body<br>FROM  blog_post p<br>INNER JOIN blog_author  a ON p.author_id = a.id<br>LEFT  JOIN blog_comment c ON c.post_id   = p.id<br>WHERE a.name = &#39;Alice&#39;<br>ORDER BY p.created_at DESC;</pre><p>⚠️The N+1 Problem — A common trap</p><p><em>If you do </em><em>Post.objects.all() then loop and access </em><em>post.author for each post, Django makes one SQL query per post. Fix it with </em><em>select_related(&#39;author&#39;) — it pre-fetches everything in one JOIN query.</em></p><h3>5. Migrations: Schema Version Control</h3><p>One of Django’s killer features: migrations. Every time you change a model, Django can auto-generate the SQL needed to update your database — and track it in version control.</p><p>Shell</p><pre># Step 1: Generate migration file from your model changes<br>python manage.py makemigrations<br><br># Output:<br># Migrations for &#39;blog&#39;:<br>#   blog/migrations/0001_initial.py<br>#     - Create model Author<br>#     - Create model Post<br>#     - Create model Comment<br># Step 2: Apply migrations to your database<br>python manage.py migrate</pre><p>Compare this to Sequelize, which has a very similar workflow:</p><p>Sequelize · JavaScript equivalent</p><pre>// Define the model (same idea as Django&#39;s class)<br>const Post = sequelize.define(&#39;Post&#39;, {<br>  title: {<br>    type: DataTypes.STRING(200),<br>    allowNull: false<br>  },<br>  content: {<br>    type: DataTypes.TEXT<br>  }<br>}, {<br>  timestamps: true // adds createdAt / updatedAt<br>});<br><br>// Sync (like migrate)<br>await sequelize.sync({ alter: true });</pre><h3>6. Django ORM vs Sequelize vs Raw SQL</h3><h4><em>Django ORM</em><br>Python / Django</h4><p>Batteries-included, tight framework integration, excellent admin panel, migrations out of the box.</p><h4><em>Sequelize</em><br>JavaScript / Node.js</h4><p>The most popular ORM for Node. Similar concepts to Django ORM, but in JS. Works with Express, Fastify, etc.</p><h4><em>Raw SQL</em><br>Any language</h4><p>Maximum control. Ideal for very complex queries or performance-critical paths where every byte counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*1nA0avHxcOvVJtuhkLqc3g.png" /></figure><h3>7. When to Use Each Approach</h3><h4>Use Django ORM when…</h4><p>You’re building a standard web app with CRUD operations. You want readable, maintainable code. You need admin panel features. You’re working in a team and want consistency. This is 90% of Django work.</p><h4>Use Raw SQL when…</h4><p>You have a very complex report query with many joins and aggregations. You’re squeezing out every millisecond of performance. The ORM generates poor SQL for your specific use case (check with print(queryset.query) first!).</p><h4>Use Sequelize when…</h4><p>You’re building a Node.js backend (Express, Fastify, NestJS). You’re a frontend dev expanding to full-stack with JavaScript. You want the same ORM mental model as Django, just in JS/TS.</p><h3>8. A Real-World Example: Blog with Comments</h3><p>Let’s build a complete mini-blog with Django models, queries, and a view — all in one place so you can see how it all connects.</p><p>Python · models.py</p><pre>from django.db import models<br>from django.contrib.auth.models import User<br><br>class Category(models.Model):<br>    name = models.CharField(max_length=80, unique=True)<br>    def __str__(self): return self.name<br>class Post(models.Model):<br>    STATUS = [(&#39;draft&#39;, &#39;Draft&#39;), (&#39;published&#39;, &#39;Published&#39;)]<br>    title      = models.CharField(max_length=200)<br>    slug       = models.SlugField(unique=True)<br>    author     = models.ForeignKey(User, on_delete=models.CASCADE)<br>    category   = models.ForeignKey(Category, on_delete=models.SET_NULL,<br>                                    null=True, blank=True)<br>    content    = models.TextField()<br>    status     = models.CharField(max_length=10, choices=STATUS, default=&#39;draft&#39;)<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)<br>    class Meta:<br>        ordering    = [&#39;-created_at&#39;]<br>        indexes     = [models.Index(fields=[&#39;slug&#39;])]<br>class Comment(models.Model):<br>    post    = models.ForeignKey(Post, on_delete=models.CASCADE,<br>                                related_name=&#39;comments&#39;)<br>    author  = models.ForeignKey(User, on_delete=models.CASCADE)<br>    body    = models.TextField()<br>    created = models.DateTimeField(auto_now_add=True)</pre><p>Python · views.py — Querying it all together</p><pre>from django.shortcuts import render, get_object_or_404<br>from .models import Post<br><br>def post_detail(request, slug):<br>    # Fetch post + prefetch comments + author in one DB hit<br>    post = Post.objects.select_related(&#39;author&#39;, &#39;category&#39;) \<br>                       .prefetch_related(&#39;comments__author&#39;) \<br>                       .get(slug=slug, status=&#39;published&#39;)<br>    return render(request, &#39;blog/post_detail.html&#39;, {&#39;post&#39;: post})<br>def post_list(request):<br>    # Filter, order, paginate - all ORM<br>    posts = Post.objects \<br>        .filter(status=&#39;published&#39;) \<br>        .select_related(&#39;author&#39;) \<br>        .only(&#39;title&#39;, &#39;slug&#39;, &#39;created_at&#39;, &#39;author__username&#39;)<br>    # .only() is like SELECT specific columns - faster than SELECT *<br>    return render(request, &#39;blog/list.html&#39;, {&#39;posts&#39;: posts})</pre><h3>9. Bonus: The Django Admin (For Free)</h3><p>Here’s something Sequelize and raw SQL can’t give you: once you define your Django models, you get a fully functional admin UI completely for free — just by registering your models.</p><p>Python · admin.py</p><pre>from django.contrib import admin<br>from .models import Post, Comment, Category<br><br><br># Two lines → full CRUD UI at /admin/<br>admin.register(Category)<br><br><br>@admin.register(Post)<br>class PostAdmin(admin.ModelAdmin):<br>    list_display = [&#39;title&#39;, &#39;author&#39;, &#39;status&#39;, &#39;created_at&#39;]<br>    list_filter = [&#39;status&#39;, &#39;category&#39;]<br>    search_fields = [&#39;title&#39;, &#39;content&#39;]<br>    prepopulated_fields = {&#39;slug&#39;: (&#39;title&#39;,)}</pre><p>✨This is Django’s superpower</p><p><em>Your models are not just database tables. They’re the contract for your entire app: your admin panel, your API serializers (DRF), your forms, your migrations — all generated from one Python class.</em></p><h3>10. Summary: The Mental Model</h3><p>Here’s how to think about all of this:</p><p>Conceptual Mapping</p><pre># Database world   →  ORM world (Django)<br>Table               →  Python class  (class Post(models.Model))<br>Column              →  Class field   (title = models.CharField(...))<br>Row                 →  Class instance (post = Post.objects.get(id=1))<br>Foreign Key         →  ForeignKey field<br>JOIN                →  select_related / prefetch_related<br>INSERT              →  Post.objects.create(...)  or  post.save()<br>UPDATE              →  post.save()  or  .update(...)<br>DELETE              →  post.delete()  or  .filter(...).delete()<br>SELECT WHERE        →  .filter(...)<br>SELECT WHERE NOT    →  .exclude(...)<br>ORDER BY            →  .order_by(...)<br>LIMIT               →  .first() / [:10] / Paginator</pre><p>If you’re coming from JavaScript and Sequelize, this is nearly a 1:1 mapping — Post.findAll() ≈ Post.objects.all(), Post.create() ≈ Post.objects.create(). The concepts are identical.</p><p>If you’re coming from raw SQL, the biggest mindset shift is: <em>stop thinking in tables and rows, start thinking in objects and relationships.</em> The SQL still happens — you just don’t write it.</p><blockquote><em>The best code is the code you don’t have to write. Django’s ORM quietly writes thousands of lines of safe, optimized SQL so you can focus on your app.</em></blockquote><p>Now go run python manage.py startproject and build something. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d37341aa5260" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Django Handles Requests: From URL → View → Template]]></title>
            <link>https://medium.com/@bharathofficial05/how-django-handles-requests-from-url-view-template-94995a981618?source=rss-5fa5ae546213------2</link>
            <guid isPermaLink="false">https://medium.com/p/94995a981618</guid>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 17:01:06 GMT</pubDate>
            <atom:updated>2026-03-10T17:01:06.705Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into the lifecycle of a Django request — what happens between the moment a user hits Enter and the page appears on screen.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5aa3Ki7DYvR9F8iBq-9Jw.png" /></figure><p>Every time a browser sends a request to a Django application, a beautifully orchestrated sequence of events kicks off behind the scenes. Most developers use Django for months before they truly understand what’s happening under the hood. Once you do, everything — debugging, performance tuning, middleware design — becomes significantly clearer.</p><p>Let’s walk through the entire journey, step by step.</p><h3>The Big Picture</h3><p>Before diving into code, here’s the 10,000-foot view of what happens when a request hits a Django app:</p><pre>Browser Request<br>      ↓<br>  WSGI/ASGI Server (Gunicorn, Uvicorn, etc.)<br>      ↓<br>  Django&#39;s WSGIHandler / ASGIHandler<br>      ↓<br>  Middleware Stack (request phase)<br>      ↓<br>  URL Resolver (urls.py)<br>      ↓<br>  View Function or Class-Based View<br>      ↓<br>  Template Engine (if needed)<br>      ↓<br>  Middleware Stack (response phase)<br>      ↓<br>Browser Response</pre><p>Simple on the surface. Fascinating underneath. Let’s unpack each layer.</p><h3>Step 1: The WSGI/ASGI Entry Point</h3><p>Django is a WSGI (Web Server Gateway Interface) application at its core — and more recently, an ASGI application too for async support.</p><p>When a web server like Gunicorn receives an HTTP request, it calls Django’s entry point, defined in your project’s wsgi.py file:</p><pre># myproject/wsgi.py<br>import os<br>from django.core.wsgi import get_wsgi_application</pre><pre>os.environ.setdefault(&#39;DJANGO_SETTINGS_MODULE&#39;, &#39;myproject.settings&#39;)<br>application = get_wsgi_application()</pre><p>This application object is a callable. Every incoming HTTP request gets passed to it as a raw environment dictionary and a start_response callback. Django takes it from there.</p><p>Internally, get_wsgi_application() returns a WSGIHandler instance. This handler is responsible for converting the raw WSGI environment into a proper HttpRequest object — the request object you interact with in every view.</p><h3>Step 2: Middleware — The Gatekeeper Layer</h3><p>Before your view ever runs, the request passes through the <strong>middleware stack</strong>. Think of middleware as a series of plugins that can inspect, modify, or even short-circuit the request/response cycle.</p><p>Middleware is configured in settings.py:</p><pre>MIDDLEWARE = [<br>    &#39;django.middleware.security.SecurityMiddleware&#39;,<br>    &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,<br>    &#39;django.middleware.common.CommonMiddleware&#39;,<br>    &#39;django.middleware.csrf.CsrfViewMiddleware&#39;,<br>    &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,<br>    &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,<br>    &#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,<br>]</pre><p>Django processes this list <strong>top-to-bottom</strong> for the request and <strong>bottom-to-top</strong> for the response. It’s an onion — each layer wraps the next.</p><p>Here’s what a custom middleware looks like:</p><pre>class MyCustomMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br>        # One-time setup on server startup</pre><pre>    def __call__(self, request):<br>        # Code here runs BEFORE the view<br>        print(f&quot;Incoming: {request.method} {request.path}&quot;)</pre><pre>        response = self.get_response(request)  # Call the next layer</pre><pre>        # Code here runs AFTER the view<br>        print(f&quot;Outgoing: {response.status_code}&quot;)</pre><pre>        return response</pre><p>Key middleware responsibilities in Django’s default stack:</p><ul><li><strong>SecurityMiddleware</strong> — enforces HTTPS, sets security headers</li><li><strong>SessionMiddleware</strong> — loads and saves session data</li><li><strong>AuthenticationMiddleware</strong> — attaches request.user to every request</li><li><strong>CsrfViewMiddleware</strong> — validates CSRF tokens on POST requests</li></ul><p>If any middleware returns a response directly (like a redirect or a 403), the request never reaches your view. This is the security layer’s first line of defense.</p><h3>Step 3: URL Resolution — Finding the Right View</h3><p>Once the request clears middleware, Django needs to figure out <em>which view</em> should handle it. This is the job of the <strong>URL resolver</strong>.</p><p>Django starts with your project’s root URL configuration, defined in settings.py:</p><pre>ROOT_URLCONF = &#39;myproject.urls&#39;</pre><p>It then imports that module and tries to match the request’s URL path against the patterns defined there:</p><pre># myproject/urls.py<br>from django.contrib import admin<br>from django.urls import path, include</pre><pre>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;blog/&#39;, include(&#39;blog.urls&#39;)),<br>    path(&#39;api/&#39;, include(&#39;api.urls&#39;)),<br>]</pre><p>The include() function allows you to delegate to another URLs module. This is crucial for keeping large applications modular.</p><p>Inside blog/urls.py:</p><pre>from django.urls import path<br>from . import views</pre><pre>urlpatterns = [<br>    path(&#39;&#39;, views.post_list, name=&#39;post-list&#39;),<br>    path(&#39;&lt;int:pk&gt;/&#39;, views.post_detail, name=&#39;post-detail&#39;),<br>    path(&#39;&lt;int:pk&gt;/edit/&#39;, views.post_edit, name=&#39;post-edit&#39;),<br>]</pre><p>Django tries each pattern in order. When it finds a match, it extracts any <strong>URL parameters</strong> (like pk in &lt;int:pk&gt;/) and passes them as keyword arguments to the view.</p><p>If no pattern matches, Django raises a Http404 — or more precisely, a Resolver404 exception — which is then handled gracefully.</p><p>You can also use re_path() for regex-based patterns when you need more control:</p><pre>from django.urls import re_path</pre><pre>re_path(r&#39;^archive/(?P&lt;year&gt;[0-9]{4})/$&#39;, views.archive, name=&#39;archive&#39;),</pre><h3>Step 4: The View — Where Your Logic Lives</h3><p>The URL resolver found a match. Now Django calls your view function (or class-based view), passing it the HttpRequest object and any captured URL parameters.</p><h3>Function-Based Views (FBVs)</h3><p>The most straightforward approach:</p><pre># blog/views.py<br>from django.shortcuts import render, get_object_or_404<br>from .models import Post</pre><pre>def post_detail(request, pk):<br>    post = get_object_or_404(Post, pk=pk)</pre><pre>    context = {<br>        &#39;post&#39;: post,<br>        &#39;title&#39;: post.title,<br>    }</pre><pre>    return render(request, &#39;blog/post_detail.html&#39;, context)</pre><p>The view is responsible for three things:</p><ol><li><strong>Receiving</strong> the request and URL parameters</li><li><strong>Processing</strong> business logic (database queries, form handling, API calls)</li><li><strong>Returning</strong> an HttpResponse</li></ol><p>The render() shortcut combines template loading and response creation into one step. Under the hood, it calls loader.get_template(), renders it with the context, and wraps the result in an HttpResponse.</p><h3>Class-Based Views (CBVs)</h3><p>For more complex views, Django provides class-based views that come with a lot of built-in behavior:</p><pre>from django.views.generic import DetailView<br>from .models import Post</pre><pre>class PostDetailView(DetailView):<br>    model = Post<br>    template_name = &#39;blog/post_detail.html&#39;<br>    context_object_name = &#39;post&#39;</pre><p>When a request comes in, Django calls the view’s as_view() method, which dispatches to get(), post(), put(), etc., based on the HTTP method. CBVs shine for CRUD operations — ListView, DetailView, CreateView, UpdateView, and DeleteView handle the boilerplate so you don&#39;t have to.</p><h3>Handling Different HTTP Methods</h3><pre>def post_edit(request, pk):<br>    post = get_object_or_404(Post, pk=pk)</pre><pre>    if request.method == &#39;POST&#39;:<br>        form = PostForm(request.POST, instance=post)<br>        if form.is_valid():<br>            form.save()<br>            return redirect(&#39;post-detail&#39;, pk=post.pk)<br>    else:<br>        form = PostForm(instance=post)</pre><pre>    return render(request, &#39;blog/post_edit.html&#39;, {&#39;form&#39;: form, &#39;post&#39;: post})</pre><p>This pattern — check the method, process or display accordingly — is the backbone of form handling in Django.</p><h3>Step 5: The Template Engine — Rendering the Response</h3><p>Your view has gathered its data and is ready to produce HTML. This is where Django’s <strong>template engine</strong> takes over.</p><p>The render() shortcut calls the template loader, which searches for the template file in the directories listed under TEMPLATES in settings:</p><pre>TEMPLATES = [<br>    {<br>        &#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;,<br>        &#39;DIRS&#39;: [BASE_DIR / &#39;templates&#39;],<br>        &#39;APP_DIRS&#39;: True,  # Also looks in each app&#39;s templates/ directory<br>        &#39;OPTIONS&#39;: {<br>            &#39;context_processors&#39;: [<br>                &#39;django.template.context_processors.request&#39;,<br>                &#39;django.contrib.auth.context_processors.auth&#39;,<br>                &#39;django.contrib.messages.context_processors.messages&#39;,<br>            ],<br>        },<br>    },<br>]</pre><p>With APP_DIRS: True, Django also checks blog/templates/blog/post_detail.html — a widely used convention.</p><h3>The Template Language</h3><p>Django templates use a clean, designer-friendly syntax:</p><pre>&lt;!-- blog/templates/blog/post_detail.html --&gt;<br>{% extends &quot;base.html&quot; %}</pre><pre>{% block title %}{{ post.title }}{% endblock %}</pre><pre>{% block content %}<br>&lt;article&gt;<br>    &lt;h1&gt;{{ post.title }}&lt;/h1&gt;<br>    &lt;p class=&quot;meta&quot;&gt;<br>        By {{ post.author.get_full_name }} on {{ post.created_at|date:&quot;F j, Y&quot; }}<br>    &lt;/p&gt;<br>    &lt;div class=&quot;body&quot;&gt;<br>        {{ post.body|linebreaks }}<br>    &lt;/div&gt;<br>&lt;/article&gt;</pre><pre>{% if post.tags.all %}<br>&lt;ul class=&quot;tags&quot;&gt;<br>    {% for tag in post.tags.all %}<br>    &lt;li&gt;{{ tag.name }}&lt;/li&gt;<br>    {% endfor %}<br>&lt;/ul&gt;<br>{% endif %}<br>{% endblock %}</pre><p>Key template concepts at work here:</p><ul><li>{{ variable }} — outputs a variable&#39;s value</li><li>{% tag %} — control flow: extends, block, for, if</li><li>|filter — transforms a value: |date, |linebreaks, |truncatewords</li><li>{% extends %} / {% block %} — template inheritance for DRY layouts</li></ul><h3>Context Processors</h3><p>Notice that you didn’t pass request.user explicitly to the template, but it&#39;s still available. That&#39;s thanks to <strong>context processors</strong> — functions that inject data into every template context automatically. The auth context processor adds user and perms. You can write your own to inject site-wide data without touching every view.</p><h3>Step 6: The Response Journey Back</h3><p>After the template is rendered, the view returns an HttpResponse. This response then travels back <em>up</em> through the middleware stack (bottom-to-top this time), giving each middleware a chance to modify it.</p><p>For example, SecurityMiddleware adds HTTP security headers like X-Content-Type-Options on the way out. SessionMiddleware saves any session changes back to the database.</p><p>Finally, Django passes the response back to the WSGI server, which sends the HTTP response bytes to the browser.</p><h3>Putting It All Together: A Visual Trace</h3><p>Let’s trace a real request: a user visits /blog/42/.</p><pre>GET /blog/42/ HTTP/1.1</pre><pre>1. WSGIHandler receives it, creates HttpRequest object<br>2. SecurityMiddleware → passes through (no redirect needed)<br>3. SessionMiddleware → loads session for this user<br>4. AuthenticationMiddleware → attaches request.user<br>5. CsrfViewMiddleware → GET request, no CSRF check needed<br>6. URL Resolver:<br>   - tries &#39;admin/&#39; → no match<br>   - tries &#39;blog/&#39; → match! delegates to blog/urls.py<br>   - tries &#39;&lt;int:pk&gt;/&#39; with pk=42 → match!<br>7. Calls post_detail(request, pk=42)<br>8. View queries Post.objects.get(pk=42)<br>9. Calls render(request, &#39;blog/post_detail.html&#39;, context)<br>10. Template engine loads the template, renders HTML<br>11. Returns HttpResponse with 200 status<br>12. Response passes back through middleware (bottom-to-top)<br>13. WSGI server sends HTML to browser</pre><p>Total time for this? Often under 50 milliseconds for a well-optimized app.</p><h3>Common Pitfalls and Pro Tips</h3><p><strong>The N+1 Query Problem in Templates</strong></p><p>Because templates can lazily evaluate querysets, it’s easy to accidentally trigger dozens of database queries. Use select_related() and prefetch_related() in your views:</p><pre># Bad — triggers a query for each post&#39;s author<br>posts = Post.objects.all()</pre><pre># Good — joins author in a single query<br>posts = Post.objects.select_related(&#39;author&#39;).all()</pre><p><strong>Short-Circuiting with Middleware</strong></p><p>Middleware can return a response directly, bypassing all subsequent middleware and the view entirely. This is how authentication middleware can block access before your view code ever runs.</p><p><strong>URL Naming and </strong><strong>reverse()</strong></p><p>Always name your URL patterns and use reverse() (or {% url %} in templates) instead of hardcoding paths. If a URL ever changes, you update it in one place:</p><pre>from django.urls import reverse<br>redirect_url = reverse(&#39;post-detail&#39;, kwargs={&#39;pk&#39;: post.pk})</pre><p><strong>Template Caching</strong></p><p>In production, Django caches compiled templates in memory. In development, it reloads them on every request. This is controlled by the loaders setting — something worth reviewing if you&#39;re squeezing out performance.</p><h3>Conclusion</h3><p>Django’s request lifecycle is a masterclass in separation of concerns. Each layer — middleware, URL routing, views, templates — has a clear, focused responsibility. The framework handles the plumbing so you can focus on the logic that makes your application unique.</p><p>Understanding this flow transforms you from someone who <em>uses</em> Django to someone who <em>understands</em> it. Debugging becomes more intuitive. Architecture decisions become clearer. And when something breaks at 2am, you’ll know exactly where to look.</p><p>Next time you write return render(request, &#39;template.html&#39;, context), you&#39;ll know the full journey that single line sets in motion.</p><p><em>Found this useful? Follow for more deep dives into Django internals, Python patterns, and web development best practices.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94995a981618" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Essentials Every Developer Should Know Before Learning Django]]></title>
            <link>https://medium.com/@bharathofficial05/python-essentials-every-developer-should-know-before-learning-django-baa616c20212?source=rss-5fa5ae546213------2</link>
            <guid isPermaLink="false">https://medium.com/p/baa616c20212</guid>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 16:52:16 GMT</pubDate>
            <atom:updated>2026-03-09T16:52:16.362Z</atom:updated>
            <content:encoded><![CDATA[<h3>The practical Python concepts that will make Django easier, faster, and far less frustrating</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0u0_0JUAHgs_sgA6o51cg.png" /></figure><p>Django is one of the most powerful web frameworks in the world. But before diving into it, there’s a set of Python concepts that will make the entire experience smoother and much more productive.</p><p>This isn’t a list of trivial syntax reminders. These are the real patterns and tools that Django relies on under the hood — concepts you’ll encounter constantly when building real-world web applications.</p><p>If you’ve written some Python but still feel unsure when Django code becomes complex, this guide is for you.</p><h3>1. List Comprehensions</h3><p>List comprehensions are one of Python’s most expressive features. They allow you to create and transform lists in a single readable line.</p><p>They also appear everywhere in real Django projects.</p><h3>Example</h3><pre>numbers = [1, 2, 3, 4, 5]<br>squared = [n*n for n in numbers]</pre><pre># Output<br>[1, 4, 9, 16, 25]</pre><h3>Why this matters in Django</h3><p>You’ll frequently use list comprehensions to:</p><ul><li>Transform queryset results into usable data</li><li>Filter lists before sending them to templates</li><li>Write concise logic in views and serializers</li></ul><p>Instead of writing long loops, list comprehensions give you clean and readable code.</p><h3>2. Lambda Functions</h3><p>Lambda functions are small anonymous functions designed for quick operations.</p><p>They are written inline and do not require a function name.</p><h3>Example</h3><pre>square = lambda x: x * x<br>print(square(5))  # 25</pre><h3>Common use cases</h3><ul><li>Sorting complex objects</li><li>Functional programming with map() and filter()</li><li>Quick data transformations</li></ul><p>In Django projects, lambdas are often used with sorted() to order data by a specific field.</p><h3>3. Error Handling (Exception Handling)</h3><p>When building web applications, errors are inevitable.</p><p>Users provide unexpected input, APIs fail, and databases may return unexpected results. Proper error handling ensures your application behaves gracefully instead of crashing.</p><h3>Basic Pattern</h3><pre>try:<br>    num = int(input(&quot;Enter number: &quot;))<br>except ValueError:<br>    print(&quot;Invalid input&quot;)</pre><h3>Exceptions you’ll encounter in Django</h3><p>Common Python exceptions include:</p><ul><li>ValueError</li><li>TypeError</li><li>KeyError</li><li>ImportError</li></ul><p>Django also introduces its own exceptions like:</p><ul><li>DoesNotExist</li><li>MultipleObjectsReturned</li></ul><p>Understanding Python’s exception model makes these far easier to work with.</p><h3>4. Working with Files</h3><p>File handling is a core Python skill.</p><p>In Django applications you may need to:</p><ul><li>Handle uploaded files</li><li>Generate reports</li><li>Process CSV data</li><li>Store logs</li></ul><h3>Example</h3><pre>with open(&quot;data.txt&quot;, &quot;r&quot;) as file:<br>    content = file.read()</pre><p>Using with ensures that the file is automatically closed after use — even if an error occurs.</p><h3>5. Python Decorators</h3><p>Decorators are one of Python’s most powerful features, and they are used extensively in Django.</p><p>A decorator wraps a function and allows you to execute code before or after that function runs.</p><h3>Example</h3><pre>def my_decorator(func):<br>    def wrapper():<br>        print(&quot;Before function&quot;)<br>        func()<br>    return wrapper</pre><pre>@my_decorator<br>def say_hello():<br>    print(&quot;Hello&quot;)</pre><h3>Decorators in Django</h3><p>Django provides several useful decorators, such as:</p><ul><li>login_required</li><li>permission_required</li><li>csrf_exempt</li><li>cache_page</li></ul><p>Understanding decorators helps you understand how Django authentication, permissions, and caching work internally.</p><h3>6. Generators</h3><p>Generators produce values one at a time rather than storing everything in memory.</p><h3>Example</h3><pre>def count_up(n):<br>    for i in range(n):<br>        yield i</pre><h3>Why this matters</h3><p>Django QuerySets use <strong>lazy evaluation</strong>, a concept similar to generators.</p><p>This means the database is only queried when the data is actually needed.</p><p>Benefits include:</p><ul><li>Processing large datasets efficiently</li><li>Avoiding memory issues</li><li>Streaming large responses</li></ul><h3>7. Python Packages and Project Organization</h3><p>Python organizes code into modules and packages.</p><p>Understanding this structure becomes important as your Django projects grow.</p><h3>Example Structure</h3><pre>project/<br>    main.py<br>    utils.py<br>    services/<br>        __init__.py<br>        email_service.py<br>        payment_service.py</pre><h3>Key concepts</h3><ul><li><strong>Modules</strong> → individual .py files</li><li><strong>Packages</strong> → directories containing Python modules</li><li>__init__.py → marks directories as packages</li></ul><p>Each Django app is essentially a Python package.</p><h3>8. Working with JSON</h3><p>Modern web applications rely heavily on JSON.</p><p>Whether you’re building APIs or integrating external services, JSON will appear everywhere.</p><h3>Example</h3><pre>import json</pre><pre>data = {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25}</pre><pre>json_string = json.dumps(data)<br>parsed_data = json.loads(json_string)</pre><p>This becomes especially important when working with Django APIs and REST services.</p><h3>9. Python’s Standard Library</h3><p>Python ships with a powerful built-in standard library.</p><p>Some commonly used modules include:</p><ul><li>datetime → handling dates and time</li><li>os → working with operating system features</li><li>sys → system-level operations</li><li>json → JSON handling</li><li>collections → specialized data structures</li></ul><h3>Example</h3><pre>import datetime</pre><pre>now = datetime.datetime.now()<br>print(now.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;))</pre><p>Many Django features rely on these libraries internally.</p><h3>10. Environment Variables</h3><p>Sensitive information should never be hardcoded into your application.</p><p>Instead, use environment variables.</p><h3>Example</h3><pre>import os</pre><pre>SECRET_KEY = os.getenv(&quot;SECRET_KEY&quot;)<br>DATABASE_URL = os.getenv(&quot;DATABASE_URL&quot;)</pre><p>Environment variables are commonly used for:</p><ul><li>Django SECRET_KEY</li><li>Database credentials</li><li>API keys</li><li>Debug configuration</li></ul><p>This is a critical security practice in production systems.</p><h3>11. Python Logging</h3><p>Professional applications avoid using print() for debugging.</p><p>Instead, Python provides a powerful logging system.</p><h3>Example</h3><pre>import logging</pre><pre>logger = logging.getLogger(__name__)</pre><pre>logger.info(&quot;User logged in&quot;)<br>logger.warning(&quot;High memory usage&quot;)<br>logger.error(&quot;Payment failed&quot;)</pre><p>Django integrates deeply with Python’s logging system, allowing centralized monitoring and debugging.</p><h3>12. Understanding Iterators</h3><p>An iterator is an object that produces values one at a time.</p><p>Python’s loops rely on the iterator protocol.</p><h3>Example</h3><pre>numbers = [1, 2, 3]</pre><pre>for n in numbers:<br>    print(n)</pre><p>Behind the scenes Python calls:</p><pre>iter(numbers)<br>next(iterator)</pre><p>Django QuerySets also use this lazy iteration model to efficiently retrieve database results.</p><h3>13. Virtual Environments</h3><p>Every Python project should use a virtual environment.</p><p>This isolates project dependencies and prevents conflicts.</p><h3>Standard Workflow</h3><pre>python -m venv venv</pre><p>Activate it:</p><p><strong>Mac/Linux</strong></p><pre>source venv/bin/activate</pre><p><strong>Windows</strong></p><pre>venv\Scripts\activate</pre><p>Install dependencies:</p><pre>pip install django</pre><p>Save dependencies:</p><pre>pip freeze &gt; requirements.txt</pre><p>Never commit the venv folder to version control — only commit requirements.txt.</p><h3>Advanced Python Concepts That Help You Master Django Faster</h3><p>Once you’re comfortable with the fundamentals, these advanced patterns will accelerate your Django development:</p><ul><li>List comprehensions for clean data transformations</li><li>Decorators for authentication and middleware</li><li>Generators for efficient data handling</li><li>JSON processing for APIs</li><li>Logging for debugging production systems</li><li>Environment variables for secure deployments</li></ul><p>Mastering these concepts makes Django feel natural rather than confusing.</p><h3>Final Thoughts</h3><p>Django is often described as:</p><blockquote>“The web framework for perfectionists with deadlines.</blockquote><p>But it rewards developers who have strong Python fundamentals.</p><p>Every concept in this article appears in real Django code — often within the first week of building a serious project.</p><p>The best Django developers are not just framework users.</p><p>They are <strong>Python developers first</strong>.</p><p>Build the foundation.</p><p>Then let Django do what it does best: help you build powerful web applications quickly and confidently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baa616c20212" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Essentials for Django & Django REST Framework Developers]]></title>
            <link>https://medium.com/@bharathofficial05/python-essentials-for-django-django-rest-framework-developers-4ddc9a6e8795?source=rss-5fa5ae546213------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ddc9a6e8795</guid>
            <category><![CDATA[python-essentials]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-framework]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 10:21:00 GMT</pubDate>
            <atom:updated>2026-03-04T10:21:00.713Z</atom:updated>
            <content:encoded><![CDATA[<p>If you want to work professionally with <strong>Django</strong> and <strong>Django REST Framework</strong>, you don’t need to master every corner of Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWSDoGuyPSaIE3skRbg1hg.png" /></figure><p>You need to master the parts of Python that are actually used in real-world backend development.</p><p>This article focuses only on the <strong>operators, functions, and Python features</strong> that you’ll use daily when building APIs with:</p><ul><li>Django</li><li>Django REST Framework</li></ul><p>If you’re coming from JavaScript, think of this as:</p><blockquote><em>The 20% of Python that powers 80% of your Django backend.</em></blockquote><h3>1. Variables and Data Types (Used Everywhere)</h3><p>In Django apps, you constantly deal with:</p><ul><li>Strings (usernames, emails)</li><li>Integers (IDs, counts)</li><li>Floats (prices)</li><li>Booleans (is_active)</li><li>Lists (query results)</li><li>Dictionaries (JSON data)</li></ul><pre>name = &quot;Bharath&quot;<br>age = 25<br>price = 199.99<br>is_active = True</pre><p>DRF converts Python dictionaries into JSON responses.</p><pre>data = {<br>    &quot;name&quot;: &quot;Product 1&quot;,<br>    &quot;price&quot;: 500<br>}</pre><p>If you understand JavaScript objects, Python dictionaries will feel very familiar.</p><h3>2. Python Operators (Used in Business Logic)</h3><h3>Arithmetic Operators</h3><pre>total = price * quantity<br>discounted = total - 100</pre><p>Used in:</p><ul><li>Pricing logic</li><li>Calculations</li><li>Aggregations</li></ul><h3>Comparison Operators</h3><pre>if user.age &gt; 18:<br>    print(&quot;Adult&quot;)</pre><p>Common in:</p><ul><li>Permission checks</li><li>Filtering logic</li><li>Validation</li></ul><h3>Logical Operators</h3><pre>if user.is_active and user.is_staff:<br>    print(&quot;Admin access&quot;)</pre><p>Used heavily in:</p><ul><li>Custom permissions</li><li>Conditional logic</li><li>Access control</li></ul><h3>Membership Operator (in)</h3><p>Very common in Django:</p><pre>if role in [&quot;admin&quot;, &quot;manager&quot;]:<br>    allow_access = True</pre><p>You’ll also see it in QuerySets and filters.</p><h3>Identity Operator (is)</h3><p>Used for checking None:</p><pre>if user is None:<br>    return Response({&quot;error&quot;: &quot;User not found&quot;})</pre><p>In Django, always check None using is, not ==.</p><h3>3. Functions (Core to Django Development)</h3><p>Functions are everywhere in Django:</p><ul><li>Views</li><li>Utility helpers</li><li>Business logic</li></ul><p>Basic example:</p><pre>def calculate_tax(price):<br>    return price * 0.18</pre><p>In Django views:</p><pre>def product_list(request):<br>    return JsonResponse({&quot;message&quot;: &quot;Hello&quot;})</pre><p>Functions are first-class citizens in Python — just like JavaScript.</p><h3>4. Classes (Django Is Class-Based)</h3><p>Django is heavily class-oriented.</p><p>Models:</p><pre>class Product(models.Model):<br>    name = models.CharField(max_length=100)</pre><p>DRF ViewSets:</p><pre>class ProductViewSet(viewsets.ModelViewSet):<br>    queryset = Product.objects.all()</pre><p>If you understand ES6 classes, this is straightforward.</p><h3>5. List Comprehensions (Very Common)</h3><p>Instead of:</p><pre>names = []<br>for user in users:<br>    names.append(user.name)</pre><p>You write:</p><pre>names = [user.name for user in users]</pre><p>Used frequently when:</p><ul><li>Formatting API responses</li><li>Transforming data</li><li>Filtering objects</li></ul><h3>6. Dictionary Operations (Important for APIs)</h3><p>DRF serializers and responses use dictionaries.</p><p>Accessing values:</p><pre>data[&quot;email&quot;]</pre><p>Using .get() (safer):</p><pre>email = data.get(&quot;email&quot;)</pre><p>.get() prevents errors if key doesn’t exist.</p><p>This is commonly used when handling request data:</p><pre>request.data.get(&quot;username&quot;)</pre><h3>7. Exception Handling (Critical in APIs)</h3><p>In production APIs, error handling is mandatory.</p><pre>try:<br>    user = User.objects.get(id=1)<br>except User.DoesNotExist:<br>    return Response({&quot;error&quot;: &quot;User not found&quot;})</pre><p>Without proper exception handling:</p><ul><li>Your API crashes</li><li>You expose internal errors</li></ul><p>This is heavily used in Django views.</p><h3>8. Import Statements</h3><p>Every Django file starts with imports:</p><pre>from django.db import models<br>from rest_framework import serializers</pre><p>Unlike JavaScript:</p><ul><li>No default exports</li><li>No named exports confusion</li><li>Very clean module system</li></ul><h3>9. Decorators (Used Frequently in Django)</h3><p>Decorators modify functions.</p><p>Example:</p><pre>@login_required<br>def dashboard(request):<br>    ...</pre><p>In DRF:</p><pre>@api_view([&quot;GET&quot;])<br>def product_list(request):<br>    ...</pre><p>Decorators are extremely important in Django.</p><p>Think of them like middleware attached to a function.</p><h3>10. Lambda Functions (Sometimes Used)</h3><p>Small anonymous functions:</p><pre>sorted_users = sorted(users, key=lambda user: user.age)</pre><p>Used occasionally in:</p><ul><li>Sorting</li><li>Filtering</li><li>Query manipulation</li></ul><h3>11. QuerySets (Very Important in Django)</h3><p>QuerySets behave like Python lists, but they represent database queries.</p><pre>users = User.objects.all()</pre><p>Filtering:</p><pre>active_users = User.objects.filter(is_active=True)</pre><p>They support:</p><ul><li>Chaining</li><li>Lazy evaluation</li><li>Aggregations</li></ul><p>Understanding Python iteration helps here.</p><h3>12. Virtual Environments (Essential Practice)</h3><p>Python projects use virtual environments.</p><p>Equivalent to:</p><ul><li>node_modules</li><li>package isolation</li></ul><p>Command:</p><pre>python -m venv venv</pre><p>This keeps project dependencies isolated.</p><h3>13. Indentation (Python’s Biggest Difference)</h3><p>Python does not use {} like JavaScript.</p><p>It uses indentation:</p><pre>if user.is_active:<br>    print(&quot;Active&quot;)</pre><p>Indentation defines scope.</p><p>This feels strange initially but becomes clean and readable over time.</p><h3>14. Truthy and Falsy Values</h3><p>Very similar to JavaScript.</p><p>Falsy in Python:</p><ul><li>None</li><li>False</li><li>0</li><li>“”</li><li>[]</li><li>{}</li></ul><p>Example:</p><pre>if not users:<br>    print(&quot;No users found&quot;)</pre><p>Used often in:</p><ul><li>Validation</li><li>Query checks</li><li>Response handling</li></ul><h3>15. Common Built-in Functions You’ll Use</h3><h3>len()</h3><pre>len(users)</pre><h3>type()</h3><pre>type(user)</pre><h3>isinstance()</h3><pre>isinstance(user, User)</pre><h3>enumerate()</h3><pre>for index, user in enumerate(users):<br>    print(index, user.name)</pre><p>These are used constantly in backend logic.</p><h3>What You Actually Use Daily in Django/DRF</h3><p>If we summarize:</p><p>Most used Python features in Django:</p><ul><li>Classes</li><li>Functions</li><li>if/else</li><li>try/except</li><li>Dictionary operations</li><li>List comprehensions</li><li>Imports</li><li>Basic operators</li><li>QuerySet filtering</li><li>Decorators</li></ul><p>You rarely need:</p><ul><li>Advanced functional programming</li><li>Complex inheritance</li><li>Metaclasses</li><li>Low-level Python internals</li></ul><h3>Final Thoughts</h3><p>If you’re learning Django and Django REST Framework, focus on:</p><ul><li>Clean function writing</li><li>Understanding classes</li><li>Exception handling</li><li>Dictionary and list manipulation</li><li>QuerySet logic</li></ul><p>Python in Django is not about clever tricks.</p><p>It’s about readable, maintainable, and structured backend code.</p><p>Master these fundamentals, and you’ll feel confident building production APIs with Django.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ddc9a6e8795" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django & Django REST Framework — Explained for JavaScript Developers]]></title>
            <link>https://medium.com/@bharathofficial05/django-django-rest-framework-explained-for-javascript-developers-eabb315f8214?source=rss-5fa5ae546213------2</link>
            <guid isPermaLink="false">https://medium.com/p/eabb315f8214</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 16:43:11 GMT</pubDate>
            <atom:updated>2026-03-03T16:43:11.565Z</atom:updated>
            <content:encoded><![CDATA[<p>If you come from a JavaScript background (Node.js, Express, React, Next.js), Django and Django REST Framework might initially feel very different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udRCRhEjQd3Y6ug588AZlQ.png" /></figure><p>But once you map the concepts, you’ll realize they solve the same problems — just with stronger structure and more built-in tools.</p><p>Let’s translate Django into JavaScript terms.</p><h3>What is Django?</h3><p>Django is a full-stack backend framework written in Python.</p><p>If you’re a JS developer, think of Django as:</p><blockquote><em>Express + Sequelize + Admin Panel + Auth System + Security Middleware — all built-in and opinionated.</em></blockquote><p>Unlike Express, where you assemble everything manually, Django gives you a predefined architecture.</p><h3>Django vs Express (Concept Mapping)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*ShqH0yg-OoYaRDbGqIv0ng.png" /></figure><p>With Django, you don’t need to install five separate packages just to get started.</p><h3>Understanding Django’s Architecture (For JS Devs)</h3><p>Django follows something called <strong>MVT (Model–View–Template)</strong>.</p><p>If you’re used to MVC:</p><ul><li>Model = Same as in Node ORM</li><li>View = Like a controller</li><li>Template = Server-rendered UI (similar to EJS or Handlebars)</li></ul><p>If you’re building APIs only, you’ll mostly deal with:</p><ul><li>Models (database)</li><li>Views (logic)</li><li>URLs (routing)</li></ul><h3>Database Handling (Like Prisma or Sequelize)</h3><p>In Node, you might define a model like:</p><pre>const User = sequelize.define(&quot;User&quot;, {<br>  name: DataTypes.STRING,<br>  email: DataTypes.STRING<br>});</pre><p>In Django:</p><pre>class User(models.Model):<br>    name = models.CharField(max_length=100)<br>    email = models.EmailField()</pre><p>Django’s ORM automatically:</p><ul><li>Creates SQL queries</li><li>Handles migrations</li><li>Protects against SQL injection</li></ul><p>It’s similar to Prisma in developer experience.</p><h3>Built-in Admin Panel (Huge Advantage)</h3><p>One of Django’s biggest advantages:</p><p>It automatically generates an admin dashboard for your models.</p><p>You define a model → register it → you instantly get:</p><ul><li>CRUD UI</li><li>Search</li><li>Filters</li><li>Permissions</li></ul><p>No need to build a custom admin panel like you would in React + Node.</p><h3>What is Django REST Framework?</h3><p>Django REST Framework (DRF) is an extension built on top of Django for building APIs.</p><p>If Django is like Express, DRF is like:</p><blockquote><em>Express + automatic request validation + built-in serialization + API testing UI</em></blockquote><p>DRF is used when:</p><ul><li>React frontend needs APIs</li><li>React Native app needs backend</li><li>You’re building microservices</li></ul><h3>Core DRF Concepts (JS Comparison)</h3><h4>1. Serializers (Like Validation + DTO)</h4><p>In Node, you might use:</p><ul><li>Joi</li><li>Zod</li><li>class-validator</li></ul><p>In DRF, serializers:</p><ul><li>Validate input</li><li>Convert JSON to Python objects</li><li>Convert Python objects to JSON</li></ul><p>Example:</p><pre>class ProductSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Product<br>        fields = &quot;__all__&quot;</pre><p>This replaces:</p><ul><li>Manual validation</li><li>Manual JSON transformation</li><li>Manual response formatting</li></ul><h4>2. ViewSets (Like Express Route Controllers Combined)</h4><p>Instead of writing:</p><pre>router.get(&quot;/products&quot;)<br>router.post(&quot;/products&quot;)<br>router.put(&quot;/products/:id&quot;)<br>router.delete(&quot;/products/:id&quot;)</pre><p>You write one class:</p><pre>class ProductViewSet(viewsets.ModelViewSet):<br>    queryset = Product.objects.all()<br>    serializer_class = ProductSerializer</pre><p>You get full CRUD automatically.</p><h4>3. Routing (Cleaner Than Express)</h4><p>In Express:</p><pre>app.use(&quot;/api/products&quot;, productRoutes);</pre><p>In DRF:</p><pre>router = DefaultRouter()<br>router.register(&quot;products&quot;, ProductViewSet)</pre><p>Done. All routes are generated automatically.</p><h3>Authentication (Compared to Node)</h3><p>In Node, you usually install:</p><ul><li>jsonwebtoken</li><li>bcrypt</li><li>passport</li><li>custom middleware</li></ul><p>In Django:</p><ul><li>User model is built-in</li><li>Password hashing is automatic</li><li>Permissions system exists</li><li>Admin role management exists</li></ul><p>DRF supports:</p><ul><li>Token authentication</li><li>JWT (via extensions)</li><li>Session authentication</li></ul><p>Access control can be defined at:</p><ul><li>Global level</li><li>View level</li><li>Object level</li></ul><p>Much more structured than typical Express setups.</p><h3>Security</h3><p>In Express, you manually configure:</p><ul><li>Helmet</li><li>CORS</li><li>CSRF</li><li>SQL injection protection</li></ul><p>In Django, many protections are enabled by default:</p><ul><li>CSRF protection</li><li>SQL injection prevention</li><li>XSS protection</li><li>Secure password hashing</li></ul><p>Security-first design is one of Django’s strongest advantages.</p><h3>Django vs Node (Philosophy Difference)</h3><h3>Node / Express</h3><ul><li>Minimal</li><li>Flexible</li><li>You assemble everything</li><li>You control structure</li></ul><h3>Django</h3><ul><li>Opinionated</li><li>Structured</li><li>Batteries included</li><li>Less setup, more productivity</li></ul><p>If you’re building a startup MVP, Django can save weeks of setup time.</p><p>If you’re building a highly customized microservice architecture, Node might feel more flexible.</p><h3>Real-World Stack (For JS Developers)</h3><p>Modern architecture example:</p><p>Frontend:</p><ul><li>React</li><li>Next.js</li><li>React Native</li></ul><p>Backend:</p><ul><li>Django</li><li>Django REST Framework</li></ul><p>Database:</p><ul><li>PostgreSQL</li></ul><p>Deployment:</p><ul><li>Docker</li><li>AWS</li></ul><p>Django handles:</p><ul><li>Business logic</li><li>Database</li><li>Authentication</li><li>Admin</li></ul><p>DRF exposes:</p><ul><li>JSON APIs</li><li>Token-based auth</li><li>Role-based permissions</li></ul><h3>When Should a JS Developer Choose Django?</h3><p>Choose Django + DRF if:</p><ul><li>You want strong structure</li><li>You’re tired of configuring everything manually</li><li>You need built-in authentication</li><li>You want a ready-to-use admin dashboard</li><li>You’re building SaaS or enterprise apps</li></ul><p>Avoid it if:</p><ul><li>You prefer minimal frameworks</li><li>You want complete architectural freedom</li><li>Your team is entirely JavaScript-focused</li></ul><h3>Mental Model for JS Developers</h3><p>Think of Django as:</p><p>A production-ready backend framework where most decisions are already made for you.</p><p>Think of DRF as:</p><p>A powerful API layer that reduces boilerplate and enforces clean architecture.</p><p>If you understand:</p><ul><li>Express</li><li>Prisma or Sequelize</li><li>Middleware</li><li>JWT authentication</li><li>REST APIs</li></ul><p>Then learning Django and DRF is mostly about learning new syntax — not new concepts.</p><h3>Final Takeaway</h3><p>For a JavaScript developer:</p><p>Django is not “better” than Node.<br> It’s a different philosophy.</p><p>Node gives you flexibility.<br> Django gives you structure.</p><p>Django REST Framework gives you production-ready APIs with minimal boilerplate.</p><p>If you’re expanding beyond the JavaScript ecosystem, Django + DRF is one of the most mature and stable backend stacks you can learn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eabb315f8214" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Explained for Beginners: Why It’s One of the Most Loved Programming Languages]]></title>
            <link>https://medium.com/@bharathofficial05/python-explained-for-beginners-why-its-one-of-the-most-loved-programming-languages-91bf9e07c67c?source=rss-5fa5ae546213------2</link>
            <guid isPermaLink="false">https://medium.com/p/91bf9e07c67c</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 15:45:17 GMT</pubDate>
            <atom:updated>2026-03-02T15:45:17.974Z</atom:updated>
            <content:encoded><![CDATA[<p>Python is a <strong>high-level, interpreted, interactive, and object-oriented programming language</strong> designed with one core principle in mind:</p><blockquote><strong><em>Readability and simplicity above everything else.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pqmbXTetnp6N-9cF56D9w.png" /></figure><p>Unlike many other languages that rely heavily on symbols and complex syntax, Python uses <strong>English-like keywords</strong> and minimal punctuation. This makes it extremely approachable for beginners while still being powerful enough for large-scale systems.</p><p>Let’s break down what makes Python so special.</p><h3>🚀 What Makes Python Unique?</h3><h3>1️⃣ Python is High-Level and Interpreted</h3><p>Python is a <strong>high-level language</strong>, meaning you don’t have to worry about low-level details like memory management.</p><p>It is also <strong>interpreted</strong>, which means:</p><ul><li>Code is executed line-by-line at runtime</li><li>No separate compilation step is required</li><li>Easier debugging and faster development</li></ul><p>Unlike compiled languages (like C or C++), Python allows you to:</p><ul><li>Write code</li><li>Run it immediately</li><li>See results instantly</li></ul><p>This makes Python perfect for experimentation and learning.</p><h3>2️⃣ Python is Interactive (REPL)</h3><p>Python comes with an interactive shell based on <strong>REPL (Read — Evaluate — Print — Loop)</strong>.</p><p>You can open Python and directly type:</p><pre>&gt;&gt;&gt; 2 * 3 + 1<br>7</pre><pre>&gt;&gt;&gt; print(&quot;Hello World&quot;)<br>Hello World</pre><p>This makes Python:</p><ul><li>Great for beginners</li><li>Perfect for testing small code snippets</li><li>Ideal for learning new libraries</li></ul><p>You can experiment in real time.</p><h3>3️⃣ Python is Object-Oriented (and More)</h3><p>Python supports multiple programming paradigms:</p><ul><li>✅ Object-Oriented Programming (OOP)</li><li>✅ Imperative Programming</li><li>✅ Structured Programming</li><li>✅ Functional Programming</li></ul><p>In Python, <strong>everything is an object</strong>.</p><p>But the best part?</p><p>You are free to write code in:</p><ul><li>Object-oriented style</li><li>Procedural style</li><li>Functional style</li><li>Or even mix them</li></ul><p>This flexibility makes Python extremely powerful.</p><h3>Open Source and Cross-Platform</h3><p>Python is:</p><ul><li>✅ Open Source</li><li>✅ Free to download</li><li>✅ Cross-platform</li></ul><p>You can run Python on:</p><ul><li>Windows</li><li>Linux</li><li>macOS</li><li>Android</li></ul><p>It is distributed under the <strong>Python Software Foundation License</strong>, which is compatible with GNU GPL.</p><p>The reference implementation of Python is called <strong>CPython</strong>, written in C.</p><p>Python first compiles your code into <strong>bytecode</strong>, which runs on a virtual machine. That’s what makes it portable across operating systems.</p><h3>📜 The Design Philosophy: The Zen of Python</h3><p>Python isn’t just a language — it’s a philosophy.</p><p>Its guiding principles are captured in <strong>The Zen of Python</strong>.</p><p>If you type:</p><pre>&gt;&gt;&gt; import this</pre><p>You’ll see 19 aphorisms like:</p><ul><li>Beautiful is better than ugly.</li><li>Explicit is better than implicit.</li><li>Simple is better than complex.</li><li>Readability counts.</li><li>There should be one — and preferably only one — obvious way to do it.</li><li>Errors should never pass silently.</li><li>Now is better than never.</li></ul><p>These principles shape how Python code should be written.</p><h3>🧠 What is Pythonic Code?</h3><p>Writing Python that merely works is not enough.</p><p>Good Python code should be:</p><ul><li>Clean</li><li>Simple</li><li>Explicit</li><li>Readable</li><li>Maintainable</li></ul><p>This is called <strong>Pythonic Code Style</strong>.</p><p>Python encourages developers to write code that is:</p><ul><li>Easy to explain</li><li>Easy to read</li><li>Easy to maintain</li></ul><p>If code is hard to explain, the Zen suggests — it might be a bad idea.</p><h3>⭐ Important Features of Python</h3><p>Let’s explore the most important features that make Python powerful.</p><h3>1⃣ Easy to Learn</h3><p>This is the biggest reason for Python’s popularity.</p><p>Python has:</p><ul><li>Simple syntax</li><li>Very few keywords</li><li>No curly bracket clutter</li><li>Indentation-based structure</li><li>No need to declare variable types</li></ul><p>Example:</p><pre>x = 10<br>name = &quot;Bharath&quot;</pre><p>No type declaration required.</p><p>That’s why beginners love Python.</p><h3>2⃣ Dynamically Typed</h3><p>Python is dynamically typed.</p><p>You don’t need to specify the data type when declaring a variable.</p><p>The type is determined at runtime based on the value assigned.</p><p>Example:</p><pre>x = 10      # integer<br>x = &quot;Hello&quot; # now it&#39;s a string</pre><p>This reduces complexity and speeds up development.</p><h3>3⃣ Interpreter-Based Execution</h3><p>In compiler-based languages:</p><ul><li>The entire program must compile successfully.</li><li>A single error can stop compilation.</li></ul><p>In Python:</p><ul><li>Code executes line-by-line.</li><li>Statements before the error are executed.</li><li>Debugging is easier.</li></ul><p>This makes Python extremely beginner-friendly.</p><h3>4⃣ Multi-Paradigm Support</h3><p>Python supports:</p><ul><li>Object-Oriented Programming</li><li>Procedural Programming</li><li>Functional Programming</li></ul><p>You can choose what best fits your problem.</p><h3>5⃣ “Batteries Included” Standard Library</h3><p>Python comes with a massive standard library.</p><p>This means: No need to install external packages for common tasks</p><p>Built-in modules for:</p><ul><li>File handling</li><li>JSON</li><li>Networking</li><li>Data compression</li><li>Date &amp; time</li><li>Math operations</li></ul><p>Popular Python libraries include:</p><ul><li>NumPy</li><li>Pandas</li><li>Matplotlib</li><li>Tkinter</li><li>Math</li></ul><p>This “batteries included” philosophy saves massive development time.</p><h3>6⃣ GUI Application Support</h3><p>Python supports graphical applications through:</p><ul><li>Tkinter (standard GUI library)</li><li>PyQt</li><li>wxWidgets</li><li>PySimpleGUI</li></ul><p>You can build desktop applications easily.</p><h3>7⃣ Database Connectivity</h3><p>Python works with:</p><ul><li>MySQL</li><li>PostgreSQL</li><li>SQLite</li><li>Oracle</li><li>MongoDB (NoSQL)</li></ul><p>Through DB-API and third-party libraries, Python integrates easily with almost any database.</p><h3>8⃣ Extensible</h3><p>Python can integrate with:</p><ul><li>C</li><li>C++</li><li>Java</li><li>C#</li><li>COM</li><li>ActiveX</li><li>CORBA</li></ul><p>Since CPython is written in C, you can write C modules and plug them into Python.</p><p>There are other implementations too:</p><ul><li>Jython (Java-based)</li><li>IronPython (C# based)</li></ul><p>This makes Python highly extensible.</p><h3>9⃣ Automatic Garbage Collection</h3><p>Python automatically manages memory.</p><p>You don’t need to manually allocate or free memory.</p><p>This reduces bugs and improves safety.</p><h3>Active Developer Community</h3><p>Python has one of the largest developer communities in the world.</p><p>It is supported by:</p><ul><li>Python Software Foundation</li><li>Large open-source contributors</li><li>Major tech companies like Google, Microsoft, and Meta</li></ul><p>Because of this:</p><ul><li>Documentation is rich</li><li>Learning resources are abundant</li><li>Libraries are constantly improving</li></ul><h3>🧩 Python Enhancement Proposal (PEP)</h3><p>To maintain readability and evolve responsibly, Python uses the <strong>PEP (Python Enhancement Proposal)</strong> process.</p><p>Anyone can propose:</p><ul><li>New features</li><li>Improvements</li><li>Standard library additions</li></ul><p>This keeps Python structured and community-driven.</p><h3>Why Python is Perfect for Beginners</h3><p>Python supports building:</p><ul><li>Simple text-processing scripts</li><li>Automation tools</li><li>Web applications</li><li>Data science projects</li><li>Machine learning systems</li><li>Games</li><li>Enterprise-level applications</li></ul><p>It grows with you.</p><p>You can start small and scale big.</p><h3>Final Thoughts</h3><p>Python isn’t just a programming language.</p><p>It’s a design philosophy centered around:</p><ul><li>Simplicity</li><li>Clarity</li><li>Readability</li><li>Practicality</li></ul><p>If you are starting your programming journey, Python is not just a good choice — it’s one of the smartest choices you can make.</p><p>And remember:</p><blockquote><em>Code that works is good.<br> Code that is readable is better.<br> Code that is Pythonic is best.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91bf9e07c67c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every Python Beginner Needs to Know This First]]></title>
            <link>https://medium.com/@bharathofficial05/every-python-beginner-needs-to-know-this-first-c0330c70dbd6?source=rss-5fa5ae546213------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0330c70dbd6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 06:36:00 GMT</pubDate>
            <atom:updated>2026-02-27T06:36:00.964Z</atom:updated>
            <content:encoded><![CDATA[<p>Before you write a single line of Python, learn the tool that every developer uses every single day — the command line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YyGqN17PbiUkhvwPXdlzSA.png" /></figure><p>Here’s a scene most new Python learners know well. You’ve watched a tutorial, you’ve written your first script, and now you’re staring at a file called hello.py sitting on your Desktop. The tutorial says &quot;now just run it.&quot; But... how? Where? You open something called a terminal, a black window stares back at you, and suddenly the excitement drains away.</p><p>This is the moment where a lot of people quietly close the terminal and go back to running code inside an online sandbox — never quite understanding why “real” Python development feels different.</p><p>The answer is the <strong>command line</strong>. It’s not magic, it’s not only for hackers, and it’s not nearly as complicated as it looks. It’s just a text-based way to control your computer — and for Python developers, it’s the primary place where code actually gets <em>run</em>.</p><p>This guide will walk you through everything you need to know, starting from zero.</p><h3>Why Python and the Command Line Are Inseparable</h3><p>Think of Python as a chef, and the command line as the kitchen. You can admire recipes all day, but cooking actually happens in the kitchen.</p><p>When a Python developer wants to run a script, they type python hello.py in the terminal. When they need to install a library like pandas or requests, they type pip install pandas. When they&#39;re managing a project, setting up a virtual environment, or pushing code to GitHub — all of it flows through the command line.</p><p>You <em>can</em> avoid it for a while. Tools like IDLE, Jupyter Notebooks, or VS Code’s Run button let you execute Python without touching the terminal directly. But the moment you step outside those training wheels — deploying an app, collaborating on a real project, running automated tests — the command line is waiting for you. Learning it now means you’ll never be caught off guard later.</p><h3>What Exactly Is the Command Line?</h3><p>Your computer gives you two ways to interact with it.</p><p>The first is the <strong>graphical user interface (GUI)</strong> — everything you already know. Click a folder to open it. Drag a file to move it. Double-click an app to launch it. It’s visual, tactile, and friendly.</p><p>The second is the <strong>command line interface (CLI)</strong> — a plain text window where you type instructions and get text back. No icons. No drag-and-drop. No confirmation dialogs. Just a blinking cursor waiting for your next command.</p><p>You’ll hear it called different things: <strong>terminal</strong>, <strong>shell</strong>, <strong>console</strong>, <strong>prompt</strong>, or just the <strong>command line</strong>. These words have slightly different technical meanings, but in practice, developers use them interchangeably. Don’t let the vocabulary slow you down.</p><h3>Opening the Terminal</h3><h3>On Windows</h3><p>Windows has a built-in terminal called <strong>PowerShell</strong>. Click the search bar on your taskbar (next to the Windows button), type powershell, and press Enter. A dark blue window appears.</p><p>You’ll see something like:</p><pre>PS C:\Users\YourName&gt;</pre><p>PS stands for PowerShell. C:\Users\YourName is where you currently &quot;are&quot; on your computer — your home folder. The &gt; is where you type. Windows examples in this article use &gt; as the prompt.</p><h3>On macOS</h3><p>Mac’s terminal is called <strong>Terminal</strong>. Press <strong>Command + Space</strong>, type terminal, and hit Enter. Or find it in <strong>Applications → Utilities → Terminal</strong>.</p><p>You’ll see:</p><pre>YourMacBook:~ YourName%</pre><p>The % is your prompt. macOS examples in this article use %.</p><blockquote><strong><em>macOS note:</em></strong><em> If you see </em><em>$ instead of </em><em>%, your Mac is using an older shell called Bash. Most commands here still work, but look up how to switch to the default zsh shell when you get a chance.</em></blockquote><h3>The File System: How a Developer Thinks About It</h3><p>Before diving into commands, you need a mental model — and the best one for developers is to think of your file system as a <strong>project tree</strong>.</p><p>When a developer starts a new Python project, they create a folder structure like this:</p><pre>my-project/<br>├── src/<br>│   └── main.py<br>├── tests/<br>│   └── test_main.py<br>├── requirements.txt<br>└── README.md</pre><p>On the command line, you’re always <em>inside</em> one of those folders. Every command you run happens relative to where you currently are. Understanding how to move through this tree is the core skill of working on the command line.</p><h3>The Commands Every Python Developer Uses Daily</h3><h3>“Where am I?” — pwd and Get-Location</h3><p>The first thing you want to know when you open a terminal is where you are. Think of it like opening your code editor and needing to know which project folder is open.</p><pre># Windows<br>&gt; Get-Location</pre><pre>Path<br>----<br>C:\Users\YourName</pre><pre># macOS<br>% pwd<br>/Users/YourName</pre><p>pwd stands for <strong>print working directory</strong>. It tells you the full path of your current location. Developers run this constantly — especially when something isn&#39;t working and they realize they&#39;re in the wrong folder.</p><h3>“What’s in here?” — ls</h3><p>Once you know where you are, you want to see what’s around you. Just like browsing a project folder in VS Code’s file explorer, but in text form.</p><pre># Windows<br>&gt; ls</pre><pre># macOS<br>% ls<br>Desktop<br>Documents<br>Downloads<br>my-project</pre><p>Senior developers run ls almost as a reflex. Before running a Python script, they ls to confirm the file is actually there. Before installing anything, they ls to check the project structure. It&#39;s a tiny habit that prevents a lot of confusion.</p><h3>“Move me there.” — cd</h3><p>cd stands for <strong>change directory</strong>. It&#39;s how you navigate. If pwd is asking &quot;where am I?&quot;, cd is saying &quot;take me here.&quot;</p><pre># Windows<br>&gt; cd Desktop<br>&gt; Get-Location<br>C:\Users\YourName\Desktop</pre><pre># macOS<br>% cd Desktop<br>% pwd<br>/Users/YourName/Desktop</pre><p>There are three patterns you’ll use constantly:</p><p>Move <em>into</em> a folder:</p><pre>cd my-project</pre><p>Move <em>back</em> to the parent folder (the .. means &quot;one level up&quot;):</p><pre>cd ..</pre><p>Jump directly anywhere using the full path:</p><pre># macOS<br>% cd /Users/YourName/Documents/my-project</pre><pre># Windows<br>&gt; cd C:\Users\YourName\Documents\my-project</pre><blockquote><strong><em>The Tab key is your best friend.</em></strong><em> Type </em><em>cd my-p and press Tab — the terminal autocompletes to </em><em>cd my-project. Every experienced developer uses Tab constantly. It&#39;s faster and it prevents typos in file names that would cause your Python scripts to fail.</em></blockquote><h3>Setting Up a Python Project: A Real-World Walkthrough</h3><p>Here’s how this looks in practice. Imagine you’re starting a new Python project from scratch. This is exactly what you’d do on the command line:</p><p><strong>Step 1:</strong> Navigate to where you keep your projects.</p><pre>% cd Documents<br>% mkdir python-projects<br>% cd python-projects</pre><p>mkdir (<strong>make directory</strong>) creates a new folder. You just created a python-projects folder inside Documents and moved into it.</p><p><strong>Step 2:</strong> Create a folder for your specific project.</p><pre>% mkdir weather-app<br>% cd weather-app<br>% pwd<br>/Users/YourName/Documents/python-projects/weather-app</pre><p>You’re now inside your project folder. This is where your Python files will live. When you run python app.py later, you&#39;ll need to be in this exact folder.</p><p><strong>Step 3:</strong> Confirm everything looks right.</p><pre>% ls</pre><p>The folder is empty for now, but ls confirms you&#39;re in the right place. Once you create Python files here, they&#39;ll show up in this list.</p><h3>Moving and Copying Files</h3><p>Sometimes you need to reorganize. The mv command <strong>moves</strong> a file or folder:</p><pre>mv source destination</pre><p>Say you accidentally created a Python script in the wrong folder. You can move it:</p><pre>% mv app.py /Users/YourName/Documents/python-projects/weather-app</pre><p>The cp command <strong>copies</strong> — the original stays put and a copy appears in the new location. This is useful when you want to duplicate a project template without touching the original:</p><pre>% cp -r project-template new-project</pre><p>The -r flag means &quot;recursive&quot; — it copies the folder and everything inside it, not just the folder itself.</p><h3>Deleting Files and Folders — Read This Carefully</h3><p>This is the section that trips up beginners, so please read it slowly.</p><p>The rm command deletes files. To delete a folder and all its contents, you add the -r flag:</p><pre># Windows<br>&gt; rm -r old-project</pre><pre># macOS<br>% rm -r old-project</pre><p>Here’s what makes this different from dragging something to the Trash: <strong>there is no undo</strong>. No Trash can. No “are you sure?” dialog. No recovery. The moment you press Enter, the files are gone permanently.</p><p>Real developers — including very experienced ones — have accidentally deleted important work with rm. The habit that prevents this is simple: always run ls first, confirm you&#39;re deleting the right thing, and confirm you&#39;re in the right folder. Ten seconds of caution saves hours of pain.</p><p>Never run rm commands you found online without fully understanding what they do. A command like rm -rf / would attempt to delete your entire computer. The command line won&#39;t stop you.</p><h3>Running Python from the Command Line</h3><p>Now that you understand navigation, here’s the payoff — actually running Python.</p><p>Once you’re in the folder containing your Python file:</p><pre># macOS/Linux<br>% python3 hello.py</pre><pre># Windows<br>&gt; python hello.py</pre><p>That’s it. Python reads your script and runs it. The output appears right in the terminal.</p><p>If Python isn’t installed yet, or if the command returns an error, you can check by typing:</p><pre>% python3 --version<br>Python 3.11.4</pre><p>If you see a version number, Python is installed and ready. If you get an error, you need to install Python first — but that installation process also happens in the terminal, which is exactly why learning these navigation basics first matters.</p><h3>Installing Python Packages with pip</h3><p>Every Python developer eventually needs to install third-party libraries. pip is Python&#39;s package manager, and it runs from the command line:</p><pre># Install a single package<br>% pip install requests</pre><pre># Install multiple packages<br>% pip install pandas numpy matplotlib</pre><pre># Install everything a project needs (from a requirements file)<br>% pip install -r requirements.txt</pre><p>When a tutorial says “install this library,” this is what they mean. You type that command in your terminal, in your project folder, and pip fetches the package from the internet and installs it.</p><h3>Helpful Tricks Every Developer Knows</h3><p><strong>Clear the clutter.</strong> After running several commands, your terminal fills up. Type clear and press Enter for a fresh screen. Your history isn&#39;t deleted — it&#39;s just visually cleared.</p><p><strong>Reuse previous commands.</strong> Press the <strong>↑ up arrow</strong> to bring back your last command. Keep pressing to scroll through your history. This is huge — instead of retyping python3 manage.py runserver every time, just press up and Enter.</p><p><strong>Read the manual.</strong> Every command has built-in documentation:</p><pre># Windows<br>&gt; python/?</pre><pre># macOS<br>% man python3</pre><p><strong>Exit when you’re done.</strong></p><pre>&gt; exit</pre><h3>The Golden Rule: Never Blindly Paste Commands</h3><p>As you learn Python, you’ll constantly find commands on Stack Overflow, Reddit, GitHub issues, and YouTube comments. Here is advice that every senior developer wishes they’d heard earlier: <strong>read and understand a command before you run it</strong>.</p><p>The command line doesn’t ask for confirmation. It doesn’t protect you. A wrong rm command deletes your project. A compromised install script can do far worse. The terminal trusts you completely, which means you have to be the careful one.</p><p>When you find a command you don’t recognize, take thirty seconds to search for what it does. The man command is there for exactly this purpose. With Python-specific commands, a quick search of the official docs usually clears things up immediately.</p><h3>Practice Exercise: Set Up Your First Python Project Folder</h3><p>Work through this from start to finish. It takes about two minutes and covers everything in this guide:</p><ol><li>Open your terminal</li><li>Check where you are: pwd (macOS) or Get-Location (Windows)</li><li>Navigate to your Desktop: cd Desktop</li><li>Create a project folder: mkdir my-first-python-project</li><li>Move into it: cd my-first-python-project</li><li>Confirm your location: pwd</li><li>Check it’s empty: ls</li><li>Go back up: cd ..</li><li>List files to see your new folder: ls</li><li>Clean up: rm -r my-first-python-project</li></ol><p>You just created a project workspace the same way professional Python developers do every time they start something new. The only difference is they’d keep the folder and start putting .py files in it.</p><h3>What to Learn Next</h3><p>You now know the foundation. From here, the natural next steps for a Python developer are:</p><p><strong>Virtual environments</strong> — Python projects isolate their dependencies using venv. You create and activate them entirely from the command line.</p><p><strong>Git</strong> — Version control is how you track changes to your code and collaborate with others. Every git command runs in the terminal.</p><p><strong>Running scripts automatically</strong> — Once you’re comfortable, you can write shell scripts that chain commands together, automating setup tasks that would otherwise take you ten minutes every time.</p><p><strong>Connecting to servers</strong> — When you eventually deploy a Python app to the cloud, you’ll ssh into a remote machine and manage it entirely through the command line. What feels foreign today becomes second nature.</p><p>The command line is not a detour on the way to learning Python. It’s part of the same journey. The developers who get comfortable here early are the ones who feel confident later, when things get more complex and the terminal is the only tool available.</p><p>Open it. Type a command. See what happens. That’s how it starts.</p><p><em>Want to go deeper? For Windows users, </em><strong><em>PowerShell for SysAdmins</em></strong><em> is excellent. For macOS and Linux, check out </em><strong><em>The Linux Command Line</em></strong><em>. And for a full reference of every shell command available, ss64.com is a bookmark worth keeping.</em></p><p><em>Found this useful? Hit the clap button — it helps other Python beginners find this guide when they need it most.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0330c70dbd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Django in 2026]]></title>
            <link>https://medium.com/@bharathofficial05/getting-started-with-django-in-2026-63fd4fe53100?source=rss-5fa5ae546213------2</link>
            <guid isPermaLink="false">https://medium.com/p/63fd4fe53100</guid>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 07:21:00 GMT</pubDate>
            <atom:updated>2026-02-26T07:21:00.667Z</atom:updated>
            <content:encoded><![CDATA[<p>A Modern Developer’s Guide to Building Scalable Web Applications with Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ae5m46VdX5tEvXMpUZcJbA.png" /></figure><p>If you’re a developer looking to build scalable, production-ready web applications in Python, <strong>Django</strong> remains one of the strongest choices in 2026.</p><p>Whether you’re a beginner building your first CRUD app or an experienced developer comparing frameworks like Flask and FastAPI, Django’s “batteries-included” philosophy gives you structure, speed, and security out of the box.</p><p>As the official tagline says:</p><blockquote>“The web framework for perfectionists with deadlines.”</blockquote><p>Let’s break down what Django is, why it’s still relevant, and how it works under the hood.</p><h3>What is Django?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8nTyLQgCObCMCbug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/0*stHB3M30UU16Nqiv.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GFLh3wlyuoyjx1Y3.jpeg" /></figure><p>Django is a high-level Python web framework that handles the complex and repetitive parts of web development so you can focus on building product features.</p><p>It was originally developed in the early 2000s at the Lawrence Journal-World newspaper and named after jazz guitarist Django Reinhardt. It was open-sourced in 2005 and is now maintained by the Django Software Foundation.</p><p>Today, Django powers applications at scale for companies like:</p><ul><li>Instagram</li><li>YouTube</li><li>Spotify</li><li>Dropbox</li></ul><h3>Django in 2026: What’s New?</h3><p>The Django ecosystem continues to evolve with regular releases (minor releases every ~8 months and LTS versions every few years).</p><h4>🚀 Recent Improvements (Django 4.2 LTS → 5.x Series)</h4><ul><li>Better async support (async views, async ORM improvements)</li><li>Improved database performance and query optimization</li><li>Enhanced security defaults</li><li>More robust form rendering APIs</li><li>Better type hint support</li><li>Performance improvements in template rendering</li><li>Continued PostgreSQL enhancements</li><li>Stronger support for modern frontend integration (HTMX, Alpine, React hybrid setups)</li></ul><p>Django 5.x fully embraces modern Python versions and continues pushing toward async-first architecture while maintaining backward compatibility.</p><h3>Why Use Django?</h3><p>Django’s biggest advantage? You get everything you need out of the box.</p><ul><li><strong>ORM (Object-Relational Mapper)</strong><br> Write Python instead of SQL.</li><li><strong>Auto-generated Admin Interface</strong><br> Instant CRUD dashboard for your models.</li><li><strong>Authentication System</strong><br> Login, logout, password hashing, permissions, sessions.</li><li><strong>URL Routing</strong><br> Clean, readable URL patterns.</li><li><strong>Forms System</strong><br> Validation, CSRF protection, error handling.</li><li><strong>Security Features</strong><br> Protection against:</li><li>SQL Injection</li><li>XSS</li><li>CSRF</li><li>Clickjacking</li><li><strong>Internationalization (i18n)</strong><br> Built-in multilingual support.</li><li><strong>Documentation</strong><br> Django documentation is widely considered best-in-class.</li></ul><h3>Prerequisites Before Learning Django</h3><p>You don’t need to be an expert, but you should know:</p><ul><li>Python basics (functions, classes, imports)</li><li>OOP fundamentals</li><li>HTML &amp; CSS</li><li>Basic JavaScript</li><li>How HTTP works</li><li>Basic database concepts</li></ul><p>Pro tip:<br> Don’t try to “master everything first.” Start building and learn contextually.</p><h3>Django Architecture: MVT Pattern</h3><p>Django follows a variant of MVC called <strong>Model–View–Template (MVT).</strong></p><h4>- Models</h4><p>Represent database structure.</p><h4>- Views</h4><p>Handle business logic.</p><h4>- Templates</h4><p>Render UI.</p><h3>Request–Response Cycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*mUHTKHSO7tqXTUGq.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hM8rAXgOpH-j73lw" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*uNvINzRPyb6viNHe.png" /></figure><p>Here’s what happens when a user visits your site:</p><ol><li>User sends an HTTP request</li><li>URL dispatcher maps it to a view</li><li>View fetches data from models</li><li>Template renders HTML</li><li>Response is returned to the browser</li></ol><p>Simple. Clean. Predictable.</p><h3>Django Project Structure</h3><p>Django promotes modular design.</p><pre>project_name/<br>    manage.py<br>    project_name/<br>    app1/<br>    app2/<br>    app3/</pre><h4>Key Idea:</h4><ul><li><strong>One Project</strong></li><li>Multiple <strong>Apps</strong></li><li>Each app = one responsibility</li></ul><p>Example:</p><ul><li>accounts app → authentication</li><li>articles app → blog posts</li><li>payments app → billing logic</li></ul><p>This makes large codebases manageable.</p><h3>Models: Defining Data</h3><p>Django’s ORM lets you define database tables in Python.</p><pre># models.py<br>from django.db import models</pre><pre>class Article(models.Model):<br>    title = models.CharField(max_length=100)<br>    content = models.TextField()<br>    pub_date = models.DateTimeField(auto_now_add=True)</pre><p>Behind the scenes:</p><ul><li>Django converts this into SQL</li><li>Handles migrations</li><li>Manages relationships</li><li>Provides query APIs</li></ul><p>Example query:</p><pre>Article.objects.filter(title__icontains=&quot;Django&quot;)</pre><p>Clean and expressive.</p><h3>URLs: Clean Routing</h3><pre># urls.py<br>from django.urls import path<br>from .views import HomePageView, ArticleListView, ArticleDetailView</pre><pre>urlpatterns = [<br>    path(&quot;&quot;, HomePageView.as_view(), name=&quot;homepage&quot;),<br>    path(&quot;articles/&quot;, ArticleListView.as_view(), name=&quot;article-list&quot;),<br>    path(&quot;articles/&lt;int:pk&gt;/&quot;, ArticleDetailView.as_view(), name=&quot;article-detail&quot;),<br>]</pre><p>URLs are readable and REST-friendly.</p><h3>Views: Business Logic</h3><p>Django offers:</p><ul><li>Function-based views</li><li>Class-based views</li><li>Generic views</li></ul><p>Example:</p><pre>from django.views.generic import TemplateView, ListView, DetailView<br>from .models import Article</pre><pre>class HomePageView(TemplateView):<br>    template_name = &quot;home.html&quot;</pre><pre>class ArticleListView(ListView):<br>    model = Article<br>    template_name = &quot;article_list.html&quot;</pre><pre>class ArticleDetailView(DetailView):<br>    model = Article<br>    template_name = &quot;article_detail.html&quot;</pre><p>Minimal code. Maximum output.</p><h3>Templates: Dynamic HTML</h3><p>Django templates mix logic and presentation safely.</p><pre>&lt;h1&gt;All Articles&lt;/h1&gt;<br>{% for article in article_list %}<br>  &lt;div&gt;<br>    &lt;h2&gt;{{ article.title }} | {{ article.pub_date }}&lt;/h2&gt;<br>    &lt;p&gt;{{ article.content }}&lt;/p&gt;<br>  &lt;/div&gt;<br>{% endfor %}</pre><p>You can also:</p><ul><li>Switch to Jinja2</li><li>Integrate HTMX</li><li>Use Django as API backend with React/Vue</li></ul><h3>Django vs Flask (Quick Comparison)</h3><p>Flask is minimal and flexible.<br>Django is structured and complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*UcrphAz5p0lfQAaFYMXLog.png" /></figure><p>Choose:</p><ul><li><strong>Django</strong> → Large projects, teams, scalability</li><li><strong>Flask</strong> → Lightweight APIs, microservices</li></ul><h3>Is Django Still Worth Learning in 2026?</h3><p>Absolutely.</p><p>Reasons:</p><ul><li>Mature ecosystem</li><li>Massive job market</li><li>Enterprise adoption</li><li>Clean architecture</li><li>Security-first approach</li><li>Excellent for SaaS products</li><li>Great with PostgreSQL</li><li>Works beautifully with modern JS frontends</li></ul><p>With async improvements and ongoing modernization, Django is not legacy — it’s evolving.</p><h3>Final Thoughts</h3><p>Django isn’t just a framework.</p><p>It’s:</p><ul><li>A philosophy</li><li>A community</li><li>A productivity accelerator</li></ul><p>If you want to build real-world applications fast without sacrificing architecture, Django is one of the best tools you can learn in 2026.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63fd4fe53100" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>