# FusionAuth QuickStart for Python Django

Integrate FusionAuth with an example Python Django website.

> For the index of this section of the site, see [llms.txt](https://fusionauth.io/docs/llms.txt)

![Python Django](https://fusionauth.io/img/icons/python.svg)

This QuickStart explains how to add a login page and authentication to a website built with [Django](https://www.djangoproject.com/). You'll begin with a simple Django app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.

This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.

## Prerequisites

This QuickStart requires:

*   [Python](https://www.python.org/downloads/) 3.12 or later
*   [Docker](https://docs.docker.com/get-started/get-docker/) 23 or later

If you use macOS or Windows, you need one of the following container management tools:

*   [Docker Desktop](https://www.docker.com/products/docker-desktop/)
*   [OrbStack](https://docs.orbstack.dev/quick-start) (to use OrbStack for `docker compose` commands after installation, run `docker context use orbstack`)
*   [Podman](https://podman.io/docs/installation) (in the commands below, replace `docker` with `podman`)

## Create a Simple Django App

For this QuickStart, we'll use a Django app that reads and writes data to a text file:

1.  Create a folder for the app and navigate into it:
    
    ```shell-session
    $ mkdir django-quickstart && cd django-quickstart
    ```
    
2.  Create a virtual environment for the app's dependencies and activate it:
    
    ```shell-session
    $ python3 -m venv .venv
    ```
    
    ```shell-session
    $ source .venv/bin/activate
    ```
    
    On Windows, activate the virtual environment with `.venv\Scripts\activate` instead.
    
3.  Install dependencies:
    
    ```shell-session
    $ pip install Django==6.1.3
    ```
    
4.  Create a Django project named `notes` in the current folder:
    
    ```shell-session
    $ django-admin startproject notes .
    ```
    
    This creates a `manage.py` file and a `notes` folder with the project's settings and URL configuration.
    
5.  Create the database tables Django uses for sessions and its other built-in apps:
    
    ```shell-session
    $ python manage.py migrate
    ```
    
6.  In the `notes` folder, create a file named `views.py` with the following contents:
    
    ```python
    from pathlib import Path
    
    from django.shortcuts import redirect
    from django.template import RequestContext, Template
    from django.http import HttpResponse
    
    TARGET_FILE = Path(__file__).resolve().parent.parent / 'note.txt'
    
    # Ensure the file exists so we don't crash
    if not TARGET_FILE.exists():
        TARGET_FILE.write_text('Hello! Edit this text.')
    
    # Simple HTML UI
    PAGE = Template('''
    <!DOCTYPE html>
    <html>
    <head>
        <title>Text Editor</title>
        <style>
            body { font-family: sans-serif; margin: 40px; line-height: 1.6; }
            textarea { width: 100%; height: 300px; padding: 10px; margin-bottom: 10px; }
            button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
            button:hover { background: #0056b3; }
        </style>
    </head>
    <body>
        <h1>Edit: {{ filename }}</h1>
        <form method="POST" action="/save">
            {% csrf_token %}
            <textarea name="content">{{ content }}</textarea>
            <br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>
    ''')
    
    
    def home(request):
        context = RequestContext(request, {'filename': TARGET_FILE.name, 'content': TARGET_FILE.read_text()})
        return HttpResponse(PAGE.render(context))
    
    
    def save(request):
        TARGET_FILE.write_text(request.POST['content'])
        return redirect('/')  # Refresh the page to show updated content
    ```
    
    The form includes `{% csrf_token %}` because Django rejects form submissions without a CSRF token.
    
7.  Replace the contents of `notes/urls.py` with the following code, which connects the URLs to the views:
    
    ```python
    from django.urls import path
    from django.views.decorators.http import require_GET, require_POST
    
    from . import views
    
    urlpatterns = [
        path('', require_GET(views.home)),
        path('save', require_POST(views.save)),
    ]
    ```
    
8.  Run the app:
    
    ```shell-session
    $ python manage.py runserver 3000
    ```
    
9.  Open the app at [http://localhost:3000](http://localhost:3000).
    
10.  Replace the text area text with "Hello Django", then click the **Save Changes** button.
     
11.  In a file browser or terminal, look in the `django-quickstart` folder. You should see a new file named `note.txt`, with text content "Hello Django".
     
12.  Congratulations, you have a working Django app that lets you edit a local text file through your web browser. Press **Ctrl+C** on your keyboard to stop the Django server.
     

## Install and Run FusionAuth

Before we can add authentication to our Django app, we need a local FusionAuth instance:

1.  Open your container management tool (listed in the prerequisites above).
    
2.  From the `django-quickstart` folder, clone the [GitHub repository for the FusionAuth instance you'll use with this QuickStart](https://github.com/FusionAuth/fusionauth-quickstart-app):
    
    ```shell-session
    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    ```
    
3.  Navigate into the cloned directory:
    
    ```shell-session
    $ cd fusionauth-quickstart-app
    ```
    
4.  To start a local instance of FusionAuth, run the following command (omit the `-d` flag to see all Docker logs):
    
    ```shell-session
    $ docker compose up -d
    ```
    
5.  Wait until all networks, volumes, and containers show a green status of **Healthy**, **Started**, or **Created**. This may take a few minutes, depending on your network speed and cached dependencies.
    
6.  Open [http://localhost:9011/admin](http://localhost:9011/admin) to access the FusionAuth Admin UI.
    
7.  Log in with these credentials:
    
    *   username: `admin@example.com`
    *   password: `password`
8.  Navigate to Applications -> QuickStart App -> Edit -> OAuth . On this page, you can find your client ID, your client secret, and specify redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our Django app with FusionAuth.
    
9.  Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Django app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.
    

## Add FusionAuth to the Django App

Now that you have a working instance of FusionAuth and a working Django app, let's use FusionAuth to add login to your Django app:

1.  Navigate out of the `fusionauth-quickstart-app` folder, back to the `django-quickstart` folder that contains `manage.py` and `note.txt`:
    
    ```shell-session
    $ cd ..
    ```
    
2.  Create a file named `.env` with the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):
    
    ```plaintext
    FUSIONAUTH_CLIENT_ID=f0510a74-da7a-4101-a474-05e7f1d5ba7e
    FUSIONAUTH_CLIENT_SECRET=super-secret-secret-that-should-be-regenerated-for-production
    FUSIONAUTH_CALLBACK_URL=http://localhost:3000/oauth-callback
    ```
    
3.  Install the dependencies we'll need to authenticate with FusionAuth:
    
    ```shell-session
    $ pip install Authlib==1.9.9 requests==2.34.2 python-dotenv==1.2.4
    ```
    
    Most importantly, we're adding [Authlib](https://docs.authlib.org/), which handles communication with our FusionAuth instance (using [Requests](https://pypi.org/project/requests/) to make HTTP calls), and [python-dotenv](https://pypi.org/project/python-dotenv/), which handles reading our configuration from the `.env` file we just created.
    
4.  Replace the contents of `notes/views.py` with the following code:
    
    ```python
    import os
    from functools import wraps
    from pathlib import Path
    from urllib.parse import urlencode
    
    from django.shortcuts import redirect
    from django.template import RequestContext, Template
    from django.http import HttpResponse
    
    # auth dependencies
    from authlib.integrations.django_client import OAuth
    from dotenv import load_dotenv
    
    BASE_DIR = Path(__file__).resolve().parent.parent
    TARGET_FILE = BASE_DIR / 'note.txt'
    
    # Ensure the file exists so we don't crash
    if not TARGET_FILE.exists():
        TARGET_FILE.write_text('Hello! Edit this text.')
    
    # read configuration from .env file
    load_dotenv(BASE_DIR / '.env')
    FUSIONAUTH_URL = 'http://localhost:9011'
    CLIENT_ID = os.environ['FUSIONAUTH_CLIENT_ID']
    CLIENT_SECRET = os.environ['FUSIONAUTH_CLIENT_SECRET']
    CALLBACK_URL = os.environ['FUSIONAUTH_CALLBACK_URL']
    
    # tell authlib how to talk to fusionauth
    oauth = OAuth()
    oauth.register(
        'fusionauth',
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        server_metadata_url=f'{FUSIONAUTH_URL}/.well-known/openid-configuration',
        client_kwargs={'scope': 'openid', 'code_challenge_method': 'S256'},
    )
    
    
    # require authentication to access
    def login_required(view):
        @wraps(view)
        def wrapped(request, *args, **kwargs):
            if 'user' not in request.session:
                return redirect('/login')
            return view(request, *args, **kwargs)
        return wrapped
    
    
    # Simple HTML UI
    PAGE = Template('''
    <!DOCTYPE html>
    <html>
    <head>
        <title>Text Editor</title>
        <style>
            body { font-family: sans-serif; margin: 40px; line-height: 1.6; }
            textarea { width: 100%; height: 300px; padding: 10px; margin-bottom: 10px; }
            button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
            button:hover { background: #0056b3; }
            .logout-btn { background: #dc3545; color: white; padding: 8px 15px;
                          text-decoration: none; border-radius: 4px; float: right; }
        </style>
    </head>
    <body>
        <a href="/logout" class="logout-btn">Logout</a>
        <h1>Edit: {{ filename }}</h1>
        <form method="POST" action="/save">
            {% csrf_token %}
            <textarea name="content">{{ content }}</textarea>
            <br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>
    ''')
    
    
    # --- routes ---
    def login(request):
        return oauth.fusionauth.authorize_redirect(request, CALLBACK_URL)
    
    
    def oauth_callback(request):
        token = oauth.fusionauth.authorize_access_token(request)
        request.session['user'] = {'id': token['userinfo']['sub']}
        return redirect('/')
    
    
    def logout(request):
        # Clear the local Django session
        request.session.flush()
    
        # Redirect to FusionAuth to clear the SSO session
        return redirect(f'{FUSIONAUTH_URL}/oauth2/logout?' + urlencode({'client_id': CLIENT_ID}))
    
    
    @login_required
    def home(request):
        context = RequestContext(request, {'filename': TARGET_FILE.name, 'content': TARGET_FILE.read_text()})
        return HttpResponse(PAGE.render(context))
    
    
    @login_required
    def save(request):
        TARGET_FILE.write_text(request.POST['content'])
        return redirect('/')  # Refresh the page to show updated content
    ```
    
    The new code connects the app to FusionAuth:
    
    *   `load_dotenv()` reads the configuration from the `.env` file.
    *   `oauth.register` tells Authlib how to talk to FusionAuth. It uses the client Id, client secret, and [PKCE](https://fusionauth.io/docs/authentication/oauth/authorization-code.md#proof-key-for-code-exchange), and finds the login and token endpoints in the OpenID Connect discovery document at `/.well-known/openid-configuration`. With PKCE, Authlib sends a code verifier when it exchanges the authorization code for tokens, so a stolen authorization code is useless on its own.
    *   The `login_required` decorator sends users who aren't logged in to `/login`. It's defined in this file, not Django's built-in `login_required`, which works with Django's own user accounts.
    *   The `/login` route calls `authorize_redirect`, which sends the user to the FusionAuth login page.
    *   The `/oauth-callback` route calls `authorize_access_token`, which exchanges the authorization code from FusionAuth for tokens and validates the [ID token](https://fusionauth.io/docs/authentication/oauth/tokens.md#id-token). The app then stores the user's Id in the Django session.
    *   The `/logout` route clears the Django session, then sends the user to FusionAuth's `/oauth2/logout` endpoint so the FusionAuth session ends too.
5.  Replace the contents of `notes/urls.py` with the following code, which adds the `/login`, `/oauth-callback`, and `/logout` routes:
    
    ```python
    from django.urls import path
    from django.views.decorators.http import require_GET, require_POST
    
    from . import views
    
    urlpatterns = [
        path('', require_GET(views.home)),
        path('save', require_POST(views.save)),
        path('login', require_GET(views.login)),
        path('oauth-callback', require_GET(views.oauth_callback)),
        path('logout', require_GET(views.logout)),
    ]
    ```
    
6.  That's it! Your Django app should now use FusionAuth login. Run the app:
    
    ```shell-session
    $ python manage.py runserver 3000
    ```
    
7.  Open the app at [http://localhost:3000](http://localhost:3000).
    
8.  Log in with the following credentials:
    
    *   username: `richard@example.com`
    *   password: `password`
9.  Edit the text file from the safety of an authenticated Django app.
    
10.  Click **Logout**. FusionAuth ends your session and sends you back to the login page.
     

## Add Independent Notes for Each User

To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:

1.  Open the FusionAuth Admin UI at [http://localhost:9011/admin](http://localhost:9011/admin).
    
2.  Log in with the following credentials:
    
    *   username: `admin@example.com`
    *   password: `password`
3.  Navigate to Applications -> QuickStart App -> Edit -> Registration .
    
    *   Under **Self-service registration**, check that **Registration mode** is set to **Create registration**. The QuickStart configuration has already turned on self-service registration.
    *   In the **Registration field** list, turn on the **Enabled** and **Required** switches for the following rows:
        *   **Birthdate**
        *   **First name**
        *   **Last name**
4.  Click the **Save** button in the top right of the page to save your changes to self-service registration.
    
5.  Navigate to Users -> Richard Hendricks -> Manage .
    
6.  In the **Source** tab, look for the `firstName` and `lastName` fields. That's what we'll use to personalize the UI for each user. We'll use the user's `id` field to generate a unique name for each user's note.
    
7.  Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Django app.
    
8.  Replace the contents of `notes/views.py` with the following code, which requests the `profile` and `email` scopes, reads the user's name (first and last) and Id from the ID token, and stores each user's note in a separate file:
    
    ```python
    import os
    from functools import wraps
    from pathlib import Path
    from urllib.parse import urlencode
    
    from django.shortcuts import redirect
    from django.template import RequestContext, Template
    from django.http import HttpResponse
    
    # auth dependencies
    from authlib.integrations.django_client import OAuth
    from dotenv import load_dotenv
    
    BASE_DIR = Path(__file__).resolve().parent.parent
    
    # set up a directory for multi-user files
    DATA_DIR = BASE_DIR / 'user_data'
    DATA_DIR.mkdir(exist_ok=True)
    
    # read configuration from .env file
    load_dotenv(BASE_DIR / '.env')
    FUSIONAUTH_URL = 'http://localhost:9011'
    CLIENT_ID = os.environ['FUSIONAUTH_CLIENT_ID']
    CLIENT_SECRET = os.environ['FUSIONAUTH_CLIENT_SECRET']
    CALLBACK_URL = os.environ['FUSIONAUTH_CALLBACK_URL']
    
    # tell authlib how to talk to fusionauth
    oauth = OAuth()
    oauth.register(
        'fusionauth',
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        server_metadata_url=f'{FUSIONAUTH_URL}/.well-known/openid-configuration',
        client_kwargs={'scope': 'openid profile email', 'code_challenge_method': 'S256'},
    )
    
    
    # require authentication to access
    def login_required(view):
        @wraps(view)
        def wrapped(request, *args, **kwargs):
            if 'user' not in request.session:
                return redirect('/login')
            return view(request, *args, **kwargs)
        return wrapped
    
    
    # helper to get specific user file
    def get_user_file(user_id):
        return DATA_DIR / f'note-{user_id}.txt'
    
    
    # Simple HTML UI
    PAGE = Template('''
    <!DOCTYPE html>
    <html>
    <head>
        <title>Text Editor</title>
        <style>
            body { font-family: sans-serif; margin: 40px; line-height: 1.6; }
            textarea { width: 100%; height: 300px; padding: 10px; margin-bottom: 10px; }
            button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
            button:hover { background: #0056b3; }
            .logout-btn { background: #dc3545; color: white; padding: 8px 15px;
                          text-decoration: none; border-radius: 4px; float: right; }
        </style>
    </head>
    <body>
        <a href="/logout" class="logout-btn">Logout</a>
        <p style="float: right; margin-right: 20px;">Welcome, {{ name }}</p>
        <h1>Personal Note Editor</h1>
        <form method="POST" action="/save">
            {% csrf_token %}
            <textarea name="content">{{ content }}</textarea>
            <br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>
    ''')
    
    
    # --- routes ---
    def login(request):
        return oauth.fusionauth.authorize_redirect(request, CALLBACK_URL)
    
    
    def oauth_callback(request):
        token = oauth.fusionauth.authorize_access_token(request)
    
        # authlib validates the ID token and decodes its claims into userinfo
        userinfo = token['userinfo']
        full_name = f"{userinfo.get('given_name', '')} {userinfo.get('family_name', '')}".strip()
    
        request.session['user'] = {
            'id': userinfo['sub'],
            'email': userinfo.get('email'),
            'name': full_name or userinfo.get('email') or 'User',
        }
        return redirect('/')
    
    
    def logout(request):
        # Clear the local Django session
        request.session.flush()
    
        # Redirect to FusionAuth to clear the SSO session
        return redirect(f'{FUSIONAUTH_URL}/oauth2/logout?' + urlencode({
            'client_id': CLIENT_ID,
            'post_logout_redirect_uri': 'http://localhost:3000/login',
        }))
    
    
    @login_required
    def home(request):
        user = request.session['user']
        target_file = get_user_file(user['id'])
    
        # Ensure the file exists so we don't crash
        if not target_file.exists():
            target_file.write_text(f"Hello {user['name']}!")
    
        context = RequestContext(request, {'name': user['name'], 'content': target_file.read_text()})
        return HttpResponse(PAGE.render(context))
    
    
    @login_required
    def save(request):
        get_user_file(request.session['user']['id']).write_text(request.POST['content'])
        return redirect('/')  # Refresh the page to show updated content
    ```
    
    Authlib validates the ID token and decodes its claims into `token['userinfo']`, so we don't need a separate JWT library. The logout route also passes a `post_logout_redirect_uri`, which sends the user back to the login page after FusionAuth ends their session.
    
9.  Open the app at [http://localhost:3000](http://localhost:3000). The Django development server reloads the changed file, so you don't need to restart it.
    
10.  Log in with the following credentials:
     
     *   username: `richard@example.com`
     *   password: `password`
11.  *In a separate private/incognito window*, open the app at [http://localhost:3000](http://localhost:3000).
     
12.  Click **Create an account** and create an account using your personal email address, name, and birthdate.
     
13.  Enjoy using your unique user note! You should see your name at the top of the page, and in the default note text.
     

Your Django app now provides unique notes for each user. Each user can independently edit and save their note. To see all of the notes, look for `note-<id>.txt` files in the `user_data` directory. To identify which note corresponds to which user, compare the `id` in the file name with the `id` field in the user's **Source** tab.

## Summary

In this QuickStart, FusionAuth handled login for your Django app:

*   Authlib sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
*   The `login_required` decorator kept logged-out users away from the notes page.
*   The ID token gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
*   FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.

## Next Steps

This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see [Get Started](https://fusionauth.io/docs/get-started.md).

FusionAuth has many features (including [Social Login](https://fusionauth.io/docs/authentication/identity-providers.md#social-identity-providers), [Single Sign-On](https://fusionauth.io/docs/authentication/sessions/enable-sso.md), [Passkeys](https://fusionauth.io/docs/authentication/passkeys/configure.md), [Multi-factor Authentication](https://fusionauth.io/docs/authentication/multi-factor-authentication.md)), most of which are free. This example app is a great starting point for learning about FusionAuth features.

Related

[Quickstarts FusionAuth QuickStart for Python Flask QuickStart integration of Python Flask web application with FusionAuth. python web loginpython authentication](https://fusionauth.io/docs/quickstarts/web/quickstart-python-flask-web.md)

[SDKs Python Client Library Learn how to call FusionAuth from Python applications with the Python client library. python authentication](https://fusionauth.io/docs/sdks/python.md)
---

## Other pages in Web

> For the full index of this section, see [Quickstarts](https://fusionauth.io/docs/llms-quickstarts.txt).

- [FusionAuth QuickStart for Express](https://fusionauth.io/docs/quickstarts/web/express.md): Integrate FusionAuth with an example Express website.
- [Web](https://fusionauth.io/docs/quickstarts/web.md): Explore step-by-step web application QuickStart guides from FusionAuth to seamlessly integrate authentication into your application.
- [FusionAuth QuickStart for Next.js](https://fusionauth.io/docs/quickstarts/web/nextjs.md): Integrate FusionAuth with an example Next.js website.
- [FusionAuth QuickStart for .NET](https://fusionauth.io/docs/quickstarts/web/quickstart-dotnet-web.md): QuickStart integration of .NET web application with FusionAuth.
- [FusionAuth QuickStart for Golang](https://fusionauth.io/docs/quickstarts/web/quickstart-golang-web.md): QuickStart integration of a Golang web application with FusionAuth using the CoreOS OIDC library.
- [FusionAuth QuickStart for Spring Boot With Thymeleaf](https://fusionauth.io/docs/quickstarts/web/quickstart-java-springboot-web.md): QuickStart integration of a Spring Boot web application using Thymeleaf with FusionAuth.
- [FusionAuth QuickStart for Nuxt](https://fusionauth.io/docs/quickstarts/web/quickstart-javascript-nuxt-web.md): QuickStart integration of a Nuxt web application with FusionAuth.
- [FusionAuth QuickStart for Remix](https://fusionauth.io/docs/quickstarts/web/quickstart-javascript-remix-web.md): QuickStart integration of Javascript Remix web application with FusionAuth.
- [FusionAuth QuickStart for Drupal](https://fusionauth.io/docs/quickstarts/web/quickstart-php-drupal-web.md): QuickStart integration of Drupal web application with FusionAuth.
- [FusionAuth QuickStart for Laravel](https://fusionauth.io/docs/quickstarts/web/quickstart-php-laravel-web.md): QuickStart integration of PHP Laravel web application with FusionAuth.
- [FusionAuth QuickStart for PHP](https://fusionauth.io/docs/quickstarts/web/quickstart-php-web.md): QuickStart integration of PHP web application with FusionAuth.
- [FusionAuth QuickStart for Python Flask](https://fusionauth.io/docs/quickstarts/web/quickstart-python-flask-web.md): QuickStart integration of Python Flask web application with FusionAuth.
- [FusionAuth QuickStart for Ruby on Rails](https://fusionauth.io/docs/quickstarts/web/quickstart-ruby-rails-web.md): QuickStart integration of Ruby on Rails web application with FusionAuth.
- [FusionAuth QuickStart for Rust with Actix](https://fusionauth.io/docs/quickstarts/web/quickstart-rust-actix-web.md): QuickStart integration of a Rust Actix web application with FusionAuth.
- [FusionAuth QuickStart for WordPress](https://fusionauth.io/docs/quickstarts/web/quickstart-wordpress-web.md): QuickStart integration of WordPress application with FusionAuth.
