<?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 Naufal Ichsan on Medium]]></title>
        <description><![CDATA[Stories by Naufal Ichsan on Medium]]></description>
        <link>https://medium.com/@naufalichsan?source=rss-32d132a20d81------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*umwAvyhEFAS98SmBcTDoSw.jpeg</url>
            <title>Stories by Naufal Ichsan on Medium</title>
            <link>https://medium.com/@naufalichsan?source=rss-32d132a20d81------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:20:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@naufalichsan/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[Building a Scalable App with Django and DRF: Applying Best Practices in Real-World Scenarios]]></title>
            <link>https://python.plainenglish.io/building-a-scalable-app-with-django-and-drf-applying-best-practices-in-real-world-scenarios-0c77833342bb?source=rss-32d132a20d81------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c77833342bb</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Naufal Ichsan]]></dc:creator>
            <pubDate>Tue, 27 May 2025 16:10:47 GMT</pubDate>
            <atom:updated>2025-05-28T06:24:29.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*YgmQ0QKE4cjyQan2Lkinzw.jpeg" /><figcaption>Source: Google.com</figcaption></figure><h3>Introduction</h3><p>As the demand for real-time web applications grows, building scalable and maintainable backend systems becomes more critical than ever. This is especially true when your application must handle hundreds or even thousands of users concurrently. In this blog post, I will walk you through how I and my team built a robust quiz application using Django and Django REST Framework (DRF), tailored to handle between 500–1000 concurrent users.</p><p>I’ll explore how various industry-standard best practices — such as Domain-Driven Design (DDD), adherence to SOLID principles, separation of concerns, and implementation of key design patterns — were applied in this project. I’ll also compare alternative architectural strategies, highlight performance and maintainability benefits, and share lessons learned that can be applied to similar projects.</p><h3>🔄 Refactoring: What Is It, Really?</h3><p>Refactoring is the disciplined process of restructuring existing code without changing its external behavior. It’s a vital practice in software development to improve code readability, reduce complexity, and make future changes easier and safer.</p><p>In this project, refactoring was not just about cleaning up code — it was a strategic step to enable scalability and maintainability as the app evolved. Real-world applications rarely get the “perfect” design from day one; instead, continuous improvement through refactoring allows you to:</p><ul><li><strong>Isolate business logic</strong> from presentation and infrastructure layers</li><li><strong>Implement design patterns</strong> that make code extensible and testable</li><li><strong>Reduce technical debt</strong> accumulated during rapid prototyping</li><li><strong>Enhance collaboration</strong> by making code clearer and better organized</li><li><strong>Prepare for future features</strong> without disruptive rewrites</li></ul><p>By thoughtfully refactoring our initial monolithic and tightly coupled codebase into well-defined domains, services, and patterns like Strategy and Factory, we laid a strong foundation for handling complex quiz logic and high concurrency without sacrificing code quality.</p><h3>Project Overview</h3><p>The quiz application was developed to enable real-time quiz participation, with strict correctness, timing, and scalability requirements. The major components of the application include:</p><ul><li><strong>Quiz management</strong>: Creating, editing, and publishing quizzes</li><li><strong>Question management</strong>: Associating multiple-choice questions to quizzes</li><li><strong>Participant attempts</strong>: User interaction during a quiz session</li><li><strong>Answer submission</strong>: Recording and processing answers from users in real time</li></ul><h4>Tech Stack:</h4><ul><li><strong>Backend</strong>: Django, Django REST Framework</li><li><strong>Database</strong>: PostgreSQL</li><li><strong>Cache/Queue</strong>: Redis</li><li><strong>Containerization &amp; Deployment</strong>: Docker, Docker Compose</li><li><strong>Load Testing</strong>: Locust</li></ul><h3>📖 Best Practices We Implemented</h3><h4>1. Domain-Driven Design (DDD)</h4><p>We structured the Django project into clear domains that mirror the business logic:</p><pre>quiz/<br>  ├── tests/<br>  ├── models.py<br>  ├── views.py<br>  ├── serializers.py<br>question/<br>  ├── tests/<br>  ├── models.py<br>  ├── views.py<br>  ├── serializers.py<br>participant_answer/<br>  ├── tests/<br>  ├── models.py<br>  ├── services.py<br>  ├── serializers.py<br>attempt/<br>  ├── tests/<br>  ├── models.py<br>  ├── views.py<br>  ├── serializers.py</pre><h4>Benefits:</h4><ul><li>Logical separation of concerns</li><li>Easier Organization and Discoverability</li><li>Enables microservice transition in the future</li><li>Independent unit testing per domain</li></ul><p>By thinking in terms of subdomains, each Django app corresponds to a real-world concept. This makes it easier to reason about changes and enhances modularity, make it easier if we want to migrate it to microservices architecture in the future.</p><h4>2. Design Pattern in Action: Strategy and Factory pattern for Scoring Types</h4><h4><strong>🧠 Why Use Strategy + Factory Patterns?</strong></h4><p>When building a real-time quiz system, we needed to support multiple question types:</p><ul><li>Multiple Choice</li><li>True/False</li><li>Short Answer</li><li>Essay</li></ul><p>Each type requires different logic to evaluate whether an answer is correct. Initially, we had simple<strong> if-else</strong> or <strong>switch</strong> logic embedded in the service layer:</p><pre>def evaluate_answer(question_type, submitted_answer, correct_answer):<br>    if question_type == &#39;mcq&#39;:<br>        return submitted_answer == correct_answer<br>    elif question_type == &#39;tf&#39;:<br>        return submitted_answer.lower() == correct_answer.lower()<br>    elif question_type == &#39;sa&#39;:<br>        return normalize(submitted_answer) == normalize(correct_answer)<br>    # ...</pre><h4><strong>⚠️ Problems with This Approach:</strong></h4><ul><li><strong>Hard to Extend</strong>: Adding new types meant modifying this core function repeatedly.</li><li><strong>Violates OCP</strong>: The service layer wasn’t closed to modification.</li><li><strong>Unit Testing Pain</strong>: Testing each case meant setting up mocks for each branch in the same function.</li><li><strong>Harder to Read</strong>: Business logic was tightly coupled and not reusable elsewhere.</li></ul><h4><strong>✅ The Solution: Strategy Pattern + Factory</strong></h4><h4>What Is Strategy Pattern?</h4><p>The <strong>Strategy pattern</strong> is a behavioral design pattern that enables selecting an algorithm’s behavior at runtime. Instead of hardcoding multiple conditional statements, you define a family of interchangeable algorithms (strategies), encapsulate each one in a separate class, and make them interchangeable within the context that uses them.</p><p><strong>Why use it?</strong></p><ul><li>To <strong>separate concerns</strong> by isolating algorithms from the code that uses them.</li><li>To <strong>make code extensible</strong> by allowing new algorithms to be added without changing existing code.</li><li>To <strong>promote flexibility</strong> so the algorithm can be switched dynamically depending on context or input.</li></ul><h4>What Is Factory Pattern?</h4><p>The <strong>Factory pattern</strong> is a creational design pattern used to create objects without specifying the exact class of object that will be created. Instead of calling constructors directly, you use a factory method or class that decides which subclass or instance to create based on input parameters.</p><p><strong>Why use it?</strong></p><ul><li>To <strong>decouple object creation</strong> from the code that uses the objects.</li><li>To <strong>centralize and control instantiation logic</strong>, making it easier to manage and extend.</li><li>To <strong>hide complex creation logic</strong> behind a simple interface.</li></ul><p>We replaced if-else logic with a clean strategy interface and a factory to dynamically choose the correct evaluator, enabling seamless selection and instantiation of interchangeable behaviors of scoring.</p><pre># strategies/base.py<br>class ScoringStrategy(ABC):<br>    @abstractmethod<br>    def evaluate(self, submitted_answer, correct_answer):<br>        pass<br><br># strategies/mcq.py<br>class MultipleChoiceStrategy(ScoringStrategy):<br>    def evaluate(self, submitted, correct):<br>        return submitted == correct<br><br>class TrueFalseStrategy(ScoringStrategy):<br>    def evaluate(self, submitted, correct):<br>        return submitted.lower() == correct.lower()</pre><pre># Factory to handle abstraction<br>class ScoringFactory:<br>    strategies = {<br>        &#39;mcq&#39;: MultipleChoiceStrategy(),<br>        &#39;tf&#39;: TrueFalseStrategy(),<br>        # &#39;fib&#39;: FillInBlankStrategy(),<br>    }<br>    return strategies.get(question_type)</pre><pre># services.py<br>scorer = ScoringFactory.get_strategy(question.type)<br>is_correct = scorer.evaluate(data[&#39;answer&#39;], question.correct_answer)</pre><h4><strong>Benefits:</strong></h4><ul><li><strong>Clean Extension</strong>: Adding a new question type? Just implement a new strategy class.</li><li><strong>Pure Logic Isolation</strong>: Logic is testable without needing the full Django request/response lifecycle.</li><li><strong>Follows OCP + DIP</strong>: AnswerService doesn’t care how scoring works — it just delegates it.</li><li><strong>Improves Maintainability</strong>: Easy to trace bugs or change logic in one strategy file only.</li><li><strong>Ready for AI/ML</strong>: In the future, we could add a ML-based grading strategy without touching the service code.</li></ul><h4>3. Class-Based Views (CBVs) and SOLID Principles</h4><h4>⚠️ The Problem: Why Implement SOLID Principles?</h4><h4><strong>Before Applying SOLID:</strong></h4><p>When our quiz app started handling more features and growing user load, we encountered several maintainability and scalability issues due to code design flaws:</p><ul><li><strong>Large, Monolithic Functions &amp; Views: </strong>Many views combined HTTP handling, business logic, and data access in one place, making them hard to read, debug, and extend.</li><li><strong>Difficult to Add New Features: </strong>Every time we added a new question type or scoring rule, we had to modify existing code directly, risking introducing bugs.</li><li><strong>Poor Testability: </strong>Tight coupling between components meant unit tests were slow, brittle, and often required full-stack setups.</li><li><strong>Rigid Code Structure: </strong>Without clear separation of concerns, the codebase was fragile and resisted scaling both in terms of team size and user demand.</li></ul><pre># This view handles too much and violates SRP and OCP<br>@api_view([&#39;POST&#39;])<br>def submit_answer(request):<br>    data = request.data<br>    quiz = Quiz.objects.get(id=data[&#39;quiz_id&#39;])<br>    question = Question.objects.get(id=data[&#39;question_id&#39;])<br>    is_correct = question.correct_answer == data[&#39;answer&#39;]<br>    ParticipantAnswer.objects.create(user=request.user, question=question, answer=data[&#39;answer&#39;])<br>    return Response({&quot;correct&quot;: is_correct})</pre><h4><strong>After Applying SOLID:</strong></h4><p>Rather than using Django’s function-based views (FBVs), we applied CBVs combined with DRF’s generic views and mixins. Here’s how the SOLID principles played out:</p><pre># views.py<br><br># SRP: View only delegates<br>class SubmitAnswerView(APIView):<br>    def post(self, request):<br>        return AnswerService.submit(request.user, request.data)</pre><pre># services.py<br><br># OCP: Logic moved to service and can be extended without modifying views<br>class AnswerService:<br>    @staticmethod<br>    def submit(user, data):<br>        quiz = Quiz.objects.get(id=data[&#39;quiz_id&#39;])<br>        question = Question.objects.get(id=data[&#39;question_id&#39;])<br>        scorer = ScoringFactory.get_strategy(question.type)<br>        is_correct = scorer.evaluate(data[&#39;answer&#39;], question.correct_answer)<br>        ParticipantAnswer.objects.create(user=user, question=question, answer=data[&#39;answer&#39;])<br>        return Response({&quot;correct&quot;: is_correct})</pre><h4>Benefits:</h4><ul><li><strong>Single Responsibility Principle</strong>: Each class or function does one thing only. SubmitAnswerView only handles HTTP concerns, while AnswerService handles business logic.</li><li><strong>Open/Closed Principle</strong>: We can introduce new scoring types in the future (e.g., fill-in-the-blank, match-the-column) by adding new strategy classes without modifying existing ones.</li><li><strong>Liskov Substitution Principle:</strong> All scoring strategies inherit from a common interface and can be substituted freely without breaking functionality. Any ScoringStrategy implementation (like MultipleChoiceStrategy or TrueFalseStrategy) can be used interchangeably.</li><li><strong>Interface Segregation Principle:</strong> Each strategy implements only what it needs. There is no bloated base class — just minimal, purpose-specific interfaces.</li><li><strong>Dependency Inversion Principle:</strong> The high-level service (AnswerService) depends on the abstract interface ScoringStrategy, not concrete implementations. The creation of strategy instances is delegated to the ScoringFactory, which promotes loose coupling.</li></ul><h4>4. Performance &amp; Scalability Improvements: Asynchronous Processing with Redis and Celery</h4><p>Quiz applications with high concurrency can suffer from DB write bottlenecks. To solve this:</p><ul><li>We pushed answer submissions to a Redis queue</li><li>Used Celery to process answers asynchronously</li><li>Ensured idempotency in tasks to prevent duplicate writes</li></ul><pre>@shared_task()<br>def save_participant_answer():<br>    try:<br>        # Grab 0–499 items in a single call and remove them<br>        raw_items = rd.lrange(&quot;participant_answers_buffer&quot;, 0, 499)<br>        rd.ltrim(&quot;participant_answers_buffer&quot;, len(raw_items), -1)<br>        <br>        print(&quot;data from save_participant_answer&quot;)<br>        for i, val in enumerate(raw_items):<br>            decoded = json.loads(val)<br>            print(f&quot;{i}: {decoded}&quot;)<br><br>        if not raw_items:<br>            return<br><br>        # ...</pre><p>This pattern ensured the API response remained fast, while database integrity and processing were handled reliably in the background.</p><h3>🤔 <strong>What Are the Trade-Offs?</strong></h3><p>While applying best practices like Domain-Driven Design, SOLID principles, and design patterns such as Strategy and Factory greatly improved the maintainability and scalability of our quiz app, it’s important to recognize some potential downsides:</p><ul><li><strong>Initial Complexity and Learning Curve:</strong> Introducing abstractions and patterns can make the codebase more complex at first, which might slow down onboarding new developers unfamiliar with these concepts.</li><li><strong>More Boilerplate Code: </strong>Breaking logic into multiple classes and layers often leads to more files and classes, which can feel verbose compared to simpler, direct implementations.</li><li><strong>Over-Engineering Risk: </strong>Applying patterns prematurely or unnecessarily can complicate simple features, so it’s crucial to balance best practices with the actual needs of your project.</li><li><strong>Refactoring Effort: </strong>Refactoring existing code to adopt these principles requires time and careful testing, which may not always be feasible in tight deadlines.</li></ul><p>However, in our case, these trade-offs were justified by the long-term gains in code quality, scalability, and team productivity — especially as user concurrency increased and new features were added rapidly.</p><h3>🏁 Final Thoughts</h3><p>Best practices are not a checklist — they’re context-aware guidelines. The most effective implementations are those tuned to the <strong>actual needs</strong> of your project and team maturity.</p><p>By implementing scalable architecture with Django and DRF, and rigorously applying proven software engineering practices, we built a system that:</p><ul><li>Handles real-time interactions for 500–1000 users (tested using locust).</li><li>Can migrate into a microservice system.</li><li>Achieves strong cohesion and low coupling across all components.</li></ul><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c77833342bb" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/building-a-scalable-app-with-django-and-drf-applying-best-practices-in-real-world-scenarios-0c77833342bb">Building a Scalable App with Django and DRF: Applying Best Practices in Real-World Scenarios</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Chaos to Clarity: How We Boosted Team Productivity by Connecting the Right Tools the Right Way]]></title>
            <link>https://medium.com/@naufalichsan/from-chaos-to-clarity-how-we-boosted-team-productivity-by-connecting-the-right-tools-the-right-way-f70c6242c2f4?source=rss-32d132a20d81------2</link>
            <guid isPermaLink="false">https://medium.com/p/f70c6242c2f4</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[devtools]]></category>
            <category><![CDATA[teamwork]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[team-management]]></category>
            <dc:creator><![CDATA[Naufal Ichsan]]></dc:creator>
            <pubDate>Mon, 26 May 2025 11:57:31 GMT</pubDate>
            <atom:updated>2025-05-26T17:30:41.715Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Chaos to Clarity: How We Boosted Dev Team Productivity by Connecting the Right Tools the Right Way</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Bfz0zcPi7fGJbjFNwSWDGQ.jpeg" /><figcaption>Source: Google.com</figcaption></figure><p>In the fast-paced world of software development, the real bottleneck isn’t always bad code — it’s bad processes. When tools don’t talk to each other, when context is scattered, or when review cycles take too long, team velocity suffers.</p><p>In this post, I’ll walk you through how we transformed our workflow by <strong>strategically integrating and optimizing developer tools</strong>. These weren’t just shiny tools for the sake of it — we used them to <strong>solve real problems</strong>, from <strong>improving pull request reviews</strong> to <strong>tightening our CI/CD pipeline</strong>, while <strong>maximizing team visibility and collaboration</strong>.</p><h3>📌 The Problem: Too Many Tools, Too Little Integration</h3><p>Let’s be honest. Many dev teams suffer from issues not because of bad tooling, but because the <strong>tools don’t talk to each other</strong>. The result? Context-switching chaos and fragile collaboration.</p><p>Here are the core problems we faced before optimizing our setup:</p><h4>💤 PRs Sitting Idle</h4><ul><li>Pull Requests were often opened but <strong>lacked visibility</strong>.</li><li>No notification system to alert reviewers in a relevant channel.</li><li>PRs would block releases because no one realized they were waiting for review.</li></ul><h4>🕵️ Missed Edge Cases</h4><ul><li>Code review quality varied significantly.</li><li>Developers team were overwhelmed, leading to rushed reviews.</li><li>Developers team didn’t always know what to look for in a PR.</li><li>Manual checklists were often skipped or forgotten.</li></ul><h4>🔄 Context Switching Burnout</h4><ul><li>Engineers bounced between <strong>JIRA</strong> for task context, <strong>GitHub</strong> for code, <strong>CI logs</strong> for debugging, and <strong>Discord</strong> for discussions.</li><li>This fragmented flow caused lost time, missed comments, and duplicated work.</li><li>Developers spent more time <strong>navigating tools</strong> than writing and reviewing code.</li></ul><h4>💥 Broken CI/CD Pipelines</h4><ul><li>CI pipelines would break due to environmental inconsistencies or lack of test coverage.</li><li>No ownership — who fixes the pipeline? Who was last to change it?</li><li>Logs were buried in tools that weren’t easily accessible or searchable.</li></ul><h4>📚 Disorganized Knowledge Sharing</h4><ul><li>Important implementation notes were left in PR comments or Discord threads, then lost.</li><li>Docs lived in wikis nobody updated or read.</li></ul><p>We wanted to <strong>turn our toolchain into a well-integrated system</strong> that helped us — not hindered us.</p><h3>✅ The Stack That Changed Everything</h3><p>Here’s our current setup and how we made it work for us:</p><h4>1. 🧭 <strong>JIRA — Sprint Management &amp; Ticket Tracking</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4m1ggQcTaKVtiYrbCnEf6g.png" /></figure><p>We use <strong>JIRA for sprint planning, backlog grooming, and issue tracking</strong>, but more importantly:</p><ul><li><strong>Linked GitHub branches and PRs directly to JIRA tickets.</strong></li><li>Added <strong>automation rules</strong> to move JIRA cards to “In Review” or “Done” when PRs are opened or merged.</li></ul><p><strong>Value added</strong>:</p><ul><li>Developer no longer forget to update JIRA.</li><li>Product Owners get real-time progress without asking.</li><li>Sprint velocity metrics such as burndown chart became more accurate.</li></ul><h4>2. 🤖 GitHub Copilot — Smarter Pull Request Reviews</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hO6qkkLdShQ065ZmpJZZJw.png" /></figure><p><strong>What It Does</strong>:<br> GitHub Copilot is an AI assistant for writing and reviewing code. Beyond helping in the IDE, it also boosts PR quality.</p><p><strong>How We Use It</strong>:</p><ul><li>Automatically summarizes code changes in PR descriptions.</li><li>Suggests improvements and flags potential issues before human reviewers step in.</li><li>Identifies anti-patterns or duplicated logic in larger code changes.</li></ul><p><strong>Why It Matters</strong>:</p><ul><li>Faster and more consistent code reviews.</li><li>Great mentorship aid for developers that want fast merge.</li><li>Less review fatigue for other developers.</li></ul><h4>3. 🔁 GitHub Workflows — CI/CD Done Right</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6qsv3hKcD9HuDBOfBMd5w.png" /></figure><p><strong>What It Does</strong>:<br> GitHub Actions lets us automate tasks like building, testing, deploying, and validating pull requests — without leaving GitHub.</p><p><strong>How We Use It</strong>:</p><ul><li>Runs linters, unit tests, and type-checkers on every PR.</li><li>Builds Docker images and deploys to a staging environment.</li><li>Sends real-time updates to Discord (see below).</li><li>Notifies authors when their PR fails a check or is deployed successfully.</li></ul><p><strong>Why It Matters</strong>:</p><ul><li>Confident merges and fewer “works on my machine” bugs.</li><li>Fully automated deployments reduce manual handoffs.</li><li>Developers can focus on writing code, not shipping pipelines.</li></ul><h4>4. 🧱 Pull Request Templates — Clarity for Reviewers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4o-vYIu0FmAZ-_-IfMXMA.png" /></figure><p><strong>What It Does</strong>:<br>PR templates standardize the structure of pull requests and ensure necessary info is always included.</p><p><strong>How We Use It</strong>:</p><ul><li>Screenshots (for UI) or logs (for backend/API)</li><li>Checklist for testing, docs, reviewers, and environment updates</li></ul><p><strong>Why It Matters</strong>:</p><ul><li>Context is clear before the reviewer even clicks “Files changed.”</li><li>Helps prevent back-and-forth questions about purpose or coverage.</li><li>Keeps team standards consistent.</li></ul><h4>5. 📣 Discord — Centralized Dev Communication &amp; Alerts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X11UMM-98GXrHv0GnNwMdw.png" /></figure><p><strong>What It Does</strong>:<br> While many teams use Slack, we use <strong>Discord</strong> as our async communication and dev notification channel.</p><p><strong>How We Use It</strong>:</p><ul><li>GitHub Actions send deployment/build notifications via Discord webhooks.</li><li>JIRA automation pushes ticket status updates to team-specific Discord channels.</li><li>Failed builds and successful releases are posted directly to Discord so everyone sees them instantly.</li></ul><p><strong>Why It Matters</strong>:</p><ul><li>Reduces “out of the loop” moments.</li><li>Helps teams act quickly on failed builds or review requests.</li><li>Keeps everything in the same app we already use for meetings and dev voice chats.</li></ul><h3>🚀 Final Thoughts</h3><p>At the end of the day, it’s not about having <em>more</em> tools — it’s about having the <strong>right setup</strong> and <strong>tight integration</strong> that removes friction, improves confidence, and enables faster, higher-quality work.</p><p>By orchestrating tools like <strong>GitHub Copilot</strong>, <strong>JIRA</strong>, <strong>GitHub Actions</strong>, <strong>Discord</strong>, and <strong>CI best practices</strong>, our team built a <strong>workflow that delivers value with less effort and more consistency</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f70c6242c2f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Migration from HTTP to HTTPS — and Using a Reverse Proxy — Matters More Than Ever]]></title>
            <link>https://medium.com/@naufalichsan/why-migration-from-http-to-https-and-using-a-reverse-proxy-matters-more-than-ever-8a4cdca7aea5?source=rss-32d132a20d81------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a4cdca7aea5</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Naufal Ichsan]]></dc:creator>
            <pubDate>Sun, 25 May 2025 13:23:12 GMT</pubDate>
            <atom:updated>2025-05-25T13:26:46.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Migration from HTTP to HTTPS — and Using a Reverse Proxy — Matters More Than Ever</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_lxCFsM738P2kkI_2-ICg.png" /><figcaption>Source: Google Images</figcaption></figure><p>We live in an era where internet users expect blazing-fast websites, airtight security, and uninterrupted access — regardless of traffic spikes or cyber threats. Yet many websites still run on outdated configurations, especially HTTP and monolithic infrastructures.</p><p>If your site is still relying on plain HTTP or lacks a reverse proxy, you’re not just behind the curve — you’re putting your users (and your reputation) at risk.</p><p>In this post, we’ll break down <strong>why migrating to HTTPS and implementing a reverse proxy is no longer optional</strong> — it’s essential. Whether you’re a developer, startup founder, or just someone managing a web presence, this is your roadmap to a safer, faster, and more scalable website.</p><h3>HTTP vs. HTTPS: It’s Not Just a Letter</h3><p>HTTPS stands for <strong>HyperText Transfer Protocol Secure</strong>. It’s the secure version of HTTP, using <strong>SSL/TLS encryption</strong> to protect the data exchanged between your users and your server.</p><p>That padlock icon in your browser’s address bar? That’s HTTPS in action.</p><h4>Why You Must Migrate from HTTP to HTTPS</h4><h4>🔒 Security: Protecting User Data</h4><p>The primary reason to migrate to HTTPS is <strong>encryption</strong>. Unlike HTTP, HTTPS uses SSL/TLS to encrypt data transferred between the user’s browser and your server. This means:</p><ul><li>Passwords, payment details, and personal information are protected from eavesdroppers.</li><li>It defends against “man-in-the-middle” attacks, where malicious actors intercept data.</li><li>Modern browsers label HTTP sites as “Not Secure” — a red flag to any privacy-conscious user.</li></ul><h4>🌐 Trust &amp; SEO Benefits</h4><p>Google has been using HTTPS as a ranking signal since 2014. That means secure sites are more likely to appear higher in search results. Users are also more likely to trust and engage with a website that shows the padlock icon in the address bar.</p><h4>⚙️ Modern Web Compatibility</h4><p>Many modern web APIs, like geolocation and service workers, <strong>require</strong> HTTPS to function. Sticking with HTTP can limit what your site can do.</p><h3>Why a Reverse Proxy Is Your Infrastructure’s Secret Weapon</h3><h3>Why a Reverse Proxy Is Your Infrastructure’s Secret Weapon</h3><p>A <strong>reverse proxy</strong> sits in front of your web server and acts as an intermediary between clients and your backend services. Tools like <strong>Nginx</strong>, <strong>HAProxy</strong>, and <strong>Traefik</strong> are commonly used for this.</p><p>So, why should you care?</p><h4>🚦 Load Balancing and High Availability</h4><p>Reverse proxies can distribute incoming traffic across multiple servers, improving performance and ensuring no single server is overwhelmed. This allows you to scale horizontally and maintain uptime during traffic spikes.</p><h4>🛡️ Security and Anonymization</h4><p>With a reverse proxy, your backend servers stay hidden from the public internet, reducing the attack surface. You can also configure <strong>rate limiting, IP whitelisting</strong>, and <strong>DDoS mitigation</strong> at the proxy level.</p><h4>📦 SSL Termination Made Simple</h4><p>Instead of managing SSL certificates on each backend server, the reverse proxy handles <strong>SSL termination</strong>, meaning it decrypts HTTPS requests before passing them to your application. This centralizes SSL management and simplifies certificate renewals via tools like <strong>Let’s Encrypt</strong>.</p><h4>🔁 URL Rewriting and Routing</h4><p>Reverse proxies let you rewrite URLs, redirect traffic, or serve multiple apps under different domains or paths — without touching your backend code. This is perfect for microservices or monolithic apps transitioning to modular architecture.</p><h3>Bringing It All Together</h3><p>If you migrate from HTTP to HTTPS but don’t optimize your traffic flow, you’re only halfway there. Likewise, using a reverse proxy without securing your site via HTTPS leaves a major vulnerability open.</p><p>Together, <strong>HTTPS and reverse proxies</strong> form a powerful combination:</p><ul><li>They protect user data and inspire trust.</li><li>They reduce server load and increase performance.</li><li>They give you fine-grained control over traffic and scalability.</li><li>They make DevOps tasks like certificate renewal and service routing far easier.</li></ul><p>If you want to read how to implement reverse proxy and adding https certificate to your domain using nginx and certbot, you can read it <a href="https://medium.com/@naufalichsan114/secure-your-app-setting-up-nginx-reverse-proxy-with-https-using-certbot-56cfb2d2a2ab">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a4cdca7aea5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving TDD in Django: From Monolithic Test Files to Modular Folder Structure]]></title>
            <link>https://medium.com/@naufalichsan/improving-tdd-in-django-from-monolithic-test-files-to-modular-folder-structure-bf39a06f3535?source=rss-32d132a20d81------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf39a06f3535</guid>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[modularity]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Naufal Ichsan]]></dc:creator>
            <pubDate>Tue, 20 May 2025 07:06:12 GMT</pubDate>
            <atom:updated>2025-05-27T15:48:55.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M38cEId8XDcEv-z3qLYE2g.png" /><figcaption>Source: Google.com</figcaption></figure><p>In the fast-moving world of software development, especially when working with Django in a team setting, writing clean and modular tests is just as important as writing clean application code.</p><p>One issue that constantly tripped up my team was merge conflicts in our test files — specifically in files like test_views.py, test_models.py, and test_serializers.py. Every time multiple team members worked on different views or models, they&#39;d end up editing the same test files. This led to frequent and annoying merge conflicts during pull requests.</p><p>So, I decided to refactor the test structure to reduce conflicts and increase maintainability. In this post, I’ll walk through how I reorganized the Django test files from a flat structure to a folder-based one — and why it made a big difference.</p><h3>🧩 The Problem With Flat Test Files</h3><p>In the original structure, we had something like this:</p><pre>/myapp<br>  ├── models.py<br>  ├── views.py<br>  ├── serializers.py<br>  └── tests/<br>        ├── test_models.py<br>        ├── test_views.py<br>        └── test_serializers.py</pre><p>This worked fine at first. But as the app grew, these files became long and unmanageable. Here are some of the challenges we faced:</p><ul><li><strong>Merge Conflicts</strong>: Two developers working on different views but writing tests in test_views.py would constantly clash.</li><li><strong>Low Traceability</strong>: It was hard to quickly find tests related to a specific view or model.</li><li><strong>Poor Modularity</strong>: All tests for a file were dumped together. Adding new tests felt like tacking on spaghetti.</li></ul><h3>🛠️ The Refactor Plan</h3><p>I decided to break up the tests into folders — one for each layer: models, views, and serializers. Each file within those folders corresponds to the component being tested. Here’s the updated structure:</p><pre>/myapp<br>  └── tests/<br>        ├── models/<br>        │     ├── __init__.py<br>        │     ├── test_user.py<br>        │     └── test_product.py<br>        ├── views/<br>        │     ├── __init__.py<br>        │     ├── test_user_view.py<br>        │     └── test_product_view.py<br>        └── serializers/<br>              ├── __init__.py<br>              ├── test_user_serializer.py<br>              └── test_product_serializer.py</pre><p>Why this is better?</p><p><strong>Improved Organization and Discoverability:</strong></p><ul><li><strong>Easier Navigation:</strong> Developers can quickly search for a test file, no more iterating over 1000 lines of test code just to find one test case that generate error.</li><li><strong>Better Modularity</strong>: Each test file is small, focused, and easier to read and maintain.</li></ul><p><strong>Enhanced Focus and Isolation:</strong></p><ul><li><strong>True Unit Testing:</strong> By having separate files for each class or logical unit, we can enforce a more disciplined approach to unit testing. Each test file can focus solely on the responsibilities of that specific unit, leading to more granular and effective tests.</li><li><strong>Reduced Interdependencies:</strong> When all tests are in one file, it’s easier for them to accidentally become dependent on each other, leading to brittle tests where a failure in one test cascades and causes others to fail, even if the underlying code isn’t broken. Separate files naturally promote independence.</li></ul><p><strong>Better Team Collaboration:</strong></p><ul><li><strong>Clear Ownership:</strong> It’s easier to assign ownership of test files to specific team members who are responsible for the corresponding code.</li><li><strong>Parallel Development:</strong> Multiple developers can work on different parts of the application and their respective tests simultaneously without stepping on each other’s toes in a single, massive test file, no more irritating merge conflict.</li></ul><p><strong>Faster and More Targeted Test Runs:</strong></p><ul><li><strong>Selective Testing:</strong> Developers don’t need to run the entire test suite. With a well-organized folder structure, we can easily run only the tests related to that views. This significantly speeds up the development cycle.</li><li><strong>Parallel Execution (Potential): </strong>Having<strong> </strong>separate files can make it easier to configure and leverage this feature, as each file is a self-contained unit that can be processed independently.</li></ul><p><strong>Simplified Debugging:</strong></p><ul><li><strong>Pinpointing Issues:</strong> When a test fails, we can know exactly which file and, by extension, which component or class is likely causing the problem. This significantly reduces the time spent on debugging compared to sifting through a giant test file.</li><li><strong>Reduced Complexity:</strong> A smaller, focused test file is inherently less complex, making it easier to read the test logic and understand why a test is failing.</li></ul><h3>✅ How to Refactor Step-by-Step</h3><h4>1. Create the Folder Structure</h4><p>Here’s a command line approached I use to refactor it in my project:</p><pre>mkdir -p myapp/tests/models<br>mkdir -p myapp/tests/views<br>mkdir -p myapp/tests/serializers<br>touch myapp/tests/models/__init__.py<br>touch myapp/tests/views/__init__.py<br>touch myapp/tests/serializers/__init__.py</pre><p><strong>🗂️ What This Does:</strong></p><ul><li>mkdir -p creates the nested folders (and parent if not present).</li><li>touch creates an empty __init__.py file</li><li>__init__.py files are needed to treat folders as Python packages — crucial for test discovery using tools like <strong>pytest</strong> or Django’s test runner.</li></ul><h4>2. Split Test Files by Concern</h4><p>I moved tests from test_views.py into multiple smaller files based on the view being tested. For example:</p><p><strong>Before:</strong></p><pre>#test_views.py<br>def test_create_quiz():<br>    ...<br><br>def test_quiz_list():<br>    ...</pre><p><strong>After:</strong></p><pre>#test_create_quiz_view.py<br>class CreateQuizViewTest:<br>  def test_create_quiz():<br>      ...</pre><pre>#test_quiz_list_view.py<br>class QuizListViewTest:<br>  def test_quiz_list():<br>      ...</pre><h3>🧠 Lessons Learned</h3><ul><li>Modular tests = modular thinking. When your test files are modular, your mental model of the app also becomes cleaner.</li><li>Folder-based structure scales better. Whether you’re working on a two-person project or a team of twenty, this organization holds up.</li><li>Refactoring isn’t just for app code. Tests are code too — they deserve structure and care.</li></ul><h3>🧪 Bonus: Running the Tests</h3><p>Nothing changes in how you run your tests. Django will still discover them as long as:</p><ul><li>They follow the test_*.py naming convention.</li><li>Test classes inherit from TestCase or SimpleTestCase.</li></ul><pre># With Django<br>python manage.py test myapp<br><br># With pytest<br>pytest myapp/tests/</pre><h3>📦 Final Thoughts</h3><p>Moving from a flat test_views.py structure to a folder-based approach saved us from constant merge conflicts and gave our codebase a cleaner, more scalable testing foundation.</p><p>If your test files are getting crowded or your team is constantly stepping on each other’s toes during merges, consider making this simple, practical change. It’s an easy win — and your future self (and teammates) will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf39a06f3535" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Your App: Setting Up Nginx Reverse Proxy with HTTPS Using Certbot]]></title>
            <link>https://medium.com/@naufalichsan/secure-your-app-setting-up-nginx-reverse-proxy-with-https-using-certbot-56cfb2d2a2ab?source=rss-32d132a20d81------2</link>
            <guid isPermaLink="false">https://medium.com/p/56cfb2d2a2ab</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[tls]]></category>
            <dc:creator><![CDATA[Naufal Ichsan]]></dc:creator>
            <pubDate>Tue, 20 May 2025 05:27:03 GMT</pubDate>
            <atom:updated>2025-05-21T02:47:09.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>Secure Your Deployment: Setting Up Nginx Reverse Proxy with HTTPS Using Certbot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*uBalaaX70HcH-RhbGyQDZw.png" /><figcaption>Source: Google.com</figcaption></figure><p>When I moved one of my internal apps into Docker, I realized I still needed to expose it securely on the internet. Running an app in a container is great, but if you expose it directly, you’re missing out on proper routing and encryption.</p><p>So, I decided to run <strong>both Nginx and my app inside Docker containers</strong>, set up Nginx as a reverse proxy, and secure everything with <strong>HTTPS using Certbot</strong> — all containerized.</p><p>Here’s how I did it — sharing both my experience and a step-by-step you can follow.</p><h3>Starting Point: Dockerized App and Nginx</h3><p>My app was containerized, listening on port 3000 inside its container. I wanted to:</p><ul><li>Run Nginx as a separate Docker container</li><li>Proxy requests from Nginx to my app container</li><li>Use Certbot to issue TLS certificates, also running inside Docker</li></ul><h4>Step 1: Docker Network Setup</h4><p>To make containers talk, I created a user-defined Docker network:</p><pre>docker network create app-network</pre><h4>Step 2: Run Your App Container</h4><p>I started my app container on the network, exposing port 3000 internally:</p><pre>docker run -d --name myapp --network app-network myapp-image</pre><h4>Step 3: Set Up Nginx Container as Reverse Proxy</h4><p>I wrote an Nginx config (nginx.conf) to proxy to the app container:</p><pre>server {<br>    listen 80;<br>    server_name myapp.example.com;<br><br>    location / {<br>        proxy_pass http://myapp:8000;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><p><strong>Important:</strong> Here myapp matches the Docker container name and works because they share the same network.</p><p>I put this nginx.conf into a local folder (./nginx).</p><p>Then I started the Nginx container, mounting the config and connecting to the same network:</p><pre>docker run -d --name nginx-proxy \<br>  --network app-network \<br>  -p 80:80 -p 443:443 \<br>  -v $(pwd)/nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro \<br>  nginx</pre><h4>Step 4: Get TLS Certificates Using Certbot in Docker</h4><p>I used the official Certbot Docker image to obtain certificates with the <strong>webroot method</strong>:</p><pre>docker run -it --rm \<br>  -v $(pwd)/certbot/www:/var/www/certbot \<br>  -v $(pwd)/certbot/conf:/etc/letsencrypt \<br>  --network app-network \<br>  certbot/certbot certonly \<br>  --webroot --webroot-path=/var/www/certbot \<br>  -d myapp.example.com</pre><h4>Step 5: Update Nginx for HTTPS</h4><p>After certs are issued (stored in ./certbot/conf/live/myapp.example.com), I updated nginx.conf to:</p><pre>server {<br>    listen 80;<br>    server_name myapp.example.com;<br>    location /.well-known/acme-challenge/ {<br>        root /var/www/certbot;<br>    }<br>    location / {<br>        return 301 https://$host$request_uri;<br>    }<br>}<br><br>server {<br>    listen 443 ssl;<br>    server_name myapp.example.com;<br><br>    ssl_certificate /etc/letsencrypt/live/myapp.example.com/fullchain.pem;<br>    ssl_certificate_key /etc/letsencrypt/live/myapp.example.com/privkey.pem;<br><br>    location / {<br>        proxy_pass http://myapp:8000;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><p>Then restarted the Nginx container with the cert and webroot volumes mounted:</p><pre>docker stop nginx-proxy<br>docker rm nginx-proxy<br><br>docker run -d --name nginx-proxy \<br>  --network app-network \<br>  -p 80:80 -p 443:443 \<br>  -v $(pwd)/nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro \<br>  -v $(pwd)/certbot/www:/var/www/certbot \<br>  -v $(pwd)/certbot/conf:/etc/letsencrypt \<br>  nginx</pre><h4>Step 6: Automate Certificate Renewal</h4><p>I created a simple script renew_cert.sh:</p><pre>#!/bin/bash<br>docker run --rm \<br>  -v $(pwd)/certbot/www:/var/www/certbot \<br>  -v $(pwd)/certbot/conf:/etc/letsencrypt \<br>  --network app-network \<br>  certbot/certbot renew --webroot --webroot-path=/var/www/certbot<br><br>docker exec nginx-proxy nginx -s reload</pre><p>Scheduled it via cron on the host machine:</p><pre>crontab -e<br># Add:<br>0 3 * * * /path/to/renew_cert.sh &gt;&gt; /var/log/certbot-renew.log 2&gt;&amp;1</pre><h3>What I Learned From This Experience</h3><ul><li>Docker networking makes container-to-container communication straightforward. Just remember to use container names in Nginx proxy_pass.</li><li>Certbot in Docker with the webroot plugin works well for standalone Nginx containers.</li><li>Mounting volumes is key: certbot needs persistent storage for certificates; Nginx needs access to both certs and webroot challenge files.</li><li>Automating renewal with a script and cron outside containers is reliable and simple.</li><li>Always check your firewall rules on the host for ports 80 and 443.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56cfb2d2a2ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development (TDD) in Django: Best Practices for Modern Software Iteration]]></title>
            <link>https://python.plainenglish.io/test-driven-development-tdd-in-django-best-practices-for-modern-software-iteration-f65106137efd?source=rss-32d132a20d81------2</link>
            <guid isPermaLink="false">https://medium.com/p/f65106137efd</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Naufal Ichsan]]></dc:creator>
            <pubDate>Thu, 08 May 2025 05:02:40 GMT</pubDate>
            <atom:updated>2025-05-28T06:24:33.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*kCU2Dca5zryYLs3qGN570g.png" /><figcaption>Source: TechJedi</figcaption></figure><p>In the fast-paced world of software development, delivering scalable, maintainable, and high-quality applications requires more than just writing good code. It demands discipline, structure, and reliable processes. One of the most effective approaches to achieve this is <strong>Test-Driven Development (TDD)</strong> — especially when using a robust framework like Django.</p><p>In this article, we’ll explore:</p><ul><li>Why TDD is crucial for sustainable software development and iteration.</li><li>How to implement TDD in Django with best practices.</li><li>Complementary techniques and modern tools like inline testing, linters, code coverage, CI/CD, and monitoring tools that enhance TDD workflows.</li></ul><h3>🧪 What is TDD and Why Does It Matter?</h3><p><strong>Test-Driven Development (TDD)</strong> is more than just a technique — it’s a development discipline that influences how you think about architecture, maintainability, and product evolution.</p><p>At its core, TDD flips the traditional development workflow on its head. Instead of writing code and testing afterward, you <strong>write the test first</strong> to define what the code <em>should</em> do. Then, you build only enough code to make the test pass. Once it passes, you clean up the implementation (refactor) and move on.</p><p>The cycle follows:</p><ol><li><strong>Red</strong> — Write a test that fails.</li><li><strong>Green</strong> — Write the minimum code necessary to pass the test.</li><li><strong>Refactor</strong> — Clean up the code while ensuring tests still pass.</li></ol><h4>🚀 Benefits of TDD</h4><p><strong>1. It Forces Clarity in Requirements</strong></p><blockquote>“If you don’t know how to test it, you probably don’t understand it.”</blockquote><p>Writing tests before implementation makes you clarify what your code is <em>supposed</em> to do. This is especially useful in teams where misalignment between product and engineering is common. Each test becomes a mini-spec.</p><p><strong>2. It Enables Confident Refactoring<br></strong>Software always evolves — new features, bug fixes, performance tuning. Without a reliable test suite, refactoring becomes risky. TDD ensures there’s always a safety net.</p><p>With TDD, you can:</p><ul><li>Add features without breaking existing ones.</li><li>Refactor freely because the tests verify behavior.</li><li>Reduce fear of regression bugs after updates.</li></ul><p><strong>3. It Encourages Better Design (Separation of Concerns)<br></strong>When you’re forced to write testable code, your code tends to be:</p><ul><li>More modular</li><li>Loosely coupled</li><li>Focused on small, single responsibilities</li></ul><p>This naturally leads to <strong>cleaner architecture</strong> and better separation of concerns.</p><p><strong>4. It Makes Bugs Easier to Prevent and Fix<br></strong>In TDD, tests are created before the bug even has a chance to slip in. And when a bug does happen:</p><ul><li>You reproduce it with a failing test first.</li><li>Then you fix it.</li><li>The test ensures it doesn’t come back in the future.</li></ul><p>This is often faster and more reliable than debugging manually.</p><p><strong>5. It Reduces Overengineering<br></strong>A common issue in software development is writing more code than necessary, “just in case.” TDD restricts you to writing only what’s needed to make the test pass. This leads to:</p><ul><li>Leaner, purpose-driven code</li><li>Fewer dead branches and unused paths</li></ul><h3>🔄 TDD Supports Iterative Development</h3><p>Modern software development framework like SCRUM is built in iterations. Features evolve rapidly, requirements change, and time-to-market is critical. TDD supports this by providing:</p><ul><li><strong>Short feedback loops</strong>: Know instantly if something breaks.</li><li><strong>Faster onboarding</strong>: New team members can run the tests to understand the system.</li><li><strong>Regression-proofing</strong>: Automated tests catch unintended consequences of changes.</li></ul><p>TDD isn’t just about writing tests. It’s about <strong>shaping the way we think about building software</strong> — from reactive to proactive, from defensive to confident.</p><h3>⚙️ Setting Up TDD in a Django Project</h3><h4><strong>1</strong>. <strong>🧱 Project Structure</strong></h4><pre>myapp/<br>├── models.py<br>├── views.py<br>├── tests/<br>│   ├── test_models.py<br>│   ├── test_views.py<br>│   ├── test_serializers.py</pre><p>You can seperate it to folder based structure if your project is large enough,</p><pre>myapp/<br>├── models.py<br>├── views.py<br>├── tests/<br>│   ├── views/<br>│   ├── models/<br>│   ├── serializers/</pre><h4><strong>2. ✅ Write Your First Test</strong></h4><p>Use Django’s built-in test client and unittest.</p><pre># tests/views/test_views.py<br>from django.test import TestCase<br>from django.urls import reverse<br><br>class ProductViewTests(TestCase):<br>    def test_product_list_empty(self):<br>        response = self.client.get(reverse(&#39;product-list&#39;))<br>        self.assertEqual(response.status_code, 200)<br>        self.assertEqual(response.json(), [])</pre><h4><strong>3. 🚧 Write the Minimal Code to Pass</strong></h4><pre># views.py<br>from django.http import JsonResponse<br><br>def product_list(request):<br>    return JsonResponse([], safe=False)</pre><p>Repeat the cycle: <strong>test → code → refactor</strong>.</p><h3>🧰 Modern Techniques to Improve Your TDD Workflow</h3><h4>1. 🧪 Use pytest + pytest-django</h4><p>While Django’s unittest works, pytest is more concise and extensible.</p><p>Install:</p><pre>pip install pytest pytest-django</pre><p>In pytest.ini:</p><pre>[pytest]<br>DJANGO_SETTINGS_MODULE = myproject.settings</pre><p>Then run:</p><pre>pytest</pre><h4><strong>2. 💡 Inline Type &amp; Lint Checking</strong></h4><p>Use these tools to catch issues before they hit tests:</p><ul><li>mypy: static type checking</li><li>flake8 or ruff: linting</li><li>black: auto code formatting</li></ul><pre>pip install mypy black flake8</pre><h4>3. 📈 Add Code Coverage Tracking</h4><pre>pip install coverage<br>coverage run -m pytest<br>coverage report<br>coverage html  # for visual report</pre><h3>🔁 TDD + Continuous Integration = Safe Iterations</h3><p>Use GitHub Actions to automate test execution and linting:</p><pre># .github/workflows/test.yml<br>name: Test &amp; Lint<br><br>on: [push, pull_request]<br><br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    services:<br>      postgres:<br>        image: postgres:13<br>        ports: [&#39;5432:5432&#39;]<br>        env:<br>          POSTGRES_DB: test_db<br>          POSTGRES_USER: user<br>          POSTGRES_PASSWORD: pass<br>    env:<br>      DATABASE_URL: postgres://user:pass@localhost:5432/test_db<br><br>    steps:<br>      - uses: actions/checkout@v3<br>      - uses: actions/setup-python@v4<br>        with:<br>          python-version: &#39;3.10&#39;<br><br>      - run: pip install -r requirements.txt<br>      - run: black . --check<br>      - run: flake8 .<br>      - run: pytest --cov</pre><h3>🧭 Observability Complements TDD</h3><p>Tests verify correctness before deployment, but you still need real-world feedback after release.</p><p>Integrate:</p><ul><li><strong>Sentry</strong> — for error monitoring</li><li><strong>Prometheus + Grafana</strong> — for metrics</li><li><strong>OpenTelemetry</strong> — for distributed tracing</li><li><strong>Health Checks</strong> — for service uptime</li></ul><p>Example for Django:</p><pre>pip install sentry-sdk</pre><pre># settings.py<br>import sentry_sdk<br>from sentry_sdk.integrations.django import DjangoIntegration<br><br>sentry_sdk.init(<br>    dsn=&quot;https://your-key@o0.ingest.sentry.io/project-id&quot;,<br>    integrations=[DjangoIntegration()],<br>    traces_sample_rate=1.0,<br>)</pre><p>This way, your team can identify gaps your tests missed and improve them over time.</p><h3>Final Thoughts</h3><p>TDD is more than a test strategy — it’s a development mindset that emphasizes reliability and design. When paired with static analysis, CI/CD, and observability, it forms a feedback loop that ensures both developer confidence and user trust. Django’s ecosystem makes it practical and scalable to adopt this approach, even for solo devs or lean teams.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f65106137efd" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/test-driven-development-tdd-in-django-best-practices-for-modern-software-iteration-f65106137efd">Test-Driven Development (TDD) in Django: Best Practices for Modern Software Iteration</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Level Up Your Django App: Tackling Background Tasks with Celery]]></title>
            <link>https://python.plainenglish.io/level-up-your-django-app-tackling-background-tasks-with-celery-5a7d2cf2255a?source=rss-32d132a20d81------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a7d2cf2255a</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[celery-django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Naufal Ichsan]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 03:27:47 GMT</pubDate>
            <atom:updated>2025-05-27T06:00:26.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*P1g3E0g76cfI7-84JG5ksw.png" /><figcaption>Source: Google.com</figcaption></figure><p>In the world of web development, user experience is paramount. No one enjoys staring at a loading screen while your Django application churns through computationally intensive tasks. This is where background task processing comes to the rescue, and <strong>Celery</strong> stands out as a powerful and flexible solution for Python and Django projects.</p><p>This post will walk you through the steps of integrating Celery into your Django application, allowing you to offload time-consuming operations and keep your web requests snappy.</p><h3>Why Celery?</h3><p>Before we dive into the how-to, let’s briefly touch upon why Celery is a go-to choice for background tasks in Django:</p><ul><li><strong>Asynchronous Processing:</strong> Celery enables you to execute tasks outside the request-response cycle, preventing blocking and improving application responsiveness.</li><li><strong>Reliability:</strong> It offers mechanisms for handling task failures, retries, and ensuring tasks are executed even if workers or the main application encounter issues.</li><li><strong>Scalability:</strong> You can easily scale the number of Celery workers to handle increasing workloads.</li><li><strong>Integration:</strong> Celery seamlessly integrates with Django and a variety of message queuing(like RabbitMQ and Redis).</li><li><strong>Rich Ecosystem:</strong> A mature and well-documented library with a vibrant community.</li></ul><h3>Setting Up the Stage: Installation and Configuration</h3><p>Let’s get our hands dirty with the integration process. We’ll assume you have a Django project already set up.</p><p><strong>1. Install Celery and a Broker:</strong></p><p>First, you need to install the Celery library and a message broker. We’ll use Redis for simple message queueing system for this example, as it’s relatively easy to set up.</p><pre>pip install celery redis</pre><p><em>Notes: Redis may not be a message broker by definition, but can be used as a message queuing system where celery the one that established communication to redis.</em></p><p><strong>2. Configure Celery in Your Django Project:</strong></p><p>Create a new file named celery.py in your Django project directory (the one containing your manage.py file). Add the following code:</p><pre># your-project/celery.py<br>import os<br>from celery import Celery<br><br>os.environ.setdefault(&#39;DJANGO_SETTINGS_MODULE&#39;, &#39;your_project_name.settings&#39;)<br><br>app = Celery(&#39;your_project_name&#39;)<br>app.config_from_object(&#39;django.conf:settings&#39;, namespace=&#39;CELERY&#39;)<br><br># Load task modules from all registered Django app configs.<br>app.autodiscover_tasks()<br><br>@app.task(bind=True, ignore_result=True)<br>def debug_task(self):<br>    print(f&#39;Request: {self.request!r}&#39;)</pre><p><strong>Notes:</strong><em> app.autodiscover_tasks() </em>by default<em> </em>will discover tasks.py inside your app, so make sure all of your background tasks written at your-app/tasks.py.</p><p><strong>3. Setup your Redis Server</strong></p><p>You can use Docker to start a redis server, below is the yaml configuration using docker compose:</p><pre>services:<br>  redis:<br>    image: redis:latest<br>    container_name: redis<br>    restart: always<br>    ports:<br>      - &#39;6379:6379&#39;<br>    command: redis-server --save 20 1 --loglevel warning<br>    volumes: <br>      - cache:/data<br><br>volumes:<br>  cache:</pre><p><strong>4. Link Celery with Django Settings:</strong></p><p>Now, in your project’s settings.py file, add the following Celery configurations:</p><pre>CELERY_BROKER_URL = &#39;redis://localhost:6379/0&#39;  # Replace with your Redis connection URL<br>CELERY_RESULT_BACKEND = &#39;redis://localhost:6379/0&#39; # Optional: For tracking task results<br>CELERY_ACCEPT_CONTENT = [&#39;application/json&#39;]<br>CELERY_TASK_SERIALIZER = &#39;json&#39;<br>CELERY_RESULT_SERIALIZER = &#39;json&#39;<br>CELERY_TIMEZONE = &#39;Asia/Jakarta&#39;  # Adjust to your timezone</pre><p><strong>5. Initialize Celery in Your Django App:</strong></p><p>In the __init__.py file of one of your Django project directory, add the following lines:</p><pre>from .celery import app as celery_app<br><br>__all__ = (&#39;celery_app&#39;,)</pre><h3>Defining and Using Celery Tasks</h3><p>Now for the exciting part — creating and using your background tasks!</p><p><strong>1. Create a </strong><strong>tasks.py File:</strong></p><p>Inside one of your Django applications, create a file named tasks.py. This is where you&#39;ll define your Celery tasks.</p><pre>from celery import shared_task<br>import time<br><br>@shared_task<br>def process_data(item_id):<br>    &quot;&quot;&quot;<br>    Simulates processing data for a specific item.<br>    &quot;&quot;&quot;<br>    print(f&quot;Processing data for item: {item_id}&quot;)<br>    time.sleep(5)  # Simulate a time-consuming operation<br>    print(f&quot;Finished processing data for item: {item_id}&quot;)<br>    # Add your actual data processing logic here<br>    return f&quot;Data processing complete for item {item_id}&quot;</pre><p><strong>2. Calling Tasks from Your Django Views:</strong></p><p>In your Django views or any other part of your Django code, you can now call these tasks asynchronously using the .delay() method:</p><pre>from django.shortcuts import render<br>from .tasks import process_data, send_email_notification<br><br>def my_view(request, item_id):<br>    # ... your view logic ...<br>    process_data.delay(item_id)  # Enqueue the task for background processing<br>    return render(request, &#39;processing_started.html&#39;)</pre><p>The .delay() method adds the task to the Celery queue, and a Celery worker will pick it up and execute it in the background.</p><h3>Running the Celery Worker</h3><p>To actually execute the background tasks, you need to start a Celery worker. Open a new terminal window in your Django project directory and run:</p><pre>celery -A your_project_name worker -l info</pre><p>Replace &#39;your_project_name&#39; with your project name. The -l info flag sets the logging level to info, so you can see what the worker is doing.</p><h3>Monitoring Celery Tasks (Optional but Recommended)</h3><p>For production environments, monitoring your Celery tasks is crucial. Tools like <strong>Flower</strong> provide a web-based interface to monitor task progress, success, failure, and worker status.</p><p>To install Flower:</p><pre>pip install flower</pre><p>To run Flower:</p><pre>celery -A your_project_name flower</pre><p>Then, you can access the Flower dashboard in your web browser, typically at <a href="http://localhost:5555.">http://localhost:5555.</a></p><h3>Conclusion</h3><p>Congratulations! We succesfully configuring celery for our background tasks.</p><p>Integrating Celery with your Django application empowers you to handle time-consuming tasks efficiently without impacting the responsiveness of your web interface. By offloading these operations to background workers, you can significantly improve user experience and build more robust and scalable applications. Happy Coding!</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a7d2cf2255a" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/level-up-your-django-app-tackling-background-tasks-with-celery-5a7d2cf2255a">Level Up Your Django App: Tackling Background Tasks with Celery</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up Persistent Storage for Django Using Docker and Google Cloud Storage]]></title>
            <link>https://medium.com/@naufalichsan/how-to-set-up-persistent-storage-for-django-using-docker-and-google-cloud-storage-1cacbc5f8f33?source=rss-32d132a20d81------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cacbc5f8f33</guid>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-volume]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[cloud-storage]]></category>
            <dc:creator><![CDATA[Naufal Ichsan]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 05:20:18 GMT</pubDate>
            <atom:updated>2025-04-21T03:32:55.326Z</atom:updated>
            <content:encoded><![CDATA[<h3>Never Lose Your Data Again: Persistent Django Storage with Docker &amp; Google Cloud</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dODdHHr5QZ0Ic8epY54NSg.png" /><figcaption>Source: Google.com</figcaption></figure><p>When deploying a Django application, one common challenge is <strong>storing user-uploaded files or static assets persistently</strong> — especially when using Docker. Without persistent storage, your files will disappear every time you rebuild or restart a container.</p><p>In this guide, we’ll walk you through how to set up persistent storage for Django using <strong>Docker volumes for local development</strong> and <strong>Google Cloud Storage (GCS) for production</strong>. Whether you’re just starting with deployment or want to make your app cloud-ready, this article is for you.</p><h4>🧑‍💻 Local Development with Docker Volumes</h4><p>Let’s assume you have a standard Dockerized Django setup.</p><p><strong>Step 1: Define Volume in </strong><strong>docker-compose.yml</strong></p><pre>services:<br>  web:<br>    build: .<br>    volumes:<br>      - media_data:/app/media<br>    ...<br><br>volumes:<br>  media_data:</pre><p>or if you not using docker compose you can create volumes manually and bind it to container when using docker run,</p><pre>docker volume create media_data</pre><pre>docker run -v media_data:/app/media your-docker-images</pre><p><strong>Step 2: Update Django Settings</strong></p><p>Update your settings.py to include <strong>MEDIA_URL</strong> and <strong>MEDIA_ROOT</strong></p><pre># settings.py<br><br>MEDIA_URL = &#39;/media/&#39;<br>MEDIA_ROOT = BASE_DIR / &#39;media&#39;</pre><p><strong>Step 3: Expose Media in Development (Optional)</strong></p><p>Add urls to serve your media</p><pre># project/urls.py<br><br>from django.conf import settings<br>from django.conf.urls.static import static<br><br>urlpatterns = [<br>    # your routes<br>] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)</pre><p>Congratulations! We succesfully utilize docker volumes as persistence storage for development environment.</p><h4>☁️ Production Setup with Google Cloud Storage</h4><p>When deploying to production (e.g., GCP VM or Cloud Run), you don’t want to rely on local storage. Instead, offload media files to <strong>Google Cloud Storage (GCS)</strong>.</p><p><strong>Step 1: Install Required Packages</strong></p><pre>pip install django-storages[google]</pre><p><strong>Step 2: Get your Google Service Account</strong></p><p>Create your service account and make sure that service account has access to your GCS bucket, you can read how to create service account from <a href="https://cloud.google.com/iam/docs/service-accounts-create">here</a>.</p><p>After creating your service account, export it as json and put it inside your project root directory</p><p><em>notes: don’t push your service-account.json to public repository as it should be private and secrets.</em></p><p><strong>Step 4: Configure GCS in settings.py</strong></p><pre>GCS_CREDENTIAL = base64.b64decode(env(&#39;GCS_CREDENTIAL&#39;))<br>STORAGES = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;storages.backends.gcloud.GoogleCloudStorage&quot;,<br>        &quot;OPTIONS&quot;: {<br>            &quot;bucket_name&quot;: &lt;YOUR-BUCKET-NAME&gt;,<br>            &quot;project_id&quot;: &lt;YOUR-PROJECT-ID&gt;,<br>            &quot;credentials&quot;: service_account.Credentials.from_service_account_info(json.loads(GCS_CREDENTIAL)),<br>        }<br>    },<br>    &quot;staticfiles&quot;: {<br>        &quot;BACKEND&quot;: &quot;django.contrib.staticfiles.storage.StaticFilesStorage&quot;,<br>        <br>    }<br>}</pre><p>Congratulations! we succesfully configuring django default_storages to use GCS, now everytime you use default_storages it will automatically upload to your GCS Bucket.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cacbc5f8f33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Your Django Deployments: CI/CD with Docker & GitHub Actions]]></title>
            <link>https://python.plainenglish.io/implementing-ci-cd-for-django-project-using-docker-and-github-workflows-0400db74bb51?source=rss-32d132a20d81------2</link>
            <guid isPermaLink="false">https://medium.com/p/0400db74bb51</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Naufal Ichsan]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 08:15:51 GMT</pubDate>
            <atom:updated>2025-05-27T06:00:21.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDjT_7vzzlycqJIYE-ObOg.png" /><figcaption>Source: Google Images</figcaption></figure><h4>Introduction</h4><p>We will learn to set up a CI/CD pipeline for our Django project, utilizing Docker for containerization and GitHub Workflows for automation. Our deployment target will be Google Compute Engine (GCE).</p><p>In this guide, we’ll walk through the entire setup, from containerizing the Django application to automating the build, test, and deployment process.</p><h4>Prerequisite</h4><ul><li><a href="https://medium.com/@naufalichsan114/creating-different-django-environment-configuration-fc4e29b7e29d">Creating Different Django Environment Configuration</a></li><li>Install docker on your local and VM</li><li>Create dockerhub account</li></ul><h4><strong>1. Setup Docker</strong></h4><p>first of all we need to create our Dockerfile inside our project root, the Dockerfile content will be like this:</p><pre># Use a lightweight Python base image<br>FROM python:3.10-slim<br><br># Set environment variables<br>ENV PYTHONDONTWRITEBYTECODE 1<br>ENV PYTHONUNBUFFERED 1<br><br># Set the working directory inside the container<br>WORKDIR /app<br><br># Install system dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    gcc \<br>    libpq-dev \<br>    &amp;&amp; apt-get clean<br><br># Copy requirements.txt and install Python dependencies<br>COPY ./requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY ./entrypoint.sh .<br><br># Copy application code to the container<br>COPY . .<br><br># Expose the application port<br>EXPOSE 8000<br><br>#Execute Entrypoint when container is made<br>RUN [&quot;chmod&quot;, &quot;+x&quot;, &quot;entrypoint.sh&quot;]<br>ENTRYPOINT [ &quot;./entrypoint.sh&quot; ]</pre><p>We can see that the entrypoint of our docker images is using a script called entrypoint.sh, therefore we also need to create entrypoint.sh at our project root, here’s content of our entrypoint.sh:</p><pre>#!/bin/bash<br><br>echo &quot;Migrating&quot;<br>python manage.py showmigrations<br>python manage.py migrate<br>echo &quot;Seeding Dummy Data&quot; #Optional for data seeding<br>python manage.py load_fixtures fixtures/ #Optional for data seeding<br>echo &quot;Collecting static files&quot;<br>python manage.py collectstatic --noinput<br>echo &quot;Run App&quot;<br>gunicorn --bind 0.0.0.0:8000 &lt;your-app&gt;.wsgi:application<br>exec&quot;$@&quot;</pre><p>This is the flow of entrypoint.sh which will be executed when you use <em>docker run</em></p><ul><li>Migrate your data to your database</li><li>Seed data to your database (optional) → in my case the fixtures is stored inside <strong>fixtures/ </strong>folder</li><li>Collecting static files</li><li>Run your application using gunicorn (don’t forget to change &lt;your-app&gt; with your project name)</li></ul><p>Last but not least we need to add .dockerignore to ignore some files/folders like env, node_modules when we building our docker images,</p><p>put all of these files in our .dockerignore:</p><pre>**/*.pyc<br>**/*.pyo<br>**/*.mo<br>**/*.db<br>**/*.css.map<br>**/*.egg-info<br>**/*.sql.gz<br>**/__pycache__/<br>.cache<br>.project<br>.idea<br>.pydevproject<br>.idea/workspace.xml<br>.DS_Store<br>.git/<br>.sass-cache<br>.vagrant/<br>.scannerwork/<br>sonar-project.properties<br>dist<br>docs<br>env<br>logs<br>src/{{ project_name }}/settings/local.py<br>src/node_modules<br>web/media<br>web/static/CACHE<br>stats<br>Dockerfile<br>.gitignore<br>Dockerfile<br>db.sqlite3<br>**/*.md<br>logs/</pre><h4>2. Create Dockerhub Repository and Generate Dockerhub Token</h4><p>First, we need to create our dockerhub repository for storing our docker images</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEo7vKA9XpYp7h7o_H1KTQ.png" /><figcaption>Create Dockerhub Repository</figcaption></figure><p>After we create our repository we need to generate our dockerhub token so our CI/CD can access that repository, to create dockerhub token you should go to Account Settings &gt; Personal Access Token &gt; Generate new token,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osl3-u9SXYgxmGxtnz_3og.png" /><figcaption>Generate Dockerhub Token</figcaption></figure><p>Set the Access permissions to <em>Read &amp; Write</em> as it will be used in our CI/CD pipelines. After creating your token don’t forget to save your token somewhere as it won’t be showed to us anymore.</p><h4>3. Prepare ci-cd.yml</h4><p>Before we create our CI/CD script, we should create .github/workflows inside our project root, github by default will mark that folder as workflows folders. Then we create our ci-cd.yml files inside that folder.</p><p>The ci-cd.yml file should be structured as follows:</p><pre>name: CI/CD Pipeline<br><br>on:<br>    push:<br>        branches:<br>            - main<br>            - dev<br><br>env:<br>    SSH_AUTH_SOCK: /tmp/ssh_agent.sock<br><br>jobs:<br>    test:<br>        name: Run Unit Test<br>        runs-on: ubuntu-latest<br>        steps: <br>            - name: Checkout Repository<br>              uses: actions/checkout@v4<br>            - name: check directory<br>              run: ls -al<br>            - name: Setup Python<br>              uses: actions/setup-python@v5<br>              with:<br>                python-version: &#39;3.13&#39;<br>            - name: Install Requirements<br>              run: |<br>                pip install -r requirements.txt<br>                python -m pip install --upgrade pip<br>            - name: Set Up Environment<br>              run: echo &quot;SECRET_KEY=${{ secrets.DJANGO_SECRET_KEY }}&quot; &gt;&gt; $GITHUB_ENV<br>            - name: Run Test<br>              run: |<br>                coverage run --include=&#39;**/models.py,**/views.py,**/serializers.py&#39; --omit=&#39;env/*,*/opt/*&#39; manage.py test<br>                coverage report -m --fail-under=80<br><br>    build:<br>        name: Build &amp; Publish Docker Image<br>        runs-on: ubuntu-latest<br>        needs: test<br>        steps:<br>            - name: Checkout Repository<br>              uses: actions/checkout@v4<br>            - name: check directory<br>              run: ls -al<br>            - name: Set Up Environment<br>              run: |<br>                if [ &quot;${{ github.ref_name }}&quot; == &quot;dev&quot; ]; then<br>                    echo &quot;IMAGE_TAG=dev&quot; &gt;&gt; $GITHUB_ENV<br>                elif [ &quot;${{ github.ref_name }}&quot; == &quot;main&quot; ]; then<br>                    echo &quot;IMAGE_TAG=latest&quot; &gt;&gt; $GITHUB_ENV<br>                fi<br>            - name: Docker login<br>              run: echo ${{ secrets.DOCKER_ACCESS_TOKEN }} | docker login -u ${{ secrets.REGISTRY_USER }} --password-stdin docker.io<br>            - name: Set Docker BuildKit<br>              run: export DOCKER_BUILDKIT=1<br>            - name: Build Docker Image<br>              run: |<br>                  docker build -t ${{ secrets.REGISTRY_USER }}/${{ secrets.IMAGE_NAME }}:${{ env.IMAGE_TAG }} .<br>                  docker push ${{ secrets.REGISTRY_USER }}/${{ secrets.IMAGE_NAME }}:${{ env.IMAGE_TAG }}<br><br>    deploy:<br>        name: Deploy to GCP<br>        runs-on: ubuntu-latest<br>        needs: build<br>        steps:<br>            - name: Checkout Repository<br>              uses: actions/checkout@v4<br>            - name: Install SSH client<br>              run: sudo apt-get install openssh-client<br>            - name: Set Up Environment<br>              run: |<br>                if [ &quot;${{ github.ref_name }}&quot; == &quot;dev&quot; ]; then<br>                    echo &quot;DJANGO_SETTINGS_MODULE=${{ secrets.STAGING_DJANGO_SETTINGS_MODULE }}&quot; &gt;&gt; $GITHUB_E<br>                    echo &quot;PORT=8003&quot; &gt;&gt; $GITHUB_ENV<br>                    echo &quot;CONTAINER_NAME=myapp-dev&quot; &gt;&gt; $GITHUB_ENV<br>                    echo &quot;IMAGE_TAG=dev&quot; &gt;&gt; $GITHUB_ENV<br>                elif [ &quot;${{ github.ref_name }}&quot; == &quot;main&quot; ]; then<br>                    echo &quot;DJANGO_SETTINGS_MODULE=${{ secrets.PROD_DJANGO_SETTINGS_MODULE }}&quot; &gt;&gt; $GITHUB_ENV<br>                    echo &quot;PORT=8000&quot; &gt;&gt; $GITHUB_ENV<br>                    echo &quot;CONTAINER_NAME=myapp&quot; &gt;&gt; $GITHUB_ENV<br>                    echo &quot;IMAGE_TAG=latest&quot; &gt;&gt; $GITHUB_ENV<br>                fi<br><br>            - name: Setup SSH passphrase<br>              run: |<br>                ssh-agent -a $SSH_AUTH_SOCK &gt; /dev/null<br>                echo &#39;echo ${{ secrets.GCE_SSH_PASSPHRASE }}&#39; &gt; ~/.ssh_askpass &amp;&amp; chmod +x ~/.ssh_askpass<br>                echo &quot;${{ secrets.GCE_SSH_KEY }}&quot; | tr -d &#39;\r&#39; | DISPLAY=None SSH_ASKPASS=~/.ssh_askpass ssh-add - &gt;/dev/null<br>            - name: Deploy to GCP<br>              uses: appleboy/ssh-action@v1.0.3<br>              with:<br>                host: ${{ secrets.GCE_IP }}<br>                username: ${{ secrets.GCE_USERNAME }}<br>                key: ${{ secrets.GCE_SSH_KEY }}<br>                passphrase: ${{ secrets.GCE_SSH_PASSPHRASE }}<br>                script: |<br>                    echo ${{ secrets.DOCKER_ACCESS_TOKEN }} | sudo docker login -u ${{ secrets.REGISTRY_USER }} --password-stdin docker.io<br>                    sudo docker container rm -f ${{ env.CONTAINER_NAME }} || true &amp;&amp;<br>                    sudo docker image rm -f ${{ secrets.REGISTRY_USER }}/${{ secrets.IMAGE_NAME }}:${{ env.IMAGE_TAG }} || true &amp;&amp;<br>                    sudo docker pull ${{ secrets.REGISTRY_USER }}/${{ secrets.IMAGE_NAME }}:${{ env.IMAGE_TAG }} || true &amp;&amp;<br>                    sudo docker run --name ${{ env.CONTAINER_NAME }} \<br>                        -d \<br>                        -p ${{ env.PORT }}:8000 \<br>                        -e DJANGO_SETTINGS_MODULE=&#39;${{ env.DJANGO_SETTINGS_MODULE }}&#39; \<br>                        -e ALLOWED_HOST=&#39;${{ secrets.DJANGO_ALLOWED_HOSTS }}&#39; \<br>                        -e SECRET_KEY=&#39;${{ secrets.DJANGO_SECRET_KEY }}&#39; \<br>                        --network ${{ secrets.DOCKER_NETWORK }} \<br>                        ${{ secrets.REGISTRY_USER }}/${{ secrets.IMAGE_NAME }}:${{ env.IMAGE_TAG }}</pre><p>We can see that’s there’s a lot of github secrets used in the script. Here’s the explanation of each secrets,</p><ul><li><em>DJANGO_SECRET_KEY</em>: django secret key, usually placed on settings.py</li><li><em>DOCKER_ACCESS_TOKEN</em>: dockerhub token that we generated before</li><li><em>REGISTRY_USER</em>: Dockerhub username</li><li><em>IMAGE_NAME</em>: Docker image name usually same as repository name in dockerhub</li><li><em>STAGING_DJANGO_SETTINGS_MODULE</em>: settings module used in development/test environment in our case from <a href="https://medium.com/@naufalichsan114/creating-different-django-environment-configuration-fc4e29b7e29d">this article</a>, it will be “osbanas.config.settings_test”</li><li><em>PROD_DJANGO_SETTINGS_MODULE</em>: settings module used in development/test environment in our case from <a href="https://medium.com/@naufalichsan114/creating-different-django-environment-configuration-fc4e29b7e29d">this article</a>, it will be “osbanas.config.settings_prod”</li><li><em>DJANGO_ALLOWED_HOSTS</em>: allowed host in settings.py django</li><li>GCE_IP: GCP VM external IP</li><li>GCE_USERNAME: username that used to access GCP VM via SSH</li><li>GCE_SSH_KEY: private ssh-key that used for accessing GCP VM</li><li>GCE_SSH_PASSPHRASE: passphrase of ssh-key (remove the line that use this secrets in our script if your ssh key don’t have passphrases)</li></ul><p>Before pushing your repository to github, make sure you already add all of the secrets in your github repository secrets.</p><p>Remember that we still use django default db.sqlite2 even for our deployment, therefore each time we deploy our image to GCE, it will restart our database (nonpersistent). Next we will setup postgresql for our django project persistent database.</p><h4>Next Content:</h4><ul><li>Integrating Postgresql with Django Project</li></ul><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0400db74bb51" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/implementing-ci-cd-for-django-project-using-docker-and-github-workflows-0400db74bb51">Automate Your Django Deployments: CI/CD with Docker &amp; GitHub Actions</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy with Confidence: Setting Up Django Environments the Right Way]]></title>
            <link>https://python.plainenglish.io/creating-different-django-environment-configuration-fc4e29b7e29d?source=rss-32d132a20d81------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc4e29b7e29d</guid>
            <category><![CDATA[production]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Naufal Ichsan]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 18:31:04 GMT</pubDate>
            <atom:updated>2025-05-28T06:24:42.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AU_XkhAL0Ehdb9tMNn7pZQ.png" /><figcaption>Source: Google Images</figcaption></figure><h4>Introduction</h4><p>Creating different environment for production, testing, and development can be challenging for beginner, in this chapter we will see how we can create django configuration files for each environment in a simple way.</p><p>I will assumpt we are already knows how to create basic django project along with creating and running python virtual environment, so we can focus on managing different configuration for our django project.</p><h4><strong>1. Create Config Files</strong></h4><p>First, we need to create config folder inside our project folder, don’t forget to add <em>__init__.py</em> to mark your folder as a package so Django and manage.py can recognize it properly, now our project folder will look like this,</p><pre>- your-project-folder<br>  - __init__.py<br>  - config<br>    - __init__.py<br>  - asgi.py<br>  - urls.py<br>  - settings.py<br>  - wsgi.py</pre><p>we will move <em>settings.py</em> to config folder and we will create another file called <em>settings_prod.py</em> for production and <em>settings_test.py</em> for testing purposes.</p><pre>- your-project-folder<br>  - config<br>    - __init__.py<br>    - settings.py<br>    - settings_prod.py<br>    - settings_test.py<br>  - __init__.py<br>  - asgi.py<br>  - urls.py<br>  - wsgi.py</pre><p>now we already finished restructuring our folder structure to create different environment configuration for our Django project. we gonna treat <em>settings.py</em> as a local development configuration and a base for our <em>settings_prod.py</em> and <em>settings_test.py</em> by importing it to both files, so every configuration inside <em>settings.py</em> will be applied to both <em>settings_prod.py </em>and <em>settings_test.py.</em></p><p>Now here’s the handy things, we can just override configuration from <em>settings.py </em>by rewriting configuration that you need inside your production/test settings, so we don’t need to rewrite everything again in each configuration files. For example, below I try to override django default DEBUG to False and Database to use postgres.</p><pre>from .settings import *<br><br>#Override everything that need to be overriden here.<br>DEBUG = False<br><br>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>        &#39;NAME&#39;: &#39;postgres&#39;, <br>        &#39;USER&#39;: &#39;postgres&#39;,<br>        &#39;PASSWORD&#39;: &#39;postgres&#39;,<br>        &#39;HOST&#39;: &#39;127.0.0.1&#39;, <br>        &#39;PORT&#39;: &#39;5432&#39;,<br>    }<br>}</pre><p>in this example our DEBUG and DATABASES config will be overriden, but other config will remain from <em>settings.py</em>.</p><p>One more step, we need to ensure <em>manage.py, wsgi.py</em>, and <em>asgi.py </em>refers to the correct <em>settings.py </em>files. Because we move our <em>settings.py </em>to config folder we also need to change the reference in those three files from,</p><pre>os.environ.setdefault(&#39;DJANGO_SETTINGS_MODULE&#39;, &#39;your-project-folder.settings&#39;)</pre><p>to,</p><pre>os.environ.setdefault(&#39;DJANGO_SETTINGS_MODULE&#39;, &#39;your-project-folder.config.settings&#39;)</pre><p>Here DJANGO_SETTINGS_MODULE is environment variable that stores our custom config files (production/test environment) and will be provided in our <em>.env</em> files (local development) or CI/CD secrets (production). If DJANGO_SETTINGS_MODULE not provided in your environment variables, then it will use your-project-folder.config.settings which is your <em>settings.py </em>as default configuration files<em>.</em></p><p>Congratulations! We succesfully implemented different environment configuration for our Django Project!</p><h4>2. Using Django-Environ for Environment Variables</h4><p>One of the main security issues when we try to create an environment ready for production is security for sensitive credential. We can’t just hardcoded our sensitive credential like database username and password for production in our version control. To solve this issue we will use django-environ to store sensitive credential inside environment variables, you can use os.environ too, but for me django-environ is more easy to use.</p><p>First we need to install it or add it in requirements.txt (recommended),</p><pre>pip install django-environ</pre><p>After that, we need to import and use it inside our <em>settings.py</em></p><pre>import os<br>from pathlib import Path<br>import environ<br><br>BASE_DIR = Path(__file__).resolve().parent.parent.parent<br><br>env = environ.Env()<br>env.read_env(os.path.join(BASE_DIR, &#39;.env&#39;))</pre><blockquote>Note: here BASE_DIR is Path(__file__).resolve().<em>parent.parent.parent</em> (using parent three times) because we locate our settings.py inside your-project-folder/config</blockquote><p>Now we can change every database credential used in production environment using env from environ.Env() like this,</p><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>        &#39;NAME&#39;: env(&#39;DB_NAME&#39;), <br>        &#39;USER&#39;: env(&#39;DB_USER&#39;),<br>        &#39;PASSWORD&#39;: env(&#39;DB_PASSWORD&#39;),<br>        &#39;HOST&#39;: env(&#39;DB_HOST&#39;), <br>        &#39;PORT&#39;: env(&#39;DB_PORT&#39;),<br>    }<br>}</pre><p>We can store the environment in version control secrets like Github Secrets to manage it in our CI/CD.</p><p>Congratulations we succesfully utilizing django-environ and secured our sensitive credentials such as databases credential using environment variables.</p><h4>Next Content:</h4><ul><li><a href="https://medium.com/@naufalichsan114/implementing-ci-cd-for-django-project-using-docker-and-github-workflows-0400db74bb51">Implementing CI/CD Using Docker and Github Workflows</a></li></ul><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc4e29b7e29d" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/creating-different-django-environment-configuration-fc4e29b7e29d">Deploy with Confidence: Setting Up Django Environments the Right Way</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>