Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      From Data To Decisions: UX Strategies For Real-Time Dashboards

      September 13, 2025

      Honeycomb launches AI observability suite for developers

      September 13, 2025

      Low-Code vs No-Code Platforms for Node.js: What CTOs Must Know Before Investing

      September 12, 2025

      ServiceNow unveils Zurich AI platform

      September 12, 2025

      Building personal apps with open source and AI

      September 12, 2025

      What Can We Actually Do With corner-shape?

      September 12, 2025

      Craft, Clarity, and Care: The Story and Work of Mengchu Yao

      September 12, 2025

      Distribution Release: Q4OS 6.1

      September 12, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Learning from PHP Log to File Example

      September 13, 2025
      Recent

      Learning from PHP Log to File Example

      September 13, 2025

      Online EMI Calculator using PHP – Calculate Loan EMI, Interest, and Amortization Schedule

      September 13, 2025

      Package efficiency and dependency hygiene

      September 13, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Dmitry — The Deep Magic

      September 13, 2025
      Recent

      Dmitry — The Deep Magic

      September 13, 2025

      Right way to record and share our Terminal sessions

      September 13, 2025

      Windows 11 Powers Up WSL: How GPU Acceleration & Kernel Upgrades Change the Game

      September 13, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to Enable CORS in Django

    How to Enable CORS in Django

    April 28, 2025

    If you’ve ever tried to connect your frontend app to your Django backend and suddenly hit an error that looks something like “has been blocked by CORS policy”, you’re not alone. It’s frustrating, especially when your code seems fine.

    So what’s going on?

    This is where CORS (Cross-Origin Resource Sharing) comes in. It’s a browser security feature that blocks web pages from making requests to a different domain than the one that served the web page.

    It’s there to protect users, but if it’s not configured correctly, it can stop your app from working the way you want.

    Let’s fix that.

    In this article, I’ll walk you through everything you need to know to enable CORS in Django without headaches.

    Here’s what we’ll cover:

    • What is CORS and Why Should You Care?

    • How to Enable CORS in Django

      • 1. Install django-cors-headers

      • 2. Add It to INSTALLED_APPS

      • 3. Add Middleware

      • 4. Set the Allowed Origins

    • Optional Settings You Might Need

      • Allow All Origins (Not Recommended for Production)

      • Allow Credentials (Cookies, Auth)

      • Allow Specific Headers

    • Example: Full Settings File Snippet

    • Common Errors (And How to Fix Them)

      • 1. CORS Not Working At All?

      • 2. Preflight Request Fails (OPTIONS method)

      • 3. Using Django Rest Framework?

    • FAQs

      • Can I allow multiple frontend URLs?

      • Does CORS affect local development only?

      • Is it secure to allow all origins?

      • Do I need to change anything on the frontend?

    • Further Resources

    • Final Thoughts

    What is CORS and Why Should You Care?

    Before you start changing settings, it’s important to understand what CORS is.

    Imagine you have a frontend built with React running on http://localhost:3000 and a Django API running on http://localhost:8000.

    When the frontend tries to talk to the backend, your browser sees that they’re not the same origin (they have different ports), and it blocks the request.

    That’s CORS doing its job. It assumes you might be trying to do something unsafe – like stealing cookies or user data – so it steps in.

    Now, as a developer, if you trust the frontend and you own both ends, then it’s safe to let those requests through. You just need to tell Django it’s okay.

    How to Enable CORS in Django

    You’re going to need a third-party package called django-cors-headers. It’s widely used and actively maintained. Here’s how to set it up:

    1. Install django-cors-headers

    Run this in your terminal:

    pip install django-cors-headers
    

    This adds the package to your environment so Django can use it.

    2. Add It to INSTALLED_APPS

    Open your settings.py file and find the INSTALLED_APPS section. Add this line:

    INSTALLED_APPS = [
        ...
        <span class="hljs-string">'corsheaders'</span>,
    ]
    

    This registers the app with Django.

    3. Add Middleware

    Now scroll down to the MIDDLEWARE section in settings.py. Add this at the top of the list:

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

    Why at the top? Because middleware in Django runs in order. If you don’t place it at the top, the CORS headers might not be added correctly, and your browser will still block your requests.

    4. Set the Allowed Origins

    This is where you tell Django which origins are allowed to talk to your backend.

    Still in settings.py, add:

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

    Replace localhost:3000 with whatever domain or port your frontend is using. If you’re using HTTPS or deploying, make sure to include the correct URL, like https://yourfrontend.com.

    And that’s it! You’re now allowing your frontend to access your backend.

    Optional Settings You Might Need

    Depending on your project, you might run into other issues. Here are some extra settings you might find useful:

    Allow All Origins (Not Recommended for Production)

    If you’re just testing and want to allow everything (be careful with this), you can use:

    CORS_ALLOW_ALL_ORIGINS = <span class="hljs-literal">True</span>
    

    Again, don’t use this in production unless you understand the risks. It can open up your API to abuse.

    Allow Credentials (Cookies, Auth)

    If your frontend is sending authentication credentials like cookies or tokens, you also need this:

    CORS_ALLOW_CREDENTIALS = <span class="hljs-literal">True</span>
    

    And make sure you don’t use CORS_ALLOW_ALL_ORIGINS with this setting – it won’t work due to security rules. Stick to CORS_ALLOWED_ORIGINS.

    Allow Specific Headers

    By default, common headers are allowed, but if you’re sending custom ones (like X-Auth-Token), you can add:

    CORS_ALLOW_HEADERS = [
        <span class="hljs-string">"content-type"</span>,
        <span class="hljs-string">"authorization"</span>,
        <span class="hljs-string">"x-auth-token"</span>,
        ...
    ]
    

    Example: Full Settings File Snippet

    Here’s a mini version of what your settings.py might look like after setup:

    INSTALLED_APPS = [
        ...
        <span class="hljs-string">'corsheaders'</span>,
        ...
    ]
    
    MIDDLEWARE = [
        <span class="hljs-string">'corsheaders.middleware.CorsMiddleware'</span>,
        <span class="hljs-string">'django.middleware.common.CommonMiddleware'</span>,
        ...
    ]
    
    CORS_ALLOWED_ORIGINS = [
        <span class="hljs-string">"http://localhost:3000"</span>,
    ]
    
    CORS_ALLOW_CREDENTIALS = <span class="hljs-literal">True</span>
    

    You can tweak this based on your needs, but that’s the basic structure.

    Common Errors (And How to Fix Them)

    1. CORS Not Working At All?

    Double check:

    • You added corsheaders.middleware.CorsMiddleware it at the top of the middleware list.

    • Your frontend origin matches exactly, including port and protocol.

    • You restarted your server after changing the settings.

    2. Preflight Request Fails (OPTIONS method)

    Sometimes your browser sends an OPTIONS request first to check if the server will allow the real request. Make sure your views or Django setup allow that method, or Django will return a 405 error.

    You don’t usually need to do anything here unless you’re using a custom middleware or view decorator that blocks it.

    3. Using Django Rest Framework?

    No problem – django-cors-headers works out of the box. Just make sure it’s installed and the middleware is set up correctly.

    FAQs

    Can I allow multiple frontend URLs?

    Yes! Just add more items to the list:

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

    Does CORS affect local development only?

    No, it applies in production too. Any time your frontend and backend are on different origins (different domain or port), you need to handle CORS.

    Is it secure to allow all origins?

    No. Only do that temporarily during development. Always restrict access in production to just the domains you trust.

    Do I need to change anything on the frontend?

    Sometimes. If you’re sending credentials (like cookies), you’ll need to set credentials: "include" in your fetch or Axios requests.

    Example with fetch:

    fetch(<span class="hljs-string">"http://localhost:8000/api/data"</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">"GET"</span>,
      <span class="hljs-attr">credentials</span>: <span class="hljs-string">"include"</span>,
    })
    

    Final Thoughts

    CORS can feel like a wall you keep running into when building web apps. But once you get the hang of how it works – and how to set it up in Django – it becomes a small thing you configure and move on.

    Just remember:

    • Be specific in production

    • Always restart the server after changes

    • Don’t ignore warnings in your browser console – they’re your friends

    Now you know how to enable CORS in Django the right way.

    Further Resources

    • django-cors-headers GitHub page – for full documentation.

    • MDN CORS Overview – to understand how CORS works under the hood.

    • Official Django Middleware Docs

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleHow to Build a Website from Scratch – Start to Finish Walkthrough
    Next Article How to Turn Ubuntu 24.04 into a KVM Hypervisor – Quick Setup with Web Management

    Related Posts

    Artificial Intelligence

    Scaling Up Reinforcement Learning for Traffic Smoothing: A 100-AV Highway Deployment

    September 13, 2025
    Defending against Prompt Injection with Structured Queries (StruQ) and Preference Optimization (SecAlign)
    Artificial Intelligence

    Defending against Prompt Injection with Structured Queries (StruQ) and Preference Optimization (SecAlign)

    September 13, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-5335 – Autodesk Installer Privilege Escalation Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-6527 – “70mai M300 Web Server Local Network Access Control Vulnerability”

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-7434 – Tenda FH451 Stack-Based Buffer Overflow Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    How to browse your Android storage on Windows 11 without any USB cables

    News & Updates

    Highlights

    Will using a VPN help protect you from malware or ransomware?

    April 1, 2025

    There are many good reasons to use a VPN, especially when traveling. But be sure…

    Rilasciato Calibre 8.8: Una Panoramica Completa delle Novità e delle Funzionalità Aggiuntive

    August 8, 2025

    Nelson is a numerical computational language

    May 29, 2025

    CVE-2025-35010 – Microhard BulletLTE-NA2 and IPn4Gii-NA2 Command Injection Vulnerability

    June 8, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.