<?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 Yoseph Parai on Medium]]></title>
        <description><![CDATA[Stories by Yoseph Parai on Medium]]></description>
        <link>https://medium.com/@yosephoche?source=rss-abf46fdec084------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*kjffVnhx22gBk9uHIzCsiA.png</url>
            <title>Stories by Yoseph Parai on Medium</title>
            <link>https://medium.com/@yosephoche?source=rss-abf46fdec084------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 06:26:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yosephoche/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[DevOps for Startups: Dockerizing Django Applications]]></title>
            <link>https://medium.com/@yosephoche/devops-for-startups-dockerizing-django-applications-a060b2df4fd8?source=rss-abf46fdec084------2</link>
            <guid isPermaLink="false">https://medium.com/p/a060b2df4fd8</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[startupş]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Yoseph Parai]]></dc:creator>
            <pubDate>Fri, 01 May 2026 02:46:01 GMT</pubDate>
            <atom:updated>2026-05-01T02:46:01.360Z</atom:updated>
            <content:encoded><![CDATA[<p>From “it works on my machine” to production-ready deployments in a weekend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LxRp49azbeGuYfIn" /></figure><p>I still remember the deployment that broke me.</p><p>It was a Friday afternoon. A client needed a small bug fix deployed before the weekend. “It should only take 5 minutes,” I said. Famous last words.</p><p>The server was missing a dependency. Then Python version mismatch. Then a database configuration issue. Then Nginx wasn’t configured correctly. Four hours later, I was still debugging while the client waited.</p><p>That weekend, I Dockerized everything. It took me a day to set up, but it changed my life. Now that same deployment takes 5 minutes — and I can do it from my phone.</p><p>This is the guide I wish I’d had then. It’s everything you need to containerize your Django application and deploy with confidence.</p><h3>Why Docker Matters for Startups</h3><p>You might be thinking: “I’m a small team, do I really need Docker?”</p><p>The short answer: Yes. Here’s why:</p><ul><li><strong>Consistency</strong> — The same environment from your laptop to production</li><li><strong>Reproducibility</strong> — Roll back instantly when things go wrong</li><li><strong>Speed</strong> — New developers onboard in minutes, not days</li><li><strong>Scaling</strong> — Add more servers without configuration headaches</li><li><strong>Cost</strong> — Optimize resource usage, pay only for what you need</li></ul><p>Docker isn’t just for big teams with complex infrastructure. It’s your insurance policy against deployment nightmares.</p><h3>Understanding the Basics</h3><p>Before we dive in, let’s clarify the terminology:</p><ul><li><strong>Image</strong> — A read-only template for creating containers</li><li><strong>Container</strong> — A running instance of an image</li><li><strong>Dockerfile</strong> — Instructions for building an image</li><li><strong>docker-compose.yml</strong> — Configuration for multi-container applications</li><li><strong>Volume</strong> — Persistent storage outside the container</li></ul><h3>Creating Your First Dockerfile</h3><p>Let’s start with a production-ready Dockerfile for Django:</p><pre># Dockerfile<br># Use Python slim image for smaller size<br>FROM python:3.11-slim as base</pre><pre># Set environment variables<br>ENV PYTHONDONTWRITEBYTECODE=1<br>ENV PYTHONUNBUFFERED=1<br>ENV PIP_NO_CACHE_DIR=1<br>ENV PIP_DISABLE_PIP_VERSION_CHECK=1</pre><pre># Set work directory<br>WORKDIR /app</pre><pre># Install system dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    build-essential \<br>    libpq-dev \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><pre># Install Python dependencies<br>COPY requirements/prod.txt .<br>RUN pip install --no-cache-dir -r requirements/prod.txt</pre><pre># Copy application code<br>COPY . .</pre><pre># Collect static files<br>RUN python manage.py collectstatic --noinput || true</pre><pre># Multi-stage build for production<br>FROM base as production</pre><pre># Create non-root user for security<br>RUN useradd --create-home appuser<br>USER appuser</pre><pre># Expose port<br>EXPOSE 8000</pre><pre># Health check<br>HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \<br>    CMD curl -f <a href="http://localhost:8000/health/">http://localhost:8000/health/</a> || exit 1</pre><pre># Run with Gunicorn<br>CMD [&quot;gunicorn&quot;, &quot;config.wsgi:application&quot;, &quot;--bind&quot;, &quot;:8000&quot;, &quot;--workers&quot;, &quot;4&quot;, &quot;--worker-class&quot;, &quot;sync&quot;]</pre><blockquote><strong>Security Tip:</strong> Never run containers as root. The multi-stage build creates a non-root user for production, reducing the attack surface if the container is compromised.</blockquote><h3>Organizing Dependencies</h3><p>Separate your dependencies for different environments:</p><pre># requirements/base.txt<br>Django&gt;=4.2,&lt;5.0<br>djangorestframework&gt;=3.14<br>psycopg2-binary&gt;=2.9<br>celery&gt;=5.3<br>redis&gt;=4.5<br>django-cors-headers&gt;=4.0<br>djangorestframework-simplejwt&gt;=5.3<br>gunicorn&gt;=21.0<br>Pillow&gt;=10.0<br>python-dotenv&gt;=1.0</pre><pre># requirements/dev.txt<br>-r base.txt<br>pytest&gt;=7.4<br>pytest-django&gt;=4.5<br>pytest-cov&gt;=4.1<br>factory-boy&gt;=3.3<br>black&gt;=23.0<br>flake8&gt;=6.0<br>isort&gt;=5.12<br>ipython&gt;=8.0</pre><pre># requirements/prod.txt<br>-r base.txt<br>sentry-sdk&gt;=1.30<br>gunicorn[gevent]&gt;=21.0<br>redis&gt;=4.5</pre><h3>Docker Compose for Local Development</h3><p>For local development, we’ll use Docker Compose to run Django along with PostgreSQL and Redis:</p><pre># docker-compose.yml<br>version: &#39;3.8&#39;</pre><pre>services:<br>  web:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>      target: base  # Use base for development<br>    ports:<br>      - &quot;8000:8000&quot;<br>    environment:<br>      - DEBUG=1<br>      - DATABASE_URL=postgres://postgres:postgres@db:5432/mydb<br>      - REDIS_URL=redis://redis:6379/0<br>      - DJANGO_SETTINGS_MODULE=config.settings.development<br>    volumes:<br>      - .:/app<br>      - static_volume:/app/staticfiles<br>      - media_volume:/app/media<br>    depends_on:<br>      db:<br>        condition: service_healthy<br>      redis:<br>        condition: service_started<br>    command: python manage.py runserver 0.0.0.0:8000</pre><pre>  db:<br>    image: postgres:15-alpine<br>    environment:<br>      - POSTGRES_DB=mydb<br>      - POSTGRES_USER=postgres<br>      - POSTGRES_PASSWORD=postgres<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    ports:<br>      - &quot;5432:5432&quot;<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U postgres&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      retries: 5</pre><pre>  redis:<br>    image: redis:7-alpine<br>    ports:<br>      - &quot;6379:6379&quot;<br>    volumes:<br>      - redis_data:/data</pre><pre>  celery:<br>    build: .<br>    command: celery -A config worker -l info<br>    environment:<br>      - DATABASE_URL=postgres://postgres:postgres@db:5432/mydb<br>      - REDIS_URL=redis://redis:6379/0<br>    volumes:<br>      - .:/app<br>    depends_on:<br>      - db<br>      - redis</pre><pre>volumes:<br>  postgres_data:<br>  redis_data:<br>  static_volume:<br>  media_volume:</pre><h3>Environment Variables Management</h3><p>Use environment variables for configuration, never hardcode secrets:</p><pre># .env.example (safe to commit)<br>DEBUG=True<br>DJANGO_SECRET_KEY=your-secret-key-here<br>ALLOWED_HOSTS=localhost,127.0.0.1<br>DATABASE_URL=postgres://user:password@localhost:5432/dbname<br>REDIS_URL=redis://localhost:6379/0<br>EMAIL_HOST=smtp.gmail.com<br>EMAIL_PORT=587<br>AWS_ACCESS_KEY_ID=your-key<br>AWS_SECRET_ACCESS_KEY=your-secret</pre><pre># config/settings/development.py<br>import os<br>from .base import *</pre><pre>DEBUG = True</pre><pre>ALLOWED_HOSTS = os.environ.get(&#39;ALLOWED_HOSTS&#39;, &#39;localhost,127.0.0.1&#39;).split(&#39;,&#39;)</pre><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>        &#39;NAME&#39;: os.environ.get(&#39;POSTGRES_DB&#39;, &#39;mydb&#39;),<br>        &#39;USER&#39;: os.environ.get(&#39;POSTGRES_USER&#39;, &#39;postgres&#39;),<br>        &#39;PASSWORD&#39;: os.environ.get(&#39;POSTGRES_PASSWORD&#39;, &#39;postgres&#39;),<br>        &#39;HOST&#39;: os.environ.get(&#39;POSTGRES_HOST&#39;, &#39;localhost&#39;),<br>        &#39;PORT&#39;: os.environ.get(&#39;POSTGRES_PORT&#39;, &#39;5432&#39;),<br>    }<br>}</pre><pre># Use console email backend for development<br>EMAIL_BACKEND = &#39;django.core.mail.backends.console.EmailBackend&#39;</pre><pre># config/settings/production.py<br>import os<br>from .base import *<br>from dotenv import load_dotenv</pre><pre>load_dotenv()</pre><pre>DEBUG = False</pre><pre>SECRET_KEY = os.environ.get(&#39;DJANGO_SECRET_KEY&#39;)</pre><pre>ALLOWED_HOSTS = os.environ.get(&#39;ALLOWED_HOSTS&#39;, &#39;&#39;).split(&#39;,&#39;)</pre><pre># Production database<br>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>        &#39;NAME&#39;: os.environ.get(&#39;POSTGRES_DB&#39;),<br>        &#39;USER&#39;: os.environ.get(&#39;POSTGRES_USER&#39;),<br>        &#39;PASSWORD&#39;: os.environ.get(&#39;POSTGRES_PASSWORD&#39;),<br>        &#39;HOST&#39;: os.environ.get(&#39;POSTGRES_HOST&#39;),<br>        &#39;PORT&#39;: os.environ.get(&#39;POSTGRES_PORT&#39;, &#39;5432&#39;),<br>        &#39;CONN_MAX_AGE&#39;: 60,<br>    }<br>}</pre><pre># Security settings<br>SECURE_SSL_REDIRECT = True<br>SESSION_COOKIE_SECURE = True<br>CSRF_COOKIE_SECURE = True<br>SECURE_BROWSER_XSS_FILTER = True<br>SECURE_CONTENT_TYPE_NOSNIFF = True<br>X_FRAME_OPTIONS = &#39;DENY&#39;</pre><pre># Caching with Redis<br>CACHES = {<br>    &#39;default&#39;: {<br>        &#39;BACKEND&#39;: &#39;django.core.cache.backends.redis.RedisCache&#39;,<br>        &#39;LOCATION&#39;: os.environ.get(&#39;REDIS_URL&#39;),<br>    }<br>}</pre><h3>Optimizing Docker Images</h3><p>Large images mean slow deployments. Here’s how to keep them lean:</p><pre># Bad: Copy everything first, then install dependencies<br>FROM python:3.11<br>COPY . .  # Copies all files including huge node_modules<br>RUN pip install -r requirements.txt  # Cache invalidated on any code change</pre><pre># Good: Install dependencies first, then copy code<br>FROM python:3.11<br>COPY requirements/prod.txt .<br>RUN pip install --no-cache-dir -r requirements.prod.txt<br>COPY . .  # Code changes won&#39;t invalidate pip install layer</pre><pre># Use .dockerignore to exclude unnecessary files<br># .dockerignore<br>__pycache__<br>*.pyc<br>*.pyo<br>*.pyd<br>.Python<br>*.so<br>*.egg<br>*.egg-info<br>dist<br>build<br>.git<br>.gitignore<br>.env<br>.env.example<br>*.md<br>docs<br>tests<br>.coverage<br>htmlcov<br>.venv<br>venv<br>env<br>node_modules<br>.DS_Store<br>*.log</pre><blockquote><strong>Pro Tip:</strong> Use multi-stage builds to keep your production image small. The final image should only contain what’s needed to run the application, not the build tools.</blockquote><h3>Running Commands in Docker</h3><p>Common commands you’ll use daily:</p><pre># Build and start all services<br>docker-compose up --build</pre><pre># Start services in background<br>docker-compose up -d</pre><pre># View logs<br>docker-compose logs -f web</pre><pre># Run management command<br>docker-compose exec web python manage.py migrate</pre><pre># Create superuser<br>docker-compose exec web python manage.py createsuperuser</pre><pre># Run tests<br>docker-compose exec web pytest</pre><pre># Stop all services<br>docker-compose down</pre><pre># Remove volumes too (warning: deletes data)<br>docker-compose down -v</pre><h3>Making Development Smooth</h3><p>Add these quality-of-life improvements to your setup:</p><pre># Volume mounting for hot reloading<br># In docker-compose.yml, the web service already has:<br>volumes:<br>  - .:/app  # Mounts current directory to /app in container</pre><pre># For better performance on macOS, use:<br># volumes:<br>#   - .:/app:cached  # Tell Docker to use cached reads</pre><pre># Add pytest configuration<br># pytest.ini<br>[pytest]<br>DJANGO_SETTINGS_MODULE = config.settings.testing<br>python_files = test_*.py<br>python_classes = Test*<br>python_functions = test_*<br>addopts = --strict-markers --tb=short<br>filterwarnings =<br>    ignore::DeprecationWarning<br>    ignore::PendingDeprecationWarning</pre><h3>Production Deployment</h3><p>Here’s a production Docker Compose setup with Nginx:</p><pre># docker-compose.production.yml<br>version: &#39;3.8&#39;</pre><pre>services:<br>  web:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>      target: production<br>    ports:<br>      - &quot;8000:8000&quot;<br>    environment:<br>      - DEBUG=0<br>      - DJANGO_SETTINGS_MODULE=config.settings.production<br>    env_file:<br>      - .env.production<br>    depends_on:<br>      - db<br>      - redis<br>    restart: unless-stopped</pre><pre>  nginx:<br>    image: nginx:alpine<br>    ports:<br>      - &quot;80:80&quot;<br>      - &quot;443:443&quot;<br>    volumes:<br>      - ./nginx.conf:/etc/nginx/nginx.conf:ro<br>      - static_volume:/app/staticfiles:ro<br>      - media_volume:/app/media:ro<br>    depends_on:<br>      - web<br>    restart: unless-stopped</pre><pre>  db:<br>    image: postgres:15-alpine<br>    env_file:<br>      - .env.production<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    restart: unless-stopped</pre><pre>  redis:<br>    image: redis:7-alpine<br>    restart: unless-stopped</pre><pre>  celery:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>      target: production<br>    command: celery -A config worker -l info<br>    env_file:<br>      - .env.production<br>    depends_on:<br>      - db<br>      - redis<br>    restart: unless-stopped</pre><pre>volumes:<br>  postgres_data:<br>  static_volume:<br>  media_volume:</pre><pre># nginx.conf<br>events {<br>    worker_connections 1024;<br>}</pre><pre>http {<br>    include /etc/nginx/mime.types;<br>    default_type application/octet-stream;</pre><pre>    upstream web {<br>        server web:8000;<br>    }</pre><pre>    server {<br>        listen 80;<br>        server_name yourdomain.com;</pre><pre>        # Static files<br>        location /static/ {<br>            alias /app/staticfiles/;<br>            expires 30d;<br>            add_header Cache-Control &quot;public, immutable&quot;;<br>        }</pre><pre>        # Media files<br>        location /media/ {<br>            alias /app/media/;<br>            expires 7d;<br>        }</pre><pre>        # Proxy to Django<br>        location / {<br>            proxy_pass <a href="http://web;/">http://web;</a><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>            proxy_redirect off;<br>        }<br>    }<br>}</pre><h3>Health Checks</h3><p>Add a health check endpoint to your Django app:</p><pre># apps/core/views.py<br>from django.http import JsonResponse<br>from django.db import connection<br>from django.core.cache import cache<br></pre><pre>def health_check(request):<br>    &quot;&quot;&quot;Health check endpoint for load balancers and orchestration.&quot;&quot;&quot;<br>    checks = {<br>        &#39;database&#39;: check_database(),<br>        &#39;cache&#39;: check_cache(),<br>    }</pre><pre>    all_healthy = all(checks.values())</pre><pre>    return JsonResponse(<br>        {&#39;status&#39;: &#39;healthy&#39; if all_healthy else &#39;unhealthy&#39;, &#39;checks&#39;: checks},<br>        status=200 if all_healthy else 503<br>    )<br></pre><pre>def check_database():<br>    try:<br>        with connection.cursor() as cursor:<br>            cursor.execute(&#39;SELECT 1&#39;)<br>        return True<br>    except Exception:<br>        return False<br></pre><pre>def check_cache():<br>    try:<br>        cache.set(&#39;health_check&#39;, &#39;ok&#39;, 10)<br>        return cache.get(&#39;health_check&#39;) == &#39;ok&#39;<br>    except Exception:<br>        return False</pre><pre># config/urls.py<br>from django.urls import path<br>from apps.core.views import health_check</pre><pre>urlpatterns = [<br>    path(&#39;health/&#39;, health_check, name=&#39;health_check&#39;),<br>]</pre><h3>Common Issues and Solutions</h3><p><strong>Issue:</strong> Container starts but immediately exits<br><strong>Solution:</strong> Check the command and ensure Django can start. Run docker-compose logsto see errors.</p><p><strong>Issue:</strong> Permission denied errors<br><strong>Solution:</strong> Add USER directive in Dockerfile or fix ownership: chown -R appuser:appuser /app</p><p><strong>Issue:</strong> Database connection refused<br><strong>Solution:</strong> Use depends_on with healthcheck in docker-compose, or add wait-for-it script</p><p><strong>Issue:</strong> Static files not loading<br><strong>Solution:</strong> Ensure STATIC_ROOT is set and collectstatic ran. Check Nginx alias path.</p><h3>The Bottom Line</h3><p>Docker isn’t just another tool in your stack — it’s a mindset shift. Once you containerize your application, deployment becomes repeatable, reliable, and boring. And in this business, boring is good.</p><p>Here’s what I always remember:</p><ul><li><strong>Start simple</strong> — You don’t need Kubernetes today</li><li><strong>Separate concerns</strong> — Use docker-compose for local, consider orchestration for scale</li><li><strong>Keep images small</strong> — Use slim images and multi-stage builds</li><li><strong>Never hardcode secrets</strong> — Use environment variables</li><li><strong>Add health checks</strong> — Your future self will thank you</li><li><strong>Test locally first</strong> — If it works in Docker locally, it’ll work in production</li></ul><p>That Friday afternoon deployment that used to take 4 hours? Now I deploy from my phone while waiting for coffee. That’s the power of Docker.</p><h3>What’s Next?</h3><p>In the next article, we’ll dive into CI/CD pipeline setup for Django projects. We’ll cover automated testing, deployment workflows, and how to ship code with confidence.</p><p>Follow along and let’s keep building.</p><p><em>Next article: CI/CD Pipeline Setup for Django Projects</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a060b2df4fd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a RESTful API with Django REST Framework]]></title>
            <link>https://medium.com/@yosephoche/building-a-restful-api-with-django-rest-framework-544b162dac1e?source=rss-abf46fdec084------2</link>
            <guid isPermaLink="false">https://medium.com/p/544b162dac1e</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Yoseph Parai]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 07:02:52 GMT</pubDate>
            <atom:updated>2026-04-28T07:02:52.194Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical guide to creating APIs that developers actually want to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q_SIpH8u-E2Y1806" /></figure><p>I still remember the first API I built with Django.</p><p>It was a simple project management API — users, projects, tasks, the usual. I thought I’d done everything right. Clean models, well-organized views, thorough documentation.</p><p>Then our frontend developer tried to use it.</p><p>“Why does creating a task require three API calls?”</p><p>“Where are the pagination limits? I got 10,000 tasks in one response.”</p><p>“The date format you’re returning doesn’t parse in JavaScript.”</p><p>“How do I filter tasks by status? There’s no endpoint for that.”</p><p>That conversation led to a complete rewrite. But more importantly, it taught me that building an API isn’t just about exposing your models over HTTP. It’s about creating an experience that makes developers productive.</p><p>This is the guide I wish I’d had then. It’s everything I’ve learned about building APIs with Django REST Framework — the patterns that work, the mistakes to avoid, and the details that separate good APIs from great ones.</p><h3>Setting Up Django REST Framework</h3><p>First, let’s get DRF installed and configured properly:</p><pre>pip install djangorestframework django-cors-headers</pre><pre># config/settings/base.py</pre><pre>INSTALLED_APPS = [<br>    # ... other apps<br>    &#39;rest_framework&#39;,<br>    &#39;corsheaders&#39;,<br>    &#39;apps.accounts&#39;,<br>    &#39;apps.projects&#39;,<br>]</pre><pre>MIDDLEWARE = [<br>    # ... other middleware<br>    &#39;corsheaders.middleware.CorsMiddleware&#39;,  # Should be near the top<br>]</pre><pre># DRF Configuration<br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;rest_framework.authentication.SessionAuthentication&#39;,<br>        &#39;rest_framework.authentication.TokenAuthentication&#39;,<br>    ],<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: [<br>        &#39;rest_framework.permissions.IsAuthenticated&#39;,<br>    ],<br>    &#39;DEFAULT_PAGINATION_CLASS&#39;: &#39;rest_framework.pagination.PageNumberPagination&#39;,<br>    &#39;PAGE_SIZE&#39;: 20,<br>    &#39;DEFAULT_RENDERER_CLASSES&#39;: [<br>        &#39;rest_framework.renderers.JSONRenderer&#39;,<br>    ],<br>    &#39;DEFAULT_PARSER_CLASSES&#39;: [<br>        &#39;rest_framework.parsers.JSONParser&#39;,<br>        &#39;rest_framework.parsers.FormParser&#39;,<br>        &#39;rest_framework.parsers.MultiPartParser&#39;,<br>    ],<br>    &#39;EXCEPTION_HANDLER&#39;: &#39;rest_framework.views.exception_handler&#39;,<br>    &#39;DEFAULT_SCHEMA_CLASS&#39;: &#39;rest_framework.schemas.AutoSchema&#39;,<br>}</pre><pre># CORS settings<br>CORS_ALLOWED_ORIGINS = [<br>    &#39;http://localhost:3000&#39;,<br>    &#39;https://yourdomain.com&#39;,<br>]</pre><h3>Designing Your Serializers</h3><p>Serializers are the heart of DRF. They define how your data is validated, transformed, and presented. Here’s how to do them right:</p><pre># apps/projects/serializers.py<br>from rest_framework import serializers<br>from django.contrib.auth import get_user_model<br>from .models import Project, Task, Comment</pre><pre>User = get_user_model()<br></pre><pre>class UserSerializer(serializers.ModelSerializer):<br>    &quot;&quot;&quot;Serializer for user details - no sensitive data exposed.&quot;&quot;&quot;<br>    class Meta:<br>        model = User<br>        fields = [&#39;id&#39;, &#39;email&#39;, &#39;first_name&#39;, &#39;last_name&#39;, &#39;avatar&#39;, &#39;created_at&#39;]<br>        read_only_fields = [&#39;id&#39;, &#39;created_at&#39;]<br></pre><pre>class TaskSerializer(serializers.ModelSerializer):<br>    &quot;&quot;&quot;Serializer for tasks with nested relationships.&quot;&quot;&quot;<br>    # Nested serializers for read-only relationships<br>    assignee = UserSerializer(read_only=True)<br>    assignee_id = serializers.PrimaryKeyRelatedField(<br>        queryset=User.objects.all(),<br>        source=&#39;assignee&#39;,<br>        write_only=True,<br>        required=False,<br>        allow_null=True<br>    )</pre><pre>    # Computed fields<br>    is_overdue = serializers.SerializerMethodField()<br>    comment_count = serializers.SerializerMethodField()</pre><pre>    # Human-readable status<br>    status_display = serializers.CharField(source=&#39;get_status_display&#39;, read_only=True)</pre><pre>    class Meta:<br>        model = Task<br>        fields = [<br>            &#39;id&#39;, &#39;title&#39;, &#39;description&#39;, &#39;status&#39;, &#39;status_display&#39;,<br>            &#39;priority&#39;, &#39;assignee&#39;, &#39;assignee_id&#39;, &#39;project&#39;,<br>            &#39;due_date&#39;, &#39;is_overdue&#39;, &#39;comment_count&#39;,<br>            &#39;created_at&#39;, &#39;updated_at&#39;<br>        ]<br>        read_only_fields = [&#39;id&#39;, &#39;created_at&#39;, &#39;updated_at&#39;]</pre><pre>    def get_is_overdue(self, obj):<br>        return obj.due_date and obj.due_date &lt; timezone.now() and obj.status != &#39;done&#39;</pre><pre>    def get_comment_count(self, obj):<br>        return obj.comments.count()</pre><pre>    def validate(self, attrs):<br>        &quot;&quot;&quot;Cross-field validation.&quot;&quot;&quot;<br>        if attrs.get(&#39;due_date&#39;) and attrs.get(&#39;status&#39;) == &#39;done&#39;:<br>            attrs[&#39;completed_at&#39;] = timezone.now()<br>        return attrs<br></pre><pre>class ProjectSerializer(serializers.ModelSerializer):<br>    &quot;&quot;&quot;Serializer for projects with nested tasks.&quot;&quot;&quot;<br>    tasks = TaskSerializer(many=True, read_only=True)<br>    owner = UserSerializer(read_only=True)<br>    task_count = serializers.SerializerMethodField()<br>    completed_task_count = serializers.SerializerMethodField()</pre><pre>    class Meta:<br>        model = Project<br>        fields = [<br>            &#39;id&#39;, &#39;name&#39;, &#39;description&#39;, &#39;owner&#39;,<br>            &#39;tasks&#39;, &#39;task_count&#39;, &#39;completed_task_count&#39;,<br>            &#39;is_active&#39;, &#39;created_at&#39;, &#39;updated_at&#39;<br>        ]<br>        read_only_fields = [&#39;id&#39;, &#39;created_at&#39;, &#39;updated_at&#39;]</pre><pre>    def get_task_count(self, obj):<br>        return obj.tasks.count()</pre><pre>    def get_completed_task_count(self, obj):<br>        return obj.tasks.filter(status=&#39;done&#39;).count()</pre><h3>Building Views That Scale</h3><p>Now let’s build views that handle all the CRUD operations plus filtering, sorting, and pagination:</p><pre># apps/projects/views.py<br>from rest_framework import viewsets, filters, status<br>from rest_framework.decorators import action<br>from rest_framework.response import Response<br>from rest_framework.permissions import IsAuthenticated<br>from django.db.models import Count, Q<br>from django_filters.rest_framework import DjangoFilterBackend<br>from .models import Project, Task<br>from .serializers import ProjectSerializer, TaskSerializer<br>from .permissions import IsProjectMember, CanManageTask<br></pre><pre>class ProjectViewSet(viewsets.ModelViewSet):<br>    &quot;&quot;&quot;ViewSet for managing projects.&quot;&quot;&quot;<br>    serializer_class = ProjectSerializer<br>    permission_classes = [IsAuthenticated]<br>    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]<br>    filterset_fields = [&#39;is_active&#39;, &#39;owner&#39;]<br>    search_fields = [&#39;name&#39;, &#39;description&#39;]<br>    ordering_fields = [&#39;created_at&#39;, &#39;updated_at&#39;, &#39;name&#39;]<br>    ordering = [&#39;-created_at&#39;]</pre><pre>    def get_queryset(self):<br>        &quot;&quot;&quot;Return projects the user has access to.&quot;&quot;&quot;<br>        return Project.objects.filter(<br>            Q(owner=self.request.user) |<br>            Q(members=self.request.user)<br>        ).annotate(<br>            task_count=Count(&#39;tasks&#39;),<br>            completed_task_count=Count(&#39;tasks&#39;, filter=Q(tasks__status=&#39;done&#39;))<br>        ).distinct()</pre><pre>    def get_permissions(self):<br>        &quot;&quot;&quot;Return permissions based on action.&quot;&quot;&quot;<br>        if self.action in [&#39;create&#39;]:<br>            return [IsAuthenticated()]<br>        elif self.action in [&#39;update&#39;, &#39;partial_update&#39;, &#39;destroy&#39;]:<br>            return [IsAuthenticated(), CanManageTask()]<br>        return [IsAuthenticated()]</pre><pre>    def perform_create(self, serializer):<br>        &quot;&quot;&quot;Set the owner to the current user on create.&quot;&quot;&quot;<br>        serializer.save(owner=self.request.user)</pre><pre>    @action(detail=True, methods=[&#39;get&#39;])<br>    def statistics(self, request, pk=None):<br>        &quot;&quot;&quot;Return project statistics.&quot;&quot;&quot;<br>        project = self.get_object()<br>        tasks = project.tasks.all()</pre><pre>        return Response({<br>            &#39;total_tasks&#39;: tasks.count(),<br>            &#39;by_status&#39;: tasks.values(&#39;status&#39;).annotate(count=Count(&#39;id&#39;)),<br>            &#39;by_priority&#39;: tasks.values(&#39;priority&#39;).annotate(count=Count(&#39;id&#39;)),<br>            &#39;overdue_count&#39;: tasks.filter(<br>                due_date__lt=timezone.now(),<br>                status__in=[&#39;todo&#39;, &#39;in_progress&#39;]<br>            ).count(),<br>        })</pre><pre>    @action(detail=True, methods=[&#39;post&#39;])<br>    def archive(self, request, pk=None):<br>        &quot;&quot;&quot;Archive a project.&quot;&quot;&quot;<br>        project = self.get_object()<br>        project.is_active = False<br>        project.save()<br>        return Response({&#39;status&#39;: &#39;project archived&#39;})<br></pre><pre>class TaskViewSet(viewsets.ModelViewSet):<br>    &quot;&quot;&quot;ViewSet for managing tasks.&quot;&quot;&quot;<br>    serializer_class = TaskSerializer<br>    permission_classes = [IsAuthenticated]<br>    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]<br>    filterset_fields = [&#39;status&#39;, &#39;priority&#39;, &#39;assignee&#39;, &#39;project&#39;]<br>    search_fields = [&#39;title&#39;, &#39;description&#39;]<br>    ordering_fields = [&#39;created_at&#39;, &#39;updated_at&#39;, &#39;due_date&#39;, &#39;priority&#39;]<br>    ordering = [&#39;-created_at&#39;]</pre><pre>    def get_queryset(self):<br>        &quot;&quot;&quot;Return tasks the user has access to.&quot;&quot;&quot;<br>        return Task.objects.filter(<br>            Q(project__owner=self.request.user) |<br>            Q(project__members=self.request.user) |<br>            Q(assignee=self.request.user)<br>        ).select_related(&#39;project&#39;, &#39;assignee&#39;, &#39;project__owner&#39;).prefetch_related(&#39;comments&#39;)</pre><pre>    def get_permissions(self):<br>        &quot;&quot;&quot;Return permissions based on action.&quot;&quot;&quot;<br>        if self.action in [&#39;create&#39;]:<br>            return [IsAuthenticated()]<br>        elif self.action in [&#39;update&#39;, &#39;partial_update&#39;, &#39;destroy&#39;]:<br>            return [IsAuthenticated(), CanManageTask()]<br>        return [IsAuthenticated()]</pre><pre>    @action(detail=False, methods=[&#39;get&#39;])<br>    def my_tasks(self, request):<br>        &quot;&quot;&quot;Return tasks assigned to the current user.&quot;&quot;&quot;<br>        tasks = self.get_queryset().filter(assignee=request.user)<br>        page = self.paginate_queryset(tasks)<br>        if page is not None:<br>            serializer = self.get_serializer(page, many=True)<br>            return self.get_paginated_response(serializer.data)<br>        serializer = self.get_serializer(tasks, many=True)<br>        return Response(serializer.data)</pre><pre>    @action(detail=True, methods=[&#39;post&#39;])<br>    def assign(self, request, pk=None):<br>        &quot;&quot;&quot;Assign a task to a user.&quot;&quot;&quot;<br>        task = self.get_object()<br>        user_id = request.data.get(&#39;user_id&#39;)</pre><pre>        try:<br>            user = User.objects.get(id=user_id)<br>            task.assignee = user<br>            task.save()<br>            return Response(TaskSerializer(task).data)<br>        except User.DoesNotExist:<br>            return Response(<br>                {&#39;error&#39;: &#39;User not found&#39;},<br>                status=status.HTTP_404_NOT_FOUND<br>            )</pre><h3>URL Routing Done Right</h3><p>Configure your URLs to support versioning and include documentation:</p><pre># apps/projects/urls.py<br>from django.urls import path, include<br>from rest_framework.routers import DefaultRouter<br>from .views import ProjectViewSet, TaskViewSet</pre><pre>router = DefaultRouter()<br>router.register(r&#39;projects&#39;, ProjectViewSet, basename=&#39;project&#39;)<br>router.register(r&#39;tasks&#39;, TaskViewSet, basename=&#39;task&#39;)</pre><pre>urlpatterns = [<br>    path(&#39;&#39;, include(router.urls)),<br>]</pre><pre># config/urls.py<br>from django.urls import path, include<br>from rest_framework.schemas import get_schema_view<br>from drf_yasg.views import get_swagger_view<br>from drf_yasg import openapi</pre><pre>schema_view = get_swagger_view(title=&#39;Project Management API&#39;)</pre><pre>urlpatterns = [<br>    # API endpoints<br>    path(&#39;api/v1/&#39;, include(&#39;apps.projects.urls&#39;, namespace=&#39;projects&#39;)),<br>    path(&#39;api/v1/accounts/&#39;, include(&#39;apps.accounts.urls&#39;, namespace=&#39;accounts&#39;)),</pre><pre>    # API documentation<br>    path(&#39;api/docs/&#39;, schema_view, name=&#39;api-docs&#39;),</pre><pre>    # Swagger/ReDoc<br>    path(&#39;swagger/&#39;, get_swagger_view(title=&#39;API Docs&#39;)),<br>    path(&#39;redoc/&#39;, get_swagger_view(title=&#39;ReDoc&#39;, renderer_classes=[RenderersXML]), name=&#39;api-redoc&#39;),<br>]</pre><h3>Advanced Filtering and Search</h3><p>For more complex filtering, create custom filter backends:</p><pre># apps/projects/filters.py<br>from django_filters import rest_framework as filters<br>from django.db.models import Q<br>from .models import Task<br></pre><pre>class TaskFilter(filters.FilterSet):<br>    &quot;&quot;&quot;Custom filters for tasks.&quot;&quot;&quot;<br>    # Filter by date range<br>    due_date_from = filters.DateTimeFilter(field_name=&#39;due_date&#39;, lookup_expr=&#39;gte&#39;)<br>    due_date_to = filters.DateTimeFilter(field_name=&#39;due_date&#39;, lookup_expr=&#39;lte&#39;)</pre><pre>    # Filter by overdue status<br>    overdue = filters.BooleanFilter(method=&#39;filter_overdue&#39;)</pre><pre>    # Full-text search across multiple fields<br>    q = filters.CharFilter(method=&#39;filter_search&#39;)</pre><pre>    # Filter by project name<br>    project_name = filters.CharFilter(field_name=&#39;project__name&#39;, lookup_expr=&#39;icontains&#39;)</pre><pre>    class Meta:<br>        model = Task<br>        fields = [&#39;status&#39;, &#39;priority&#39;, &#39;assignee&#39;, &#39;project&#39;]</pre><pre>    def filter_overdue(self, queryset, name, value):<br>        from django.utils import timezone<br>        if value:<br>            return queryset.filter(<br>                due_date__lt=timezone.now(),<br>                status__in=[&#39;todo&#39;, &#39;in_progress&#39;]<br>            )<br>        return queryset.exclude(<br>            due_date__lt=timezone.now(),<br>            status__in=[&#39;todo&#39;, &#39;in_progress&#39;]<br>        )</pre><pre>    def filter_search(self, queryset, name, value):<br>        return queryset.filter(<br>            Q(title__icontains=value) |<br>            Q(description__icontains=value)<br>        )<br></pre><pre># Usage in views<br>class TaskViewSet(viewsets.ModelViewSet):<br>    # ...<br>    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]<br>    filterset_class = TaskFilter</pre><h3>Handling Errors Gracefully</h3><p>Create custom exception handling for consistent error responses:</p><pre># config/exceptions.py<br>from rest_framework.exceptions import APIException<br>from rest_framework import status   <br><br>class ValidationError(APIException):     <br>    status_code = status.HTTP_400_BAD_REQUEST<br>    default_detail = &#39;Invalid input data.&#39;<br>    default_code = &#39;validation_error&#39;   <br><br><br>class ResourceNotFoundError(APIException):     <br>    status_code = status.HTTP_404_NOT_FOUND     <br>    default_detail = &#39;The requested resource was not found.&#39;     <br>    default_code = &#39;resource_not_found&#39;   <br><br><br>class BusinessLogicError(APIException):     <br>    status_code = status.HTTP_422_UNPROCESSABLE_ENTITY     <br>    default_detail = &#39;Business logic validation failed.&#39;     <br>    default_code = &#39;business_logic_error&#39;   </pre><pre># config/exception_handler.py <br>from rest_framework.views import exception_handler<br>from rest_framework.response import Response<br>from rest_framework import status   <br><br><br>def custom_exception_handler(exc, context):     <br>    response = exception_handler(exc, context)      <br>    if response is not None:         <br>       custom_response = {<br>        &#39;error&#39;: {&#39;code&#39;: exc.default_code if hasattr(exc, &#39;default_code&#39;) else &#39;error&#39;, &#39;message&#39;: str(exc.detail) if hasattr(exc, &#39;detail&#39;) else str(exc),}}          <br><br>    # Add field-specific errors for validation failures         <br>    if hasattr(exc, &#39;detail&#39;) and isinstance(exc.detail, dict):             <br>       custom_response[&#39;error&#39;][&#39;fields&#39;] = exc.detail          <br>       response.data = custom_response      <br>    <br>    return response</pre><h3>API Versioning Strategy</h3><p>Version your API from the start to allow for future changes:</p><pre># config/settings/base.py<br>REST_FRAMEWORK = {<br>    # ...<br>    &#39;DEFAULT_VERSIONING_CLASS&#39;: &#39;rest_framework.versioning.URLVersioning&#39;,<br>    &#39;DEFAULT_VERSION&#39;: &#39;v1&#39;,<br>    &#39;ALLOWED_VERSIONS&#39;: [&#39;v1&#39;, &#39;v2&#39;],<br>    &#39;VERSION_PARAM&#39;: &#39;version&#39;,<br>}<br></pre><pre># URLs with versioning<br># urls.py<br>from rest_framework.versioning import URLPathVersioning</pre><pre>urlpatterns = [<br>    path(&#39;api//&#39;, include(&#39;apps.projects.urls&#39;)),<br>]<br></pre><pre># Views with version handling<br>class ProjectViewSet(viewsets.ModelViewSet):<br>    def get_serializer_class(self):<br>        if self.request.version == &#39;v2&#39;:<br>            from .serializers import ProjectSerializerV2<br>            return ProjectSerializerV2<br>        return ProjectSerializer</pre><h3>Rate Limiting and Throttling</h3><p>Protect your API from abuse:</p><pre># config/settings/base.py<br>REST_FRAMEWORK = {     <br>  # ...     <br>  &#39;DEFAULT_THROTTLE_CLASSES&#39;: [<br>      &#39;rest_framework.throttling.AnonRateThrottle&#39;,<br>      &#39;rest_framework.throttling.UserRateThrottle&#39;     <br>  ],<br>  &#39;DEFAULT_THROTTLE_RATES&#39;: {         <br>      &#39;anon&#39;: &#39;100/hour&#39;,         <br>      &#39;user&#39;: &#39;1000/hour&#39;,         <br>      &#39;burst&#39;: &#39;50/minute&#39;,     <br>  } <br>}<br><br># Custom throttle for specific endpoints <br>from rest_framework.throttling import UserRateThrottle  <br><br><br>class BurstRateThrottle(UserRateThrottle):     <br>    scope = &#39;burst&#39;   <br><br><br>class ProjectViewSet(viewsets.ModelViewSet):     <br>    throttle_classes = [BurstRateThrottle, UserRateThrottle]<br>    # ...</pre><h3>Testing Your API</h3><p>Comprehensive tests are essential for APIs:</p><pre># apps/projects/tests/test_api.py<br>import pytest<br>from django.urls import reverse<br>from rest_framework.test import APIClient<br>from rest_framework import status<br>from apps.accounts.models import User<br>from apps.projects.models import Project, Task<br></pre><pre>@pytest.fixture<br>def api_client():<br>    return APIClient()<br></pre><pre>@pytest.fixture<br>def user(db):<br>    return User.objects.create_user(<br>        email=&#39;test@example.com&#39;,<br>        password=&#39;testpass123&#39;<br>    )<br></pre><pre>@pytest.fixture<br>def authenticated_client(api_client, user):<br>    api_client.force_authenticate(user=user)<br>    return api_client<br></pre><pre>@pytest.fixture<br>def project(db, user):<br>    return Project.objects.create(<br>        name=&#39;Test Project&#39;,<br>        owner=user,<br>        description=&#39;A test project&#39;<br>    )<br></pre><pre>@pytest.mark.django_db<br>class TestProjectAPI:<br>    def test_list_projects(self, authenticated_client, project):<br>        response = authenticated_client.get(&#39;/api/v1/projects/&#39;)<br>        assert response.status_code == status.HTTP_200_OK<br>        assert len(response.data[&#39;results&#39;]) == 1</pre><pre>    def test_create_project(self, authenticated_client):<br>        response = authenticated_client.post(&#39;/api/v1/projects/&#39;, {<br>            &#39;name&#39;: &#39;New Project&#39;,<br>            &#39;description&#39;: &#39;A new project&#39;<br>        })<br>        assert response.status_code == status.HTTP_201_CREATED<br>        assert Project.objects.filter(name=&#39;New Project&#39;).exists()</pre><pre>    def test_filter_projects_by_status(self, authenticated_client, project):<br>        response = authenticated_client.get(<br>            &#39;/api/v1/projects/&#39;,<br>            {&#39;is_active&#39;: &#39;true&#39;}<br>        )<br>        assert response.status_code == status.HTTP_200_OK<br>        assert len(response.data[&#39;results&#39;]) == 1</pre><pre>    def test_search_projects(self, authenticated_client, project):<br>        response = authenticated_client.get(<br>            &#39;/api/v1/projects/&#39;,<br>            {&#39;search&#39;: &#39;Test&#39;}<br>        )<br>        assert response.status_code == status.HTTP_200_OK</pre><pre>    def test_pagination(self, authenticated_client, user):<br>        # Create multiple projects<br>        for i in range(25):<br>            Project.objects.create(<br>                name=f&#39;Project {i}&#39;,<br>                owner=user<br>            )</pre><pre>        response = authenticated_client.get(&#39;/api/v1/projects/&#39;)<br>        assert response.status_code == status.HTTP_200_OK<br>        assert &#39;next&#39; in response.data<br>        assert len(response.data[&#39;results&#39;]) == 20  # Default page size<br></pre><pre>@pytest.mark.django_db<br>class TestTaskAPI:<br>    def test_create_task(self, authenticated_client, project):<br>        response = authenticated_client.post(&#39;/api/v1/tasks/&#39;, {<br>            &#39;title&#39;: &#39;New Task&#39;,<br>            &#39;description&#39;: &#39;Task description&#39;,<br>            &#39;project&#39;: project.id,<br>            &#39;priority&#39;: &#39;high&#39;<br>        })<br>        assert response.status_code == status.HTTP_201_CREATED</pre><pre>    def test_assign_task(self, authenticated_client, project, user):<br>        task = Task.objects.create(<br>            title=&#39;Test Task&#39;,<br>            project=project,<br>            owner=user<br>        )</pre><pre>        response = authenticated_client.post(<br>            f&#39;/api/v1/tasks/{task.id}/assign/&#39;,<br>            {&#39;user_id&#39;: user.id}<br>        )<br>        assert response.status_code == status.HTTP_200_OK<br>        task.refresh_from_db()<br>        assert task.assignee == user</pre><h3>The Bottom Line</h3><p>Building a great API isn’t about using the latest tools or implementing every feature. It’s about understanding what developers need and making their lives easier.</p><p>Here’s what I always remember:</p><ul><li><strong>Start with serializers</strong> — Get your data representation right first</li><li><strong>Add filtering and search from day one</strong> — You’ll need them sooner than you think</li><li><strong>Version your API</strong> — Plan for changes before you make them</li><li><strong>Test everything</strong> — API bugs affect every client simultaneously</li><li><strong>Document as you go</strong> — Your future self will thank you</li><li><strong>Handle errors gracefully</strong> — Consistent error responses make integration easier</li></ul><p>That frontend developer who complained about my first API? We became great friends. After that rewrite, he told me it was the best API he’d ever worked with. High praise from someone who had to tell me everything I was doing wrong.</p><h3>What’s Next?</h3><p>In the next article, we’ll dive into DevOps for startups — specifically, how to containerize your Django applications with Docker. We’ll cover everything from development to production deployment.</p><p>Follow along and let’s keep building.</p><p><em>Next article: DevOps for Startups: Dockerizing Django Applications</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=544b162dac1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Authentication & Authorization in Django]]></title>
            <link>https://medium.com/@yosephoche/implementing-authentication-authorization-in-django-7c087ffbb59d?source=rss-abf46fdec084------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c087ffbb59d</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Yoseph Parai]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 04:01:02 GMT</pubDate>
            <atom:updated>2026-04-24T04:01:02.285Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical guide to building secure authentication systems that scale with your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5agaNbRPUPOQPhIN" /></figure><p>Let me tell you about the scariest moment of my career as a developer.</p><p>I was three months into a project for a healthcare client. We had built a beautiful application for managing patient records — appointments, medical histories, billing, the works. The client was happy, users were using it, and everything seemed great.</p><p>Then our security consultant ran a penetration test.</p><p>Within hours, he had found it: a single endpoint that didn’t check permissions properly. Any authenticated user could view any other user’s medical records. Not just view — download, modify, delete. The vulnerability was simple, subtle, and devastating.</p><p>We fixed it, added tests, and moved on. But that experience changed how I think about authentication and authorization forever.</p><p>This is the guide I wish I had when I started. It’s everything I’ve learned about building secure authentication and authorization systems in Django — the right way.</p><h3>Authentication vs. Authorization: The Difference That Matters</h3><p>Before we dive into code, let’s be clear about terminology. I see developers confuse these two concepts all the time, and it leads to security vulnerabilities.</p><p><strong>Authentication</strong> is about verifying identity. Who are you? Are you who you claim to be? This is login — verifying credentials (password, token, biometric) to confirm your identity.</p><p><strong>Authorization</strong> is about permissions. Now that we know who you are, what are you allowed to do? Can you view this record? Edit this document? Delete this user?</p><p>A system can authenticate you perfectly but still authorize incorrectly. That’s what happened in my healthcare project — we knew who the users were, but we didn’t properly check what they were allowed to see.</p><h3>Setting Up Custom User Model</h3><p>Every Django project should start with a custom user model. I know the default User model seems convenient, but it will bite you later when you need to add fields like phone numbers, profile pictures, or custom authentication methods.</p><p>Here’s my standard approach:</p><pre># apps/accounts/models.py<br>from django.contrib.auth.models import AbstractUser<br>from django.db import models<br></pre><pre>class User(AbstractUser):<br>    &quot;&quot;&quot;Custom user model with additional fields.&quot;&quot;&quot;<br>    email = models.EmailField(unique=True)<br>    phone = models.CharField(max_length=20, blank=True)<br>    avatar = models.ImageField(upload_to=&#39;avatars/&#39;, blank=True)<br>    is_verified = models.BooleanField(default=False)<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)</pre><pre>    # Remove username field - we&#39;ll use email instead<br>    username = None</pre><pre>    USERNAME_FIELD = &#39;email&#39;<br>    REQUIRED_FIELDS = []</pre><pre>    class Meta:<br>        ordering = [&#39;-created_at&#39;]</pre><pre>    def __str__(self):<br>        return self.email</pre><pre>    def get_full_name(self):<br>        return f&quot;{self.first_name} {self.last_name}&quot;.strip() or self.email</pre><p>Don’t forget to tell Django to use this model:</p><pre># config/settings/base.py<br>AUTH_USER_MODEL = &#39;accounts.User&#39;</pre><p><strong>Pro Tip:</strong> Always create your custom user model before running your first migration. Changing it later is painful and often requires data migrations.</p><h3>Building Registration &amp; Login</h3><p>Now let’s build the views for registration and login. I’ll show you a clean, secure implementation:</p><pre># apps/accounts/views.py<br>from django.contrib.auth import get_user_model<br>from django.contrib.auth.tokens import default_token_generator<br>from django.core.mail import send_mail<br>from django.utils.encoding import force_bytes<br>from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode<br>from rest_framework import status, permissions<br>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework.generics import CreateAPIView, RetrieveUpdateAPIView<br>from rest_framework_simplejwt.tokens import RefreshToken<br>from .serializers import (<br>    UserRegistrationSerializer,<br>    UserSerializer,<br>    LoginSerializer,<br>    PasswordResetSerializer,<br>)<br>from .permissions import IsVerified</pre><pre>User = get_user_model()<br></pre><pre>class RegisterView(CreateAPIView):<br>    &quot;&quot;&quot;Handle user registration.&quot;&quot;&quot;<br>    serializer_class = UserRegistrationSerializer<br>    permission_classes = [permissions.AllowAny]</pre><pre>    def create(self, request, *args, **kwargs):<br>        serializer = self.get_serializer(data=request.data)<br>        serializer.is_valid(raise_exception=True)<br>        user = serializer.save()</pre><pre>        # Send verification email<br>        self.send_verification_email(user)</pre><pre>        return Response({<br>            &#39;message&#39;: &#39;Registration successful. Please check your email to verify your account.&#39;,<br>            &#39;user&#39;: UserSerializer(user).data<br>        }, status=status.HTTP_201_CREATED)</pre><pre>    def send_verification_email(self, user):<br>        token = default_token_generator.make_token(user)<br>        uid = urlsafe_base64_encode(force_bytes(user.pk))<br>        verification_link = f&quot;https://yourdomain.com/verify/{uid}/{token}&quot;</pre><pre>        send_mail(<br>            &#39;Verify your account&#39;,<br>            f&#39;Click here to verify: {verification_link}&#39;,<br>            &#39;noreply@yourdomain.com&#39;,<br>            [user.email],<br>            fail_silently=False,<br>        )<br></pre><pre>class LoginView(APIView):<br>    &quot;&quot;&quot;Handle user login.&quot;&quot;&quot;<br>    permission_classes = [permissions.AllowAny]</pre><pre>    def post(self, request):<br>        serializer = LoginSerializer(data=request.data)<br>        serializer.is_valid(raise_exception=True)</pre><pre>        user = serializer.validated_data[&#39;user&#39;]</pre><pre>        if not user.is_verified:<br>            return Response(<br>                {&#39;error&#39;: &#39;Please verify your email before logging in.&#39;},<br>                status=status.HTTP_401_UNAUTHORIZED<br>            )</pre><pre>        refresh = RefreshToken.for_user(user)</pre><pre>        return Response({<br>            &#39;access&#39;: str(refresh.access_token),<br>            &#39;refresh&#39;: str(refresh),<br>            &#39;user&#39;: UserSerializer(user).data<br>        })<br></pre><pre>class ProfileView(RetrieveUpdateAPIView):<br>    &quot;&quot;&quot;Get and update user profile.&quot;&quot;&quot;<br>    serializer_class = UserSerializer<br>    permission_classes = [permissions.IsAuthenticated, IsVerified]</pre><pre>    def get_object(self):<br>        return self.request.user</pre><p>And the serializers:</p><pre># apps/accounts/serializers.py<br>from django.contrib.auth import get_user_model<br>from django.contrib.auth.password_validation import validate_password<br>from rest_framework import serializers</pre><pre>User = get_user_model()<br></pre><pre>class UserRegistrationSerializer(serializers.ModelSerializer):<br>    password = serializers.CharField(write_only=True, validators=[validate_password])<br>    password_confirm = serializers.CharField(write_only=True)</pre><pre>    class Meta:<br>        model = User<br>        fields = [&#39;email&#39;, &#39;password&#39;, &#39;password_confirm&#39;, &#39;first_name&#39;, &#39;last_name&#39;, &#39;phone&#39;]</pre><pre>    def validate(self, attrs):<br>        if attrs[&#39;password&#39;] != attrs[&#39;password_confirm&#39;]:<br>            raise serializers.ValidationError({&quot;password&quot;: &quot;Passwords don&#39;t match&quot;})<br>        return attrs</pre><pre>    def create(self, validated_data):<br>        validated_data.pop(&#39;password_confirm&#39;)<br>        user = User.objects.create_user(**validated_data)<br>        return user<br></pre><pre>class LoginSerializer(serializers.Serializer):<br>    email = serializers.EmailField()<br>    password = serializers.CharField(write_only=True)</pre><pre>    def validate(self, attrs):<br>        from django.contrib.auth import authenticate<br>        user = authenticate(<br>            username=attrs[&#39;email&#39;],<br>            password=attrs[&#39;password&#39;]<br>        )<br>        if not user:<br>            raise serializers.ValidationError(&quot;Invalid credentials&quot;)<br>        if not user.is_active:<br>            raise serializers.ValidationError(&quot;User account is disabled&quot;)<br>        attrs[&#39;user&#39;] = user<br>        return attrs<br></pre><pre>class UserSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = User<br>        fields = [&#39;id&#39;, &#39;email&#39;, &#39;first_name&#39;, &#39;last_name&#39;, &#39;phone&#39;, &#39;avatar&#39;, &#39;is_verified&#39;, &#39;created_at&#39;]<br>        read_only_fields = [&#39;id&#39;, &#39;is_verified&#39;, &#39;created_at&#39;]</pre><h3>JWT Authentication with Django REST Framework</h3><p>For API authentication, I prefer JWTs (JSON Web Tokens). They’re stateless, scalable, and work great with mobile apps and SPAs. Here’s how to set them up:</p><pre># config/settings/base.py<br>from datetime import timedelta</pre><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (<br>        &#39;rest_framework_simplejwt.authentication.JWTAuthentication&#39;,<br>    ),<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: (<br>        &#39;rest_framework.permissions.IsAuthenticated&#39;,<br>    ),<br>}</pre><pre>SIMPLE_JWT = {<br>    &#39;ACCESS_TOKEN_LIFETIME&#39;: timedelta(minutes=60),<br>    &#39;REFRESH_TOKEN_LIFETIME&#39;: timedelta(days=7),<br>    &#39;ROTATE_REFRESH_TOKENS&#39;: True,<br>    &#39;BLACKLIST_AFTER_ROTATION&#39;: True,<br>    &#39;AUTH_HEADER_TYPES&#39;: (&#39;Bearer&#39;,),<br>    &#39;AUTH_TOKEN_CLASSES&#39;: (&#39;rest_framework_simplejwt.tokens.AccessToken&#39;,),<br>}</pre><p>Add the URLs:</p><pre># apps/accounts/urls.py<br>from django.urls import path<br>from rest_framework_simplejwt.views import TokenRefreshView, TokenVerifyView<br>from .views import RegisterView, LoginView, ProfileView, VerifyEmailView</pre><pre>urlpatterns = [<br>    path(&#39;register/&#39;, RegisterView.as_view(), name=&#39;register&#39;),<br>    path(&#39;login/&#39;, LoginView.as_view(), name=&#39;login&#39;),<br>    path(&#39;profile/&#39;, ProfileView.as_view(), name=&#39;profile&#39;),<br>    path(&#39;refresh/&#39;, TokenRefreshView.as_view(), name=&#39;token_refresh&#39;),<br>    path(&#39;verify/&#39;, TokenVerifyView.as_view(), name=&#39;token_verify&#39;),<br>]</pre><h3>Authorization: Permissions That Actually Work</h3><p>Now comes the critical part — authorization. This is where most applications fail. Let me show you a robust permission system:</p><pre># apps/accounts/permissions.py<br>from rest_framework import permissions<br></pre><pre>class IsVerified(permissions.BasePermission):<br>    &quot;&quot;&quot;Require user to have a verified email.&quot;&quot;&quot;<br>    message = &#39;You must verify your email to access this resource.&#39;</pre><pre>    def has_permission(self, request, view):<br>        return (<br>            request.user and<br>            request.user.is_authenticated and<br>            request.user.is_verified<br>        )<br></pre><pre>class IsOwner(permissions.BasePermission):<br>    &quot;&quot;&quot;Allow only object owners to access.&quot;&quot;&quot;<br>    message = &quot;You don&#39;t have permission to access this object.&quot;</pre><pre>    def has_object_permission(self, request, view, obj):<br>        return obj == request.user or request.user.is_staff<br></pre><pre>class IsAdmin(permissions.BasePermission):<br>    &quot;&quot;&quot;Allow only admin users.&quot;&quot;&quot;<br>    message = &#39;Admin access required.&#39;</pre><pre>    def has_permission(self, request, view):<br>        return request.user and request.user.is_staff<br></pre><pre>class IsOwnerOrReadOnly(permissions.BasePermission):<br>    &quot;&quot;&quot;<br>    Object-level permission to only allow owners of an object to edit it.<br>    Read permissions are allowed to any request (GET, HEAD, OPTIONS).<br>    &quot;&quot;&quot;<br>    def has_object_permission(self, request, view, obj):<br>        if request.method in permissions.SAFE_METHODS:<br>            return True</pre><pre>        # Check if user is owner or staff<br>        return obj.owner == request.user or request.user.is_staff</pre><h3>Role-Based Access Control (RBAC)</h3><p>For more complex applications, you’ll need role-based access. Here’s a practical implementation:</p><pre># apps/accounts/models.py (extended)<br>class UserRole(models.TextChoices):<br>    ADMIN = &#39;admin&#39;, &#39;Admin&#39;<br>    MANAGER = &#39;manager&#39;, &#39;Manager&#39;<br>    MEMBER = &#39;member&#39;, &#39;Member&#39;<br>    VIEWER = &#39;viewer&#39;, &#39;Viewer&#39;<br></pre><pre>class Organization(models.Model):<br>    &quot;&quot;&quot;Organization that users can belong to.&quot;&quot;&quot;<br>    name = models.CharField(max_length=255)<br>    slug = models.SlugField(unique=True)<br>    created_at = models.DateTimeField(auto_now_add=True)<br></pre><pre>class OrganizationMember(models.Model):<br>    &quot;&quot;&quot;Through model for user-organization relationship with roles.&quot;&quot;&quot;<br>    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name=&#39;memberships&#39;)<br>    organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name=&#39;members&#39;)<br>    role = models.CharField(max_length=20, choices=UserRole.choices, default=UserRole.MEMBER)<br>    created_at = models.DateTimeField(auto_now_add=True)</pre><pre>    class Meta:<br>        unique_together = [&#39;user&#39;, &#39;organization&#39;]<br></pre><pre># Usage in another app - e.g., projects app<br>class Project(models.Model):<br>    name = models.CharField(max_length=255)<br>    organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name=&#39;projects&#39;)<br>    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name=&#39;owned_projects&#39;)<br>    members = models.ManyToManyField(User, through=&#39;ProjectMember&#39;, related_name=&#39;projects&#39;)<br>    is_public = models.BooleanField(default=False)<br>    created_at = models.DateTimeField(auto_now_add=True)</pre><pre># apps/projects/permissions.py<br>from rest_framework import permissions<br>from apps.accounts.models import UserRole, OrganizationMember<br></pre><pre>class IsOrganizationAdmin(permissions.BasePermission):<br>    def has_permission(self, request, view):<br>        org_id = view.kwargs.get(&#39;organization_id&#39;)<br>        if not org_id:<br>            return False</pre><pre>        membership = OrganizationMember.objects.filter(<br>            user=request.user,<br>            organization_id=org_id,<br>            role=UserRole.ADMIN<br>        ).exists()</pre><pre>        return membership or request.user.is_staff<br></pre><pre>class CanManageProject(permissions.BasePermission):<br>    &quot;&quot;&quot;Check if user can manage (edit/delete) a project.&quot;&quot;&quot;<br>    def has_object_permission(self, request, view, obj):<br>        # Owner can manage<br>        if obj.owner == request.user:<br>            return True</pre><pre>        # Organization admins can manage<br>        membership = OrganizationMember.objects.filter(<br>            user=request.user,<br>            organization=obj.organization,<br>            role__in=[UserRole.ADMIN, UserRole.MANAGER]<br>        ).exists()</pre><pre>        return membership or request.user.is_staff<br></pre><pre>class CanViewProject(permissions.BasePermission):<br>    &quot;&quot;&quot;Check if user can view a project.&quot;&quot;&quot;<br>    def has_object_permission(self, request, view, obj):<br>        # Public projects are visible to everyone<br>        if obj.is_public:<br>            return True</pre><pre>        # Owner and org members can see<br>        if obj.owner == request.user:<br>            return True</pre><pre>        membership = OrganizationMember.objects.filter(<br>            user=request.user,<br>            organization=obj.organization<br>        ).exists()</pre><pre>        return membership or request.user.is_staff</pre><h3>Applying Permissions to Views</h3><p>Now let’s use these permissions in views:</p><pre># apps/projects/views.py<br>from rest_framework import viewsets, permissions<br>from .models import Project<br>from .serializers import ProjectSerializer<br>from .permissions import CanViewProject, CanManageProject, IsOrganizationAdmin<br></pre><pre>class ProjectViewSet(viewsets.ModelViewSet):<br>    serializer_class = ProjectSerializer<br>    permission_classes = [permissions.IsAuthenticated]</pre><pre>    def get_permissions(self):<br>        if self.action in [&#39;create&#39;]:<br>            return [IsOrganizationAdmin()]<br>        elif self.action in [&#39;update&#39;, &#39;partial_update&#39;, &#39;destroy&#39;]:<br>            return [CanManageProject()]<br>        return [CanViewProject()]</pre><pre>    def get_queryset(self):<br>        user = self.request.user<br>        # Return projects user has access to<br>        return Project.objects.filter(<br>            models.Q(owner=user) |<br>            models.Q(organization__members=user) |<br>            models.Q(is_public=True)<br>        ).distinct()</pre><h3>Password Reset Flow</h3><p>Don’t forget password reset functionality. Here’s a secure implementation:</p><pre># apps/accounts/views.py (additional)<br>class PasswordResetView(APIView):<br>    permission_classes = [permissions.AllowAny]</pre><pre>    def post(self, request):<br>        serializer = PasswordResetSerializer(data=request.data)<br>        serializer.is_valid(raise_exception=True)</pre><pre>        email = serializer.validated_data[&#39;email&#39;]<br>        try:<br>            user = User.objects.get(email=email)<br>            self.send_reset_email(user)<br>        except User.DoesNotExist:<br>            # Don&#39;t reveal if email exists<br>            pass</pre><pre>        return Response({<br>            &#39;message&#39;: &#39;If an account with that email exists, we have sent reset instructions.&#39;<br>        })</pre><pre>    def send_reset_email(self, user):<br>        token = default_token_generator.make_token(user)<br>        uid = urlsafe_base64_encode(force_bytes(user.pk))<br>        reset_link = f&quot;https://yourdomain.com/password-reset/{uid}/{token}&quot;</pre><pre>        send_mail(<br>            &#39;Password Reset Request&#39;,<br>            f&#39;Click to reset your password: {reset_link}&#39;,<br>            &#39;noreply@yourdomain.com&#39;,<br>            [user.email],<br>            fail_silently=False,<br>        )<br></pre><pre>class PasswordResetConfirmView(APIView):<br>    permission_classes = [permissions.AllowAny]</pre><pre>    def post(self, request, uidb64, token):<br>        try:<br>            uid = urlsafe_base64_decode(uidb64).decode()<br>            user = User.objects.get(pk=uid)<br>        except (TypeError, ValueError, OverflowError, User.DoesNotExist):<br>            return Response({&#39;error&#39;: &#39;Invalid token&#39;}, status=status.HTTP_400_BAD_REQUEST)</pre><pre>        if not default_token_generator.check_token(user, token):<br>            return Response({&#39;error&#39;: &#39;Invalid token&#39;}, status=status.HTTP_400_BAD_REQUEST)</pre><pre>        password = request.data.get(&#39;password&#39;)<br>        password_confirm = request.data.get(&#39;password_confirm&#39;)</pre><pre>        if password != password_confirm:<br>            return Response({&#39;error&#39;: &#39;Passwords do not match&#39;}, status=status.HTTP_400_BAD_REQUEST)</pre><pre>        user.set_password(password)<br>        user.save()</pre><pre>        return Response({&#39;message&#39;: &#39;Password reset successful&#39;})</pre><p><strong>Security Note:</strong> Always use HTTPS in production. Never send tokens or passwords over plain HTTP. Also, implement rate limiting on login and password reset endpoints to prevent brute force attacks.</p><h3>Testing Your Authentication</h3><p>Finally, you need tests. Lots of tests. Here’s my approach:</p><pre># apps/accounts/tests/test_authentication.py<br>import pytest<br>from django.urls import reverse<br>from rest_framework.test import APIClient<br>from rest_framework import status<br>from apps.accounts.models import User<br></pre><pre>@pytest.fixture<br>def api_client():<br>    return APIClient()<br></pre><pre>@pytest.fixture<br>def user(db):<br>    return User.objects.create_user(<br>        email=&#39;test@example.com&#39;,<br>        password=&#39;testpass123&#39;,<br>        is_verified=True<br>    )<br></pre><pre>@pytest.mark.django_db<br>class TestRegistration:<br>    def test_successful_registration(self, api_client):<br>        response = api_client.post(&#39;/api/accounts/register/&#39;, {<br>            &#39;email&#39;: &#39;newuser@example.com&#39;,<br>            &#39;password&#39;: &#39;securepassword123&#39;,<br>            &#39;password_confirm&#39;: &#39;securepassword123&#39;,<br>            &#39;first_name&#39;: &#39;John&#39;,<br>            &#39;last_name&#39;: &#39;Doe&#39;<br>        })<br>        assert response.status_code == status.HTTP_201_CREATED<br>        assert User.objects.filter(email=&#39;newuser@example.com&#39;).exists()</pre><pre>    def test_password_mismatch(self, api_client):<br>        response = api_client.post(&#39;/api/accounts/register/&#39;, {<br>            &#39;email&#39;: &#39;newuser@example.com&#39;,<br>            &#39;password&#39;: &#39;securepassword123&#39;,<br>            &#39;password_confirm&#39;: &#39;differentpassword&#39;,<br>        })<br>        assert response.status_code == status.HTTP_400_BAD_REQUEST<br></pre><pre>@pytest.mark.django_db<br>class TestLogin:<br>    def test_successful_login(self, api_client, user):<br>        response = api_client.post(&#39;/api/accounts/login/&#39;, {<br>            &#39;email&#39;: &#39;test@example.com&#39;,<br>            &#39;password&#39;: &#39;testpass123&#39;<br>        })<br>        assert response.status_code == status.HTTP_200_OK<br>        assert &#39;access&#39; in response.data</pre><pre>    def test_login_unverified_user(self, api_client, db):<br>        unverified_user = User.objects.create_user(<br>            email=&#39;unverified@example.com&#39;,<br>            password=&#39;testpass123&#39;,<br>            is_verified=False<br>        )<br>        response = api_client.post(&#39;/api/accounts/login/&#39;, {<br>            &#39;email&#39;: &#39;unverified@example.com&#39;,<br>            &#39;password&#39;: &#39;testpass123&#39;<br>        })<br>        assert response.status_code == status.HTTP_401_UNAUTHORIZED<br></pre><pre>@pytest.mark.django_db<br>class TestAuthorization:<br>    def test_unauthenticated_access_denied(self, api_client):<br>        response = api_client.get(&#39;/api/accounts/profile/&#39;)<br>        assert response.status_code == status.HTTP_401_UNAUTHORIZED</pre><pre>    def test_authenticated_access_allowed(self, api_client, user):<br>        api_client.force_authenticate(user=user)<br>        response = api_client.get(&#39;/api/accounts/profile/&#39;)<br>        assert response.status_code == status.HTTP_200_OK</pre><h3>The Bottom Line</h3><p>Authentication and authorization aren’t optional — they’re fundamental. A single vulnerability can destroy user trust, compromise sensitive data, and end your business.</p><p>Here’s what I always remember:</p><ul><li><strong>Start with a custom user model</strong> — It seems like extra work now, but it’ll save you pain later</li><li><strong>Use JWTs for APIs</strong> — They’re stateless, scalable, and work everywhere</li><li><strong>Separate authentication from authorization</strong> — Know the difference, implement both correctly</li><li><strong>Test thoroughly</strong> — Security bugs often hide in edge cases</li><li><strong>Use HTTPS everywhere</strong> — Never transmit credentials insecurely</li><li><strong>Implement rate limiting</strong> — Protect against brute force attacks</li></ul><p>The healthcare incident I mentioned earlier? We fixed it with proper object-level permissions. The fix took an hour. The lesson took years to learn.</p><h3>What’s Next?</h3><p>In the next article, we’ll dive into database design patterns for SaaS applications. We’ll cover multi-tenancy, schema design, and scaling strategies that actually work.</p><p>Follow along and let’s keep building secure, scalable applications.</p><p><em>Next article: Database Design Patterns for SaaS Applications</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c087ffbb59d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the Right Tech Stack for a Modern Software House]]></title>
            <link>https://medium.com/@yosephoche/choosing-the-right-tech-stack-for-a-modern-software-house-7d80b738abfc?source=rss-abf46fdec084------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d80b738abfc</guid>
            <category><![CDATA[tech-stack]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yoseph Parai]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 07:01:02 GMT</pubDate>
            <atom:updated>2026-04-20T07:01:02.363Z</atom:updated>
            <content:encoded><![CDATA[<p><em>And why most of the time, you’re probably overthinking it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WUFOFYTlDb1w0gVt" /></figure><p>I’ll be honest with you — I’ve spent way too much time in my career agonizing over tech stack decisions. There was a period where I’d spend weeks evaluating frameworks, reading endless blog posts, and creating comparison spreadsheets before I could even write a single line of code.</p><p>Then I started building a software house, and everything changed.</p><p>Suddenly, every hour spent debating React vs. Vue or PostgreSQL vs. MongoDB was an hour I wasn’t billing clients. Every day I spent researching the “perfect” microservices architecture was a day I wasn’t shipping features that made people happy.</p><p>Here’s what I’ve learned: most tech stack decisions matter way less than we think they do. And the ones that do matter are rarely the ones we obsess over.</p><p>This is how I choose my tech stack now, and why I think you should stop overthinking yours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OogXSshNDf9XYu0V" /></figure><h3>The Truth About Tech Stack Paralysis</h3><p>Before we dive into specifics, let’s talk about the elephant in the room: tech stack paralysis.</p><p>You know the feeling. You’re starting a new project, and suddenly you’re down a rabbit hole of:</p><ul><li>“Should I use Next.js or plain React?”</li><li>“Is GraphQL really better than REST for this use case?”</li><li>“Would my app scale better with a NoSQL database?”</li><li>“Should I containerize everything with Kubernetes?”</li></ul><p>Here’s the uncomfortable truth: in 95% of cases, these questions don’t matter nearly as much as you think they do.</p><p>I’ve built successful products with “outdated” tech stacks. I’ve seen brilliant engineers ship amazing software with tools that make Hacker News commenters cringe. I’ve also watched teams spend months perfecting their architecture while competitors with “worse” tech stacks shipped, got feedback, and iterated their way to success.</p><p>The best tech stack is the one that lets you ship fast, iterate quickly, and keep your mental overhead low. Everything else is optimization for problems you probably don’t have yet.</p><h3>What Actually Matters</h3><p>After building dozens of projects and running a software house, I’ve narrowed it down to three things that actually matter when choosing a tech stack:</p><h3>1. Your Team’s Expertise</h3><p>This is the single most important factor, and it’s the one most people ignore.</p><p>If your team knows Python inside and out, use Python. If they’re React wizards, use React. If they’ve been building monolithic Rails apps for years, stick with Rails.</p><p>The productivity boost from working with familiar tools is massive. You’ll debug faster, make better architectural decisions, and ship more features. And when you inevitably hit weird edge cases, you’ll have the context to solve them quickly.</p><p>I chose Python and Django not because I did an exhaustive technical comparison. I chose them because I’ve been writing Python professionally for a decade. I could read Django code in my sleep. That expertise is worth more than any marginal performance gain I might get from a “better” framework.</p><h3>2. Ecosystem and Community</h3><p>This is where I see people make the most mistakes. They pick a trendy framework with a beautiful README but no ecosystem, then wonder why they’re building basic functionality from scratch.</p><p>A good tech stack has:<br>- Active maintenance and regular updates<br>- A large community that can answer questions<br>- Well-maintained libraries for common tasks<br>- Good documentation and examples<br>- People actually using it in production</p><p>Django wins here hands down. Need authentication? There’s a package for that. Need an admin panel? Built in. Need to handle file uploads? There’s a battle-tested library. Need to integrate with a payment gateway? Someone’s already done it.</p><p>This matters more than you realize. Every feature you don’t have to build yourself is time you can spend on things that actually differentiate your product.</p><h3>3. Hiring and Onboarding</h3><p>If you’re building a software house, this is crucial. You’re going to hire people. Those people need to be productive quickly.</p><p>Popular, well-documented stacks make this way easier. When I hire a Django developer, I know they can be productive in their first week. When I hire someone to work with a niche framework I chose because it was “technically superior,” it might take them a month to get up to speed.</p><p>That month of lost productivity costs real money. Choose stacks that make hiring easy.</p><h3>My Current Stack (And Why I Chose It)</h3><p>Here’s what I use for most client projects, and the reasoning behind each choice:</p><h3>Backend: Python + Django</h3><p><strong>Why</strong>: I know it well, it has incredible batteries-included features, and the ecosystem is unmatched. I can ship a complete web application with authentication, admin panel, and database models in days, not weeks.</p><p><strong>Trade-off</strong>: It’s not the fastest framework for raw performance, but for 99% of client projects, that doesn’t matter.</p><h3>Database: PostgreSQL</h3><p><strong>Why</strong>: It’s reliable, well-documented, and handles complex queries beautifully. It’s also the standard for Django projects, so there are zero compatibility headaches.</p><p><strong>Trade-off</strong>: Not as flexible as NoSQL for unstructured data, but I rarely need that flexibility.</p><h3>Frontend: Django Templates + HTMX</h3><p><strong>Why</strong>: This is controversial, but hear me out. For most client projects, you don’t need a complex SPA. Django templates are fast, HTMX gives you interactivity without the complexity of React, and you can build 90% of what clients need with way less code.</p><p><strong>Trade-off</strong>: Not suitable for highly interactive applications, but I’ve only had one client in 50 projects who actually needed a full SPA.</p><h3>API: Django REST Framework</h3><p><strong>Why</strong>: It’s the standard for Django APIs, well-maintained, and integrates perfectly with the rest of my stack.</p><p><strong>Trade-off</strong>: Can be verbose for simple APIs, but the consistency is worth it.</p><h3>Deployment: Docker + Nginx + Gunicorn</h3><p><strong>Why</strong>: Docker makes deployment consistent across environments. Nginx and Gunicorn are battle-tested standards for serving Django apps.</p><p><strong>Trade-off</strong>: More complex than serverless, but gives me control and saves money at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CoKmgsXDPmYX_UMY" /></figure><h3>When to Break Your Own Rules</h3><p>I’m not saying you should never deviate from your standard stack. Here are situations where I do:</p><p><strong>When the client has specific requirements</strong>: If a client comes to me and says “we need this built with Next.js because our team knows it,” I’m not going to argue. Their long-term maintenance matters more than my preferences.</p><p><strong>When the problem demands it</strong>: I recently built a real-time collaboration feature that required WebSockets and complex state management. For that specific feature, I used a more appropriate toolset, even though it wasn’t my standard choice.</p><p><strong>When learning something new</strong>: I dedicate time to exploring new technologies, but I do it in personal projects, not client work. This keeps my skills sharp without risking client deadlines.</p><h3>The Anti-Patterns I See All the Time</h3><p>After years of consulting and running a software house, here are the tech stack mistakes I see repeatedly:</p><h3>The Resume-Driven Developer</h3><p>They choose technologies based on what will look good on their resume, not what’s best for the project. They’ll push for microservices because it’s trendy, even when a monolith would be 10x more appropriate.</p><h3>The Perfectionist</h3><p>They spend weeks evaluating every possible option, create elaborate comparison matrices, and still can’t decide. Meanwhile, competitors have shipped three iterations.</p><h3>The NIH Syndrome</h3><p>They refuse to use existing libraries because “we can build it better.” Six months later, they’re still building authentication systems that open-source projects solved years ago.</p><h3>The Trend Chaser</h3><p>They rewrite their entire stack every time a new framework gains popularity on Hacker News. Their codebase is a Frankenstein of abandoned experiments.</p><h3>Practical Advice for Your Next Project</h3><p>If you’re starting a new project and feeling overwhelmed by tech stack choices, here’s my advice:</p><p><strong>1. Start with what you know.</strong><br>Don’t learn a new framework for a production project unless you absolutely have to. Ship with familiar tools, learn new ones on the side.</p><p><strong>2. Default to boring.</strong><br>PostgreSQL, Django, React, Docker — these aren’t exciting, but they work. They have communities, documentation, and people who can help you when things break.</p><p><strong>3. Optimize for shipping, not perfection.</strong><br>The best architecture is the one that lets you get to v1 quickly. You can always refactor later if you actually need to (you probably won’t).</p><p><strong>4. Listen to your constraints.</strong><br>If you have a team of Python experts, don’t choose a Node.js stack because it’s “more modern.” If you need to hire quickly, don’t choose obscure technologies.</p><p><strong>5. Keep it simple.</strong><br>Monoliths are fine. Serverless is overkill for most apps. Microservices are a solution to organizational problems, not technical ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KFtpJmeu4OB8uShV" /></figure><h3>The Bottom Line</h3><p>Here’s the uncomfortable truth that took me years to accept: your tech stack is not your product.</p><p>Clients don’t care what framework you use. Users don’t care about your database choice. Investors don’t care about your deployment pipeline (unless it’s costing you too much money).</p><p>They care about:<br>- Does it solve their problem?<br>- Is it reliable?<br>- Can they get help when they need it?<br>- Is it reasonably fast?</p><p>Focus on those things. Choose a stack that helps you deliver them. Stop agonizing over the rest.</p><p>I’ve built successful products with tech stacks that make purists cringe. I’ve seen brilliant engineers ship amazing software with tools that are “outdated.” The common thread isn’t the technology — it’s the focus on solving real problems for real people.</p><h3>What’s Coming Next</h3><p>In the next article, I’ll dive into the practical implementation of authentication and authorization in Django. We’ll move beyond theory and look at actual code you can use in production today.</p><p>If you found this article helpful, or if you violently disagree with my tech stack choices, I’d love to hear from you. Drop a comment with your experience — the best insights come from sharing what’s worked (and what hasn’t) in the real world.</p><p><em>Follow me for more articles on Python, Django, and the practical realities of building a software house. New articles every Tuesday and Friday.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d80b738abfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up a Production-Ready Django Project Structure]]></title>
            <link>https://medium.com/@yosephoche/setting-up-a-production-ready-django-project-structure-75d677ca4e0d?source=rss-abf46fdec084------2</link>
            <guid isPermaLink="false">https://medium.com/p/75d677ca4e0d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Yoseph Parai]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 06:01:01 GMT</pubDate>
            <atom:updated>2026-04-17T06:01:01.974Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The project structure nobody teaches you but everyone expects you to know.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wL2rW9gBrwB6Crh6" /></figure><p>I’m going to be honest with you: the first Django project I ever deployed was a mess. One settings.py file with hardcoded database credentials. Everything — models, views, templates, utility functions — stuffed into a single app. A requirements.txt that was just a dump of my local environment. No environment variables. No Docker. No separation between development and production configs.</p><p>It worked. Kind of. For a while. Then I had to deploy an update and everything fell apart.</p><p>That experience taught me something important: <strong>project structure isn’t about following rules. It’s about saving your future self from pain.</strong> When you’re building a software house and juggling multiple client projects, you can’t afford to spend an hour figuring out where a configuration lives or why something works locally but breaks in production.</p><p>In this article, I’ll walk you through the Django project structure I use for every client project. It’s not the only way to do it. It’s not the “right” way (there isn’t one). But it’s battle-tested, and it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OqLp7iz2an-DwCB3" /></figure><h3>The Structure</h3><p>Here’s what a production-ready Django project looks like when I start a new one:</p><pre>myproject/<br>├── .env.example<br>├── .gitignore<br>├── .dockerignore<br>├── docker-compose.yml<br>├── Dockerfile<br>├── Makefile<br>├── requirements/<br>│   ├── base.txt<br>│   ├── local.txt<br>│   ├── production.txt<br>│   └── test.txt<br>├── manage.py<br>├── myproject/<br>│   ├── __init__.py<br>│   ├── asgi.py<br>│   ├── wsgi.py<br>│   ├── urls.py<br>│   ├── settings/<br>│   │   ├── __init__.py<br>│   │   ├── base.py<br>│   │   ├── local.py<br>│   │   ├── production.py<br>│   │   └── test.py<br>│   └── apps/<br>│       └── __init__.py<br>├── apps/<br>│   ├── __init__.py<br>│   ├── users/<br>│   │   ├── __init__.py<br>│   │   ├── apps.py<br>│   │   ├── models.py<br>│   │   ├── views.py<br>│   │   ├── urls.py<br>│   │   ├── serializers.py<br>│   │   ├── admin.py<br>│   │   ├── tests/<br>│   │   │   ├── __init__.py<br>│   │   │   ├── test_models.py<br>│   │   │   └── test_views.py<br>│   │   └── migrations/<br>│   └── core/<br>│       ├── __init__.py<br>│       ├── apps.py<br>│       ├── models.py<br>│       └── ...<br>├── templates/<br>├── static/<br>└── media/</pre><p>I know that looks like a lot. Let me break down the pieces that matter and why.</p><h3>Split Settings: The One Change That Saves Everything</h3><p>The single biggest improvement I ever made was splitting settings.py into a directory.</p><p>Here’s why: when you have one settings file, you end up doing this:</p><pre># settings.py — the bad old days<br>DEBUG = os.environ.get(&#39;DEBUG&#39;, &#39;True&#39;) == &#39;True&#39;</pre><pre>if DEBUG:<br>    DATABASES = {<br>        &#39;default&#39;: {<br>            &#39;ENGINE&#39;: &#39;django.db.backends.sqlite3&#39;,<br>            &#39;NAME&#39;: BASE_DIR / &#39;db.sqlite3&#39;,<br>        }<br>    }<br>else:<br>    DATABASES = {<br>        &#39;default&#39;: {<br>            &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>            &#39;NAME&#39;: os.environ.get(&#39;DB_NAME&#39;),<br>            &#39;USER&#39;: os.environ.get(&#39;DB_USER&#39;),<br>            &#39;PASSWORD&#39;: os.environ.get(&#39;DB_PASSWORD&#39;),<br>            &#39;HOST&#39;: os.environ.get(&#39;DB_HOST&#39;),<br>            &#39;PORT&#39;: os.environ.get(&#39;DB_PORT&#39;),<br>        }<br>    }</pre><p>That works for two environments. Maybe three. Then you add staging. Then you add CI. Then you add a demo environment for a client. And suddenly your settings file is a mess of if/elseblocks that nobody wants to touch.</p><p>The split settings approach fixes this by giving each environment its own file:</p><pre># settings/base.py — shared configuration<br>import os<br>from pathlib import Path</pre><pre>BASE_DIR = Path(__file__).resolve().parent.parent.parent</pre><pre>SECRET_KEY = os.environ.get(&#39;SECRET_KEY&#39;)</pre><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    # third-party<br>    &#39;rest_framework&#39;,<br>    # local apps<br>    &#39;apps.users&#39;,<br>    &#39;apps.core&#39;,<br>]</pre><pre>MIDDLEWARE = [<br>    &#39;django.middleware.security.SecurityMiddleware&#39;,<br>    &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,<br>    &#39;django.middleware.common.CommonMiddleware&#39;,<br>    &#39;django.middleware.csrf.CsrfViewMiddleware&#39;,<br>    &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,<br>    &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,<br>    &#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,<br>]</pre><pre>ROOT_URLCONF = &#39;myproject.urls&#39;</pre><pre># settings/local.py — development only<br>from .base import *  # noqa: F401,F403</pre><pre>DEBUG = True</pre><pre>INSTALLED_APPS += [<br>    &#39;django_extensions&#39;,<br>    &#39;debug_toolbar&#39;,<br>]</pre><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.sqlite3&#39;,<br>        &#39;NAME&#39;: BASE_DIR / &#39;db.sqlite3&#39;,<br>    }<br>}</pre><pre>EMAIL_BACKEND = &#39;django.core.mail.backends.console.EmailBackend&#39;</pre><pre># settings/production.py — production only<br>from .base import *  # noqa: F401,F403</pre><pre>DEBUG = False</pre><pre>ALLOWED_HOSTS = os.environ.get(&#39;ALLOWED_HOSTS&#39;, &#39;&#39;).split(&#39;,&#39;)</pre><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>        &#39;NAME&#39;: os.environ.get(&#39;DB_NAME&#39;),<br>        &#39;USER&#39;: os.environ.get(&#39;DB_USER&#39;),<br>        &#39;PASSWORD&#39;: os.environ.get(&#39;DB_PASSWORD&#39;),<br>        &#39;HOST&#39;: os.environ.get(&#39;DB_HOST&#39;, &#39;localhost&#39;),<br>        &#39;PORT&#39;: os.environ.get(&#39;DB_PORT&#39;, &#39;5432&#39;),<br>    }<br>}</pre><pre>SECURE_SSL_REDIRECT = True<br>SESSION_COOKIE_SECURE = True<br>CSRF_COOKIE_SECURE = True</pre><p>Now each environment is clean. No conditionals. No guessing. You know exactly what’s active where.</p><p>To tell Django which settings to use, set the environment variable:</p><pre>export DJANGO_SETTINGS_MODULE=myproject.settings.local<br># or for production:<br>export DJANGO_SETTINGS_MODULE=myproject.settings.production</pre><p>This single change has saved me more debugging time than anything else in my entire Django career.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0YkzqnmZyQw5__F3" /></figure><h3>Requirements: One File Is Not Enough</h3><p>Same principle as settings. A single requirements.txt is fine for a weekend project. For anything real, split them:</p><pre># requirements/base.txt<br>Django==5.1<br>djangorestframework==3.15<br>psycopg2-binary==2.9.9<br>python-decouple==3.8</pre><pre># requirements/local.txt<br>-r base.txt<br>django-debug-toolbar==4.4<br>django-extensions==3.2</pre><pre># requirements/production.txt<br>-r base.txt<br>gunicorn==22.0<br>whitenoise==6.7</pre><pre># requirements/test.txt<br>-r base.txt<br>pytest==8.3<br>pytest-django==4.8<br>factory-boy==3.3</pre><p>Each file only installs what it needs. Your production server doesn’t get debug toolbar. Your CI pipeline doesn’t get gunicorn. Clean.</p><h3>The Apps Directory: Why I Separate My Apps</h3><p>You’ll notice I put all my project apps inside an apps/ directory. This is controversial — some Django devs hate it. Here&#39;s why I do it:</p><p>When you have a project with 8 apps (users, orders, payments, notifications, analytics, etc.), your project root becomes a dumping ground. Putting them in apps/ keeps the root clean and makes it obvious which directories are <em>your</em> code versus Django&#39;s generated files.</p><p>The tradeoff is you have to use apps.users in INSTALLED_APPS instead of just users. That&#39;s it. That&#39;s the entire downside.</p><p>I also always start with two apps:</p><ul><li><strong>users</strong> — custom user model. Always. From day one. I cannot stress this enough. Swapping Django&#39;s default User model later is incredibly painful. Just do it from the start.</li><li><strong>core</strong> — shared models, utilities, and mixins that don&#39;t belong to any single domain.</li></ul><pre># apps/users/models.py<br>from django.contrib.auth.models import AbstractUser</pre><pre>class User(AbstractUser):<br>    &quot;&quot;&quot;Custom user model — always start with one.&quot;&quot;&quot;<br>    pass</pre><p>And in your settings:</p><pre>AUTH_USER_MODEL = &#39;users.User&#39;</pre><p>Do this on every project. Even if you think you don’t need a custom user model. You will.</p><h3>Environment Variables: No More Hardcoded Secrets</h3><p>I use python-decouple for this. It reads from a .env file locally and from actual environment variables in production. No code changes between environments.</p><pre># settings/base.py<br>from decouple import config</pre><pre>SECRET_KEY = config(&#39;SECRET_KEY&#39;)<br>DEBUG = config(&#39;DEBUG&#39;, default=False, cast=bool)<br>ALLOWED_HOSTS = config(&#39;ALLOWED_HOSTS&#39;, default=&#39;&#39;, cast=lambda v: [s.strip() for s in v.split(&#39;,&#39;)])</pre><p>Your .env file (which is in .gitignore, obviously):</p><pre># .env — NEVER commit this<br>SECRET_KEY=your-secret-key-here<br>DEBUG=True<br>ALLOWED_HOSTS=localhost,127.0.0.1<br>DB_NAME=myproject<br>DB_USER=postgres<br>DB_PASSWORD=postgres<br>DB_HOST=localhost<br>DB_PORT=5432</pre><p>And you ship a .env.example with the repo so other developers know what variables they need:</p><pre># .env.example — commit this one<br>SECRET_KEY=<br>DEBUG=True<br>ALLOWED_HOSTS=localhost,127.0.0.1<br>DB_NAME=<br>DB_USER=<br>DB_PASSWORD=<br>DB_HOST=localhost<br>DB_PORT=5432</pre><p>This is basic stuff. But I’ve walked into client projects where database passwords were committed to Git. More than once. Don’t be that person.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qNBNtptTHlMM93Me" /></figure><h3>Docker: Because “It Works On My Machine” Isn’t a Deployment Strategy</h3><p>I containerize every project. Not because it’s trendy, but because it eliminates an entire class of problems. Here’s a minimal setup that works:</p><pre># Dockerfile<br>FROM python:3.12-slim</pre><pre>ENV PYTHONDONTWRITEBYTECODE=1<br>ENV PYTHONUNBUFFERED=1</pre><pre>WORKDIR /app</pre><pre>RUN apt-get update &amp;&amp; apt-get install -y \<br>    build-essential \<br>    libpq-dev \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><pre>COPY requirements/production.txt /app/requirements/production.txt<br>RUN pip install --no-cache-dir -r requirements/production.txt</pre><pre>COPY . /app</pre><pre>CMD [&quot;gunicorn&quot;, &quot;--bind&quot;, &quot;0.0.0.0:8000&quot;, &quot;--workers&quot;, &quot;3&quot;, &quot;myproject.wsgi:application&quot;]</pre><pre># docker-compose.yml<br>version: &quot;3.9&quot;</pre><pre>services:<br>  db:<br>    image: postgres:16<br>    environment:<br>      POSTGRES_DB: ${DB_NAME}<br>      POSTGRES_USER: ${DB_USER}<br>      POSTGRES_PASSWORD: ${DB_PASSWORD}<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    ports:<br>      - &quot;5432:5432&quot;</pre><pre>  web:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    command: python manage.py runserver 0.0.0.0:8000<br>    volumes:<br>      - .:/app<br>    ports:<br>      - &quot;8000:8000&quot;<br>    env_file:<br>      - .env<br>    depends_on:<br>      - db</pre><pre>volumes:<br>  postgres_data:</pre><p>This gives you a consistent PostgreSQL database locally and a production-ready Dockerfile. No more “but it works on my machine.”</p><h3>The Makefile: Because I’m Lazy (And You Should Be Too)</h3><p>I add a Makefile to every project so I don’t have to remember long commands:</p><pre># Makefile<br>.PHONY: help setup run migrate shell test lint</pre><pre>help: ## Show this help message<br>    @grep -E &#39;^[a-zA-Z_-]+:.*?## .*$$&#39; $(MAKEFILE_LIST) | sort | awk &#39;BEGIN {FS = &quot;:.*?## &quot;}; {printf &quot;\033[36m%-20s\033[0m %s\n&quot;, $$1, $$2}&#39;</pre><pre>setup: ## Install dependencies and set up the project<br>    pip install -r requirements/local.txt<br>    cp .env.example .env<br>    python manage.py migrate</pre><pre>run: ## Start the development server<br>    python manage.py runserver</pre><pre>migrate: ## Run migrations<br>    python manage.py makemigrations<br>    python manage.py migrate</pre><pre>shell: ## Open Django shell<br>    python manage.py shell_plus</pre><pre>test: ## Run tests<br>    pytest</pre><pre>lint: ## Run linters<br>    ruff check .</pre><p>When a new developer joins a project, they run make setup and they&#39;re ready to go. No wiki page. No onboarding document. Just one command.</p><h3>The Mistakes I Made So You Don’t Have To</h3><p>Let me save you some pain with the things I got wrong:</p><ol><li><strong>I didn’t start with a custom user model.</strong> When I finally needed to add fields to the User model, it was a three-day migration nightmare involving data loss and cold sweats. Start with one.</li><li><strong>I committed </strong><strong>.env to Git.</strong> On a client project. With real AWS credentials. I got lucky — nothing happened. But I got a crash course in .gitignore that day.</li><li><strong>I used SQLite in production “just for now.”</strong> That “just for now” lasted eight months. PostgreSQL is free. Use it from the start, even locally via Docker.</li><li><strong>I kept everything in one Django app.</strong> One app called api that had 47 models and 2000 lines of views.py. Refactoring that was... not fun. Split by domain early.</li><li><strong>I didn’t write tests from the beginning.</strong> Adding tests to an existing codebase is 10x harder than writing them as you go. I know everyone says this. I didn’t listen either. Learn from my stubbornness.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nBtOzF_O-BMN7zsE" /></figure><h3>The Real Point</h3><p>Project structure isn’t about being “correct.” It’s about making your life easier when things get complicated — and they <em>will</em> get complicated. Client requests will change. Features will grow. New developers will join. The structure you set up today is the foundation everything else sits on.</p><p>You don’t need to adopt everything in this article. Pick what makes sense for your project. A weekend prototype doesn’t need Docker. A solo project doesn’t need split settings yet. But the moment you start building something real — something that will run in production and have actual users — these patterns will save you.</p><p>The structure I use today is the result of years of mistakes, refactors, and “I’ll never do that again” moments. I’m sure it’ll keep evolving. But it works for me right now, and that’s what matters.</p><p>Start simple. Add structure when the pain of not having it becomes real. But when that pain comes — and it will — you’ll know what to reach for.</p><p><em>Follow me for more articles on Python, Django, AI, and the real experience of building a software house from scratch. New articles every Tuesday and Friday.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75d677ca4e0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I’m Building a Software House with Python]]></title>
            <link>https://medium.com/@yosephoche/why-im-building-a-software-house-with-python-df3090fcdaa3?source=rss-abf46fdec084------2</link>
            <guid isPermaLink="false">https://medium.com/p/df3090fcdaa3</guid>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[software-house]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Yoseph Parai]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 08:29:35 GMT</pubDate>
            <atom:updated>2026-04-14T08:37:35.545Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>And why I think most people overthink the “perfect” tech stack.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zKT29ESrPv2gMLcT" /><figcaption>Photo by <a href="https://unsplash.com/@joshuaryanphoto?utm_source=medium&amp;utm_medium=referral">Joshua Reddekopp</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A few years ago, a friend asked me to build a web app for his logistics company. I said yes, that turned into more projects, and before I knew it I was running a side business on top of my full-time job. I kept both for a long time — nights, weekends, early mornings. It was exhausting, but it gave me a safety net I wasn’t ready to give up.</p><p>Funny enough, right before everything changed, an old freelance client called out of the blue with a new project. I said yes without thinking much of it. Then September 2025 happened — I got laid off. Suddenly that phone call felt a lot less random. That client is still with me today, and honestly, I don’t know if I’d be writing this without them.</p><p>The layoff stung, but it also gave me something unexpected: focus. For the first time, the software house wasn’t a side thing — it was *the* thing. I’d love to tell you the business has been booming ever since. But the truth is, it’s still not stable. I’m actively looking for freelance projects. Some months are good, some months I’m refreshing my inbox hoping for a lead.</p><p>That’s exactly why I’m writing this — not from some mountaintop of success, but from right here in the trenches, still figuring it out.</p><p>This is the story of why I chose Python to build it, and what I’ve learned so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xVFFeCgznjWpaABZ" /><figcaption>Photo by <a href="https://unsplash.com/@jakubzerdzicki?utm_source=medium&amp;utm_medium=referral">Jakub Żerdzicki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The Python Decision Wasn’t Really a Decision</h4><p>Here’s the thing — I didn’t sit down with a spreadsheet comparing languages. I didn’t spend weeks evaluating stacks. Python was just… what I knew. And honestly, that’s a better reason than most people admit.</p><p>I’d been writing Python professionally for years. I understood its quirks. I knew how to debug its weird moments. I could read someone else’s Python code without wanting to throw my monitor out the window. That counts for a lot when you’re starting a business and every hour matters.</p><p>But there’s more to it than comfort. Python has this rare quality where it gets out of your way. When I’m building something for a client, I want to spend my mental energy on *their* problem, not on fighting the language. Python lets me do that.</p><p>And then there’s Django.</p><p>If Python is the comfortable pair of shoes, Django is the entire outfit that somehow always looks good. Batteries included isn’t just a catchy phrase — it’s the reason I can deliver an MVP in two weeks instead of two months. Auth, ORM, admin panel, middleware — it’s all there. I don’t have to glue together fifteen micro-libraries just to get a basic web app running.</p><p>Some people will tell you Django is “too heavy” or “not modern enough.” I’ve learned to smile and nod at those comments while shipping products that make clients happy and pay the bills.</p><h4>What Actually Matters When Starting Out</h4><p>Looking back at the early days, here’s what I wish someone had told me:</p><p><strong>Your tech stack barely matters in the beginning.</strong></p><p>I know that sounds weird coming from someone writing an entire article about choosing Python. But hear me out — in the first six months, your problems aren’t going to be about scalability, performance, or architecture. Your problems are going to be:</p><p>- Finding clients who actually pay on time<br>- Learning to scope projects without underestimating everything by 40%<br>- Figuring out how to say “no” to bad deals<br>- Sleeping more than 5 hours a night</p><p>The best tech stack in the world won’t save you from bad project management. Trust me on this one. I learned it the hard way when I overscoped a project by literally 3x and had to eat the cost.</p><p><strong>Pick something you’re productive in. Full stop.</strong></p><p>Don’t choose a language because Hacker News says it’s trending. Don’t choose a framework because some influencer on Twitter built a todo app in 30 seconds with it. Choose the tools that let you turn client requirements into working software as fast as possible, with the fewest bugs you can manage.</p><p>For me, that’s Python and Django. For you, it might be Node.js, or Go, or Ruby on Rails. That’s fine. Really. The clients don’t care. They care about results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UvPr-SC7dSRottau" /><figcaption>Photo by <a href="https://unsplash.com/@procopiopi?utm_source=medium&amp;utm_medium=referral">Omar:. Lopez-Rincon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The AI Factor</h4><p>I can’t write this article without talking about AI, because honestly, it’s changed how I work in a fundamental way.</p><p>About a year ago, I started integrating AI into my workflow. Not in the buzzword, “we’re an AI-powered company” way. Just practical stuff:</p><p>- Using AI code assistants to speed up boilerplate writing<br>- Building simple AI features into client projects (chatbots, document processing, that kind of thing)<br>- Automating parts of my testing and code review process</p><p>And here’s what surprised me: clients <strong>love</strong> AI features. Even simple ones. A basic chatbot that can answer FAQs from their documentation? They think it’s magic. An email summarizer? Game changer for their workflow.</p><p>Python’s ecosystem for AI is, frankly, unmatched. OpenAI’s SDK, LangChain, Hugging Face — it’s all Python-first. So my choice of Python ended up paying off in ways I didn’t anticipate when I first started.</p><p>I’ll be writing much more about AI integration in future articles. This is a topic I could talk about for hours, and I’ve made enough mistakes to fill a whole series on “how not to integrate AI into production.”</p><h4>Why I’m Writing This</h4><p>You might be wondering why a backend engineer is writing Medium articles instead of just… coding.</p><p>Two reasons.</p><p><strong>First</strong>, I think our industry has a knowledge-sharing problem. There are thousands of tutorials that show you *how* to build a todo app. There are very few honest accounts of what it’s actually like to run a small software company — the wins, the screw-ups, the 3 AM debugging sessions before a client demo.</p><p>I want to share the real stuff. Not the sanitized LinkedIn version. The actual journey.</p><p><strong>Second</strong>, and I’ll be transparent about this: writing builds an audience, and an audience builds a business. Every article I publish is a small bet that someone out there will read it, find value in it, and maybe think “this person could help us with our project.” That’s not manipulative — it’s just how the world works when you’re a small company without a marketing budget.</p><h4><strong>What’s Coming Next</strong></h4><p>This article is the first in a series where I’ll be documenting everything I’m building and learning. Here’s what’s on the roadmap:</p><p>- <strong>Technical deep dives</strong> — Real, production-grade Django patterns, not toy examples. The kind of stuff I use every day in client projects.<br>- <strong>AI integration guides</strong> — How to actually put OpenAI, LangChain, and other tools into production Django apps without it being a mess.<br>- <strong>Business lessons</strong> — Pricing, scoping, client management, hiring. The stuff they don’t teach in engineering school.<br>- <strong>Honest failures</strong> — Because I’ve already made plenty of mistakes and I’m sure I’ll make more.</p><p>Some of it will be opinionated. Some of it might be wrong. But it’ll all be honest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GVlnn_VnAmX8I_iy" /><figcaption>Photo by <a href="https://unsplash.com/@clark_fransa?utm_source=medium&amp;utm_medium=referral">Arnold Francisca</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The Real Talk</h4><p>Building a software house isn’t glamorous. It’s not sitting in a cool coworking space sipping matcha lattes while your code changes the world. It’s long nights, difficult conversations, constant learning, and a lot of imposter syndrome.</p><p>But it’s also deeply rewarding. There’s something special about building something from nothing — both the code and the company. About seeing a project go from a vague client conversation to a real product that people use. About hiring your first developer and realizing you’re responsible for someone else’s livelihood.</p><p>I chose Python as the foundation. Django as the framework. And honest, practical content as the way to share what I learn along the way.</p><p>If any of this resonates with you — whether you’re a developer thinking about going out on your own, or a founder trying to figure out your tech stack, or just someone curious about what happens behind the scenes of a software house — I’d love to hear from you.</p><p>Drop a comment. Share your story. Let’s figure this out together.</p><p><strong>Follow me for more articles on Python, Django, AI, and the real experience of building a software house from scratch. New articles every Tuesday and Friday.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df3090fcdaa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add New Non Null Foreign Key to Existing Django Model]]></title>
            <link>https://medium.com/@yosephoche/add-new-non-null-foreign-key-to-existing-django-model-a62a6d39bace?source=rss-abf46fdec084------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62a6d39bace</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Yoseph Parai]]></dc:creator>
            <pubDate>Thu, 09 Apr 2020 18:21:37 GMT</pubDate>
            <atom:updated>2020-04-09T18:21:37.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iuO6I1Ex1pDmiQVt" /><figcaption>Photo by <a href="https://unsplash.com/@hejfaisal?utm_source=medium&amp;utm_medium=referral">Faisal M</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>hi…</p><p>Setelah beberapa lama vakum di medium, karena beberapa alasan dan kesibukan, hari ini akhirnya saya kembali bisa menulis artikel di medium :D</p><p>Saya mencoba untuk tetap konsisten menulis tips dan trick yang biasa saya pakai dalam pekerjaan sehari-hari khusunya dalam hal web development menggunakan Django framework.</p><p>Pada kesempatan kali ini saya ingin sedikit berbagi tips buat teman-teman khususnya buat para programmer Django.</p><p>Pada tulisan ini saya akan berbagi tips bagaimana menambahkan field dengan type Foreignkey pada model yang sudah ada sebelumnya, dimana datanya nanti kita akan ambil dari field yang sudah ada namun tidak bertype Foreignkey, langsung saja kita lihat contoh model berikut:</p><pre># Example Model</pre><pre>from django.db import models</pre><pre>class Cart(models.Model):<br>    user = models.ForeignKey(MyUser, on_delete=models.CASCADE)<br>    quantity = models.IntegerField(default=0)<br>    amount = models.IntegerField(default=0)<br>    <strong>order_id = models.CharField(&quot;Order Id&quot;, max_length=255,</strong> null=True, blank=True)<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)</pre><p>pada model Cart diatas terdapat field order_id yang seharunya field itu merupakan Foreignkey dari model Order namun karena kesalahan si programmer field itu di beri type CharField, untuk mengubahnya menjadi Foreignkey kita bisa lakukan secara langsung, tetapi kondisinya berberda ketika model Cart sudah memiliki data, jadi solusinya adalah:</p><ol><li>Buat field Foreignkey baru, seperti berikut:</li></ol><pre>from django.db import models</pre><pre>class Cart(models.Model):<br>    user = models.ForeignKey(MyUser, on_delete=models.CASCADE)<br>  <strong>orders = models.ForeignKey(OrderList, on_delete=models.CASCADE, null=True, blank=True)</strong><br>    quantity = models.IntegerField(default=0)<br>    amount = models.IntegerField(default=0)<br>    order_id = models.CharField(&quot;Order Id&quot;, max_length=255, null=True, blank=True)<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)</pre><p>sperti yang teman-teman lihat, pada model Cart diatas saya menambah field dengan nama orders yang merupakan Foreignkey dari model OrderList.</p><p>2. create dan run schema migration untuk menambahkan relationship yang sudah kita buat pada model diatas ke database, seperti biasa untuk membuat dan menjalankan migration di Django, bisa dilakukan dengan cara:</p><pre><strong>(env)$</strong> python manage.py makemigrations<br><strong>(env)$</strong> python manage.py migrate</pre><p>jika tidak ada error pada saat menjalankan perintah diatas, teman-teman akan melihat pada tabel Cart di database ada field baru yang kita buat pada model Cart diatas.</p><p>3. Buat data migration untuk menduplikat data pada field order_id yang bertype CharField menjadi Foreignkey</p><pre><strong>(env)$ </strong>python manage.py makemigrations --empty --name=copy_order_id</pre><p>perintah --empty berfungsi untuk membuat file migration kosong, --name sebagai nama dari file migrasi yang akan kita buat, nama file ini biasa diikuti dengan suffix nomor file ex. xxxx_nama_file_migrasi dimana xxxx adalah nomor file migrasinya.</p><pre># -*- coding: utf-8 -*-<br># Generated by Django 1.11.17 on 2020-04-09 16:18<br>from __future__ import unicode_literals</pre><pre>from django.db import migrations</pre><pre>def copy_order_id(apps, schema_editor):<br>    Cart = apps.get_model(&quot;api&quot;, &quot;Cart&quot;)<br>    OrderList = apps.get_model(&quot;api&quot;, &quot;OrderList&quot;)<br>    for cart in Cart.objects.all():<br>        try:<br>            if cart.order_id:<br>                order = OrderList.objects.get(order_id=cart.order_id)<br>                if order:<br>                    cart.orders_id = order<br>                    cart.save()<br>        except OrderList.DoesNotExist:<br>            continue</pre><pre>class Migration(migrations.Migration):</pre><pre>dependencies = [<br>        (&#39;api&#39;, &#39;0097_cart_orders&#39;),<br>    ]</pre><pre>operations = [<br>        migrations.RunPython(copy_order_id)<br>    ]</pre><p>saya akan menjelaskan cara kerja code diatas di section selanjutnya.</p><p>4. Jalankan perintah untuk migration, seperti berikut</p><pre><strong>(env)$</strong> python manage.py migrate</pre><h3>How it works…</h3><p>Pertama kita menambahkan field baru ke Cart model, dan membuat file migration untuk digunakan update database. Kemudian, kita membuat file migration kosong untuk melakukan duplikasi data order_id yang sudah ke field Orders untuk dijadikan Foreignkey dari model OrderList. Pada file migration kosong yang kita buat, kita menambahkan beberapa baris code.-</p><ul><li>copy_order_idpada method ini pertama kita mengambil model-model yang akan kita gunakan, dalam kasus ini model yang akan kita gunakan adalah Cart dan OrderList</li></ul><pre>Cart = apps.get_model(&quot;api&quot;, &quot;Cart&quot;)<br>OrderList = apps.get_model(&quot;api&quot;, &quot;OrderList&quot;)</pre><ul><li>Pada baris selanjutnya kita mengambil semua data pada model Cart dan melakukan perulangan untuk mengambil data dari model OrderList yang memiliki order_id yang ada pada model Cart, jika datanya ada maka data tersebut kita masukan kedalam field orders yang kita buat tadi ada pada model Cart . Setelah itu kita memanggil method save() untuk menyimpan datanya.</li></ul><pre>for cart in Cart.objects.all():<br>    try:<br>       if cart.order_id:<br>          order =OrderList.objects.get(order_id=cart.order_id)<br>          if order:<br>             cart.orders_id = order<br>             cart.save()</pre><ul><li>Kemudian, pada class Migration terdapat variable operations yang dimana berisi list dari method yang akan kita jalankan pada saat file migrasi itu di jalankan, dalam kasus ini kita akan menjalankan method copy_order_id</li></ul><pre>class Migration(migrations.Migration):</pre><pre>    dependencies = [<br>        (&#39;api&#39;, &#39;0097_cart_orders&#39;),<br>    ]</pre><pre>    operations = [<br>        migrations.RunPython(copy_order_id)<br>    ]</pre><h3>Summary of adding new ForeignKey to Django</h3><p>Contoh diatas mungkin sedikit membingungkan. Pada dasarnya kita hanya mengganti type CharField dari field yang sudah memiliki data sebelumnya menjadi Foreignkey dari tabel relasinya, dengan membuat multiple file migrasi yang dapat dieksekusi secara berurutan.</p><p>Jika teman-teman memiliki kasus yang serupa, teman-teman bisa melakukan cara diatas tanpa mempengaruhi data-data yang sudah ada sebelumnya, dan mendapatkan field Foreignkey yang bisa memudahkan saat melakukan query database dengan menggunakan relasi tabel.</p><p>Terima Kasih. Good Night. :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62a6d39bace" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arch Linux — Fix error install & Grub Loader]]></title>
            <link>https://medium.com/@yosephoche/arch-linux-fix-error-install-grub-loader-88e3b0aea971?source=rss-abf46fdec084------2</link>
            <guid isPermaLink="false">https://medium.com/p/88e3b0aea971</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[arch]]></category>
            <category><![CDATA[antergos]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <dc:creator><![CDATA[Yoseph Parai]]></dc:creator>
            <pubDate>Sat, 03 Mar 2018 16:50:00 GMT</pubDate>
            <atom:updated>2018-03-03T17:00:21.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*znEXbz76hbk7AFh-.jpg" /></figure><p>yap, dari judulnya sudah sangat jelas apa yang akan saya bagikan, jadi ceritanya kemarin pengen ganti distro linux yang sebelumnya saya pakai <strong><em>Ubuntu</em></strong>, kenapa pengen ganti karena pengen sesuatu yang baru dan kebetulan si ubuntu ini juga mulai agak lemot sih, nah pas nyari referensi distro yang cocok buat kebutuhan kerja, ketemulah si <a href="https://antergos.com/"><strong><em>Antergos</em></strong></a> distro linux turunan dari <a href="https://www.archlinux.org/"><strong><em>Arch Linux</em></strong></a> yang katanya lagi populer dan terkenal dengan keribetan proses instalasinya(untuk level beginner di linux), karena penasaran juga akhirnya saya install juga deh.</p><p>Kalau kata orang <strong><em>Arch Linux</em></strong> ribet installnya, nah si <strong><em>Antergos</em></strong> ini memudahkan apa yang orang anggap ribet, makanya milih Antergos (maklum saya termasuk beginner linux juga :D) tapi bukan berarti proses instalasi Antergos ini agk ada masalah loh, nah disini saya akan sedikit berbagi beberapa masalah yang sempat saya alami dan cara menanganinya ketika pertama install Antergos ini (sampai butuh 12 jam untuk selesai installnya, cupu yak gw :D). Oke langsung saja ya ke masalah yang pertama :</p><ol><li><strong>Antergos Installer-error</strong></li></ol><blockquote>“Can’t install necessary packages. Cnchi can’t continue ….. dst”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*FojW5bXoRS-FCM9m-enH1w.jpeg" /><figcaption>Pesan error yang muncul</figcaption></figure><p>ini masalah pertama yang saya alami, dari pesannya kemungkinan pertama karena ada package yang dibutuhkan tidak dapat di install, entah itu karena koneksi internet saya yang kurang bagus (dibutuhkan koneksi internet untuk install Antergos dan distro turunan dari Arch Linux) atau maybe ada hal lain yang tidak saya ketahui :D, untuk masalah ini solusinya lumayan mudah, cukup dengan edit <strong><em>Mirror List</em></strong> dari antergos, caranya :</p><p>~ Buka terminal/bash kemudian ketiikan perintah berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*Zj2GPgZltd7VWXPLP7VFYw.png" /><figcaption>Command untuk edit Antergos mirror list.</figcaption></figure><p>~ Setelah itu cari pada bagian <strong>“<em>Automated Mirror Selection</em>”</strong> nah disitu ada teks <strong>“<em>Server = http://mirrors.antergos.com/$repo/$arch</em>”</strong> tambahkan tanda <strong>#</strong>(comment) didepan teks itu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*2NML6dn6eTi622xztsjfRg.png" /><figcaption>Tampilan file antergos-mirrorlist.</figcaption></figure><p>Setalah itu scroll sampai ke bawah tepatnya pada bagian <strong><em>“USA”</em></strong>, lalu hilangkan tanda <strong>#</strong> pada teks <br><strong>“<em>Server = http://mirrors.tuxns.net/antergos/$repo/$arch</em>”</strong><br>sehingga hasilnya seperti pada gambar berikut.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*mlrvtv8hbNhg82nVKUlQhw.png" /></figure><p>~ Setelah itu save dengan menekan <strong>ctrl + O</strong> lalu tekan <strong>Enter</strong> dan <strong>ctrl + x</strong> untuk keluar dari editor. Kemudian lakukan proses instalasi selanjutnya (Jangan memulai proses instalasi sebelum melakukan tahap diatas).</p><p>~ Setelah proses instalasi berjalan di tahap untuk memilih mirror yang akan digunakan, pilih option ke 2, yang dimana option ke 2 ini akan menyesuaikan mirror yang digunakan selama proses instalasi dengan yang sudah kita set sebelumnya pada file <strong>antergos-mirrorlist</strong> (maaf lupa screenshot). Setelah itu lanjutkan proses instalasi dengan normal.</p><p>Jadi proses diatas kita lakukan agar selama proses instalasi, mirror yang kita gunakan lebih stabil karena server yang kita pilih dari <em>USA</em> (kalau mau coba server lain juga gak masalah) selain itu, untuk <em>Antergos</em> ini masih banyak <strong><em>issue</em></strong> soal mirror yang bermasalah (sumber dari komunitas Arch &amp; Antergos), itulah alasannya kenapa kita tidak mengaktifkan “<em>Automated Mirror Selection</em>”. Oke Next kita ke masalah yang selanjutnya.</p><p>2. <strong>Boot Loader tidak tampil.</strong></p><p>Untuk masalah yang ini khusus buat kalian yang men-Duet-kan Antergos dengan windows 10 (hampir semua Distro Linux sih yang ngalamin, selama pengalaman saya pakai beberapa distro.) kebetulan di laptop saya sebelumnya sudah terpasang windows 10, setelah proses instalasi Antergos tadi selesai dan laptop minta di restart, saya lakukan lah yang dia mau, dan hasilnya <em>Blank Screen, </em>hanya tampilan layar hitam dan beberapa option booting saja, dipilih salah satunya juga tidak ada efek samping (gak bisa screenshot :D) nah untuk solved problem ini, kita membutuhkan Windows 10 installation (DVD ataupun FlashDisk) karena kita akan <a href="https://neosmart.net/wiki/fix-mbr/"><strong><em>fix the MBR Windows 10</em></strong></a><strong><em>, </em></strong>Atau bisa juga dengan click <strong><em>Automatic Repair</em></strong><em> </em>di<em> </em>Advanced options dari windows 10 installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*2d3agMc5PGEJc56C.jpg" /></figure><p>Setelah proses repair selesai, laptop akan restart dengan sendirinya dan Grub Loader untuk pilihan OS juga akan muncul lagi. <br>Ini dikarenakan Selama proses instalasi Antergos tadi, Grub Loader atau MBR (<em>Master Boot Record</em>) dari windows terhapus, sehingga ketika komputer dinyalakan seolah — olah tidak ada operating system yang terinstall, karena MBR yang memegang informasi tentang <em>logical</em> partisi dari harddisk, yang berisi file <em>system</em>, yang mengatur sistem tersebut. Itulah mengapa komputer atau laptop akan mengalami <em>Blank Screen</em> ketika MBR ini rusak atau terhapus.</p><p>Nah untungnya di Antergos ini gak harus reinstall Grub Loader lagi setelah proses Repair MBR dari windows selesai, dibeberap distro linux yang lain, reinstall grub loader harus dilakukan karena terkadang grub loader dari linux dan MBR dari windows bentrok ketika melakukan booting komputer atau laptop (CMIIW yah :D) mungkin ini juga alasan banyak orang yang suka Arch Linux dan turunannya. Oke mungkin itu saja sedikit pengalaman yang bisa saya share kali ini, semoga bermanfaat dan jangan lupa tepuk tangannya ya guys… see you… #goOpenSource.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88e3b0aea971" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>