Search code examples
djangohttp-status-code-404vercel

404: NOT FOUND Vercel


I depolyed a simple django app on vercel with github. The build was successful, but the site says 404: NOT FOUND

I edited ALLOWED_HOSTS in my settings.py

ALLOWED_HOSTS = ['vercel.app']

enter image description here


Solution

  • Deploying a Django app to Vercel involves a lot of configuration. Since Vercel doesn't have a build config for Django, you would have to do that yourself.

    create a vercel.json file, then put this

    {
        "version": 2,
        "builds": [
            {
                "src": "project_name/wsgi.py",
                "use": "@vercel/python",
                "config": {
                    "maxLambdaSize": "15mb",
                    "runtime": "python3.9"
                }
            },
            {
                "src": "build.sh",
                "use":"@vercel/static-build",
                "config":{
                    "distDir": "staticfiles"
                }
            }
        ],
        "routes": [
            {
                "src":"/static/(.*)",
                "dest":"/static/$1"
            },
            {
                "src": "/(.*)",
                "dest": "project_name/wsgi.py"
            }
        ]
    }
    

    vercel.json serves as a configuration file for your Django application. It defines the Python version, the app's max size, and where to find static files.

    create build.sh for the build commands

    #!/bin/bash
    
    # Update pip
    echo "Updating pip..."
    python3.9 pip install -U pip
    
    # Install dependencies
    
    echo "Installing project dependencies..."
    python3.9 -m pip install -r requirements.txt
    
    # Make migrations
    echo "Making migrations..."
    python3.9 manage.py makemigrations --noinput
    python3.9 manage.py migrate --noinput
    
    # Collect staticfiles
    echo "Collect static..."
    python3.9 manage.py collectstatic --noinput --clear
    
    echo "Build process completed!"
    

    The build.sh updates the current version of pip installed in vercel, installs your application's dependencies, makes migrations to your database, and then collects static files.

    In wsgi.py add

    app = application 
    

    In settings.py

    ALLOWED_HOSTS = [".vercel.app"]
    ...
    STATIC_ROOT = BASE_DIR / "staticfiles" / "static"
    

    Deploy your app again when this configurations have been saved