How to deploy a django project with staticfiles on vercel

 In this post I am going to show you how you can deploy your django or django rest framework project on vercel in 9 easy steps.

Please note

  • For this post I am assuming that you have setup your django project.
  • This process works on django framework and django restframework projects.
  • And also for my project databse I am using postgres_db.
  • Vercel does not provide support for dbsqlite3 currently, if you try to deploy your project with django's default dbsqlite3 database then its going to lead to an error. Ensure to comment out your dbsqlite database configuration or switch to a different database (e.g postgreSQL).

Alright lets begin;

Step 1

In your projects root directory create a new file and name it build_files.sh then paste the code below inside it

# build_files.sh
pip install -r requirements.txt
python3.9 manage.py collectstatic

This file contains commands we want to run at build time on vercel

"pip install -r requirements.txt" ensures that all our installed packages declared in our requirements.txt file is downloaded and installed on the vercel server.

"python3.9 manage.py collectstatic" ensures that our static files are served on our server (ensure to add this line of code even if your staticfiles are being served from an external website because our admin page contains some static files).

Step 2

In your projects root directory create a new json file and name it vercel.json then paste the code below inside it

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

Ensure to replace projectname with the actual name of your project.

Under "builds""src": "projectname/wsgi." points to the file that contains a WSGI application declaration that was created by django for you in your projects directory.

"config": { "maxLambdaSize": "15mb", "runtime":"python3.9" } increases the size limit of our bundle (the default is 5MB),  while runtime specifies the python version we want to use, in this case we are using python 3.9.

"routes": [ ... ] rewrites all routes ("src": "/(.*)") to our WSGI application ("dest": "projectname/wsgi.py") to be handled.

Step 3

Go to your projects setting.py and paste in the code below

STATICFILES_DIRS = os.path.join(BASE_DIR, 'static'),
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles_build', 'static')
Step 4

Create an empty folder and name it static in your projects root directory (this is where all our static files will be stored). 

Next update your project's urls.py by pasting in the configuration settings below after urlpatterns=[ ];

urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Your project's urls.py should resemble the one shown below;
# your imports
urlpatterns = [
    #url paths
    
    
]
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Step 5

If you are using dbsqlite3 then comment it out like so. Since this is going to be a production enviroment I highly recommend that you should switch to another database such as postgreSQL.

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': BASE_DIR / 'db.sqlite3',
    # }
}
Step 6

If you commented out your database as shown above then skip this step.

But if you took my advice and switched to a diffrent database then run the following commands in your terminal

python manage.py makemigrations
python manage.py migrate

Creates a new migration and migrate your django project to your database. This is to needed for staticfiles to served on the vercel server.

Step 7

Next step is to go to your settings.py file and update your ALLOWED_HOST to permit vercel.app to be a valid hostname for your django app like so

ALLOWED_HOSTS = ['.vercel.app', '.now.sh']
Step 8

Go to your wsgi.py file created for you by django in your peoject directory and paste in the line of code below

app = application

This will point the app variable that vercel is going to be looking for to your project.

Step 9

Finally upload your code to a github repo and connect your github account with said repo to your vercel dashboard.

Import the project.

You can change the default project name to something else if you wish but ensure to leave all other settings as default.

Then click on deploy and after a couple of seconds your project will be deployed successfully on vercel.

Finally go to this link to see the example project on my github page.

Ps. Checkout the link below to learn how you can add a free postgreSQL database for your project.

Hosting PostgreSQL database on Supabase for free (devmaesters.com)

If you are migrating your django site from one platform(e.g heroku) to another platform (e.g vercel) then checkout the link below to learn how you can migrate your postgreSQL database to supabase for free.

Migrating your PostgreSQL database from one hosting platform to another (e.g Heroku to Supabase) (devmaesters.com)

Conclusion

Following the steps above will get your django or django rest framework project hosted on vercel. As always thanks for reading, if you have any questions, thoughts or run into any error's following the steps above then leave a comment down below and I'll try my best to help.

Author
author-image

Hello, my name is Abubakar Zakari. Am a budding fullstack developer from Nigeria who loves developing softwares and learning new frameworks and langauges.

Comment

Select image


Comments
message profile
Asadbek
2022-07-22

hello Abubakar Zakariy. My name is Asadbek, from Uzbekistan, I am getting this error how can i solve it: TypeError: decoding to str: need a bytes-like object, PosixPath found Error: Command "./build_files.sh" exited with 1

message profile
Admin
2022-07-23

Hello @Asadbek, please add the complete error log so it will be clearer where exactly the error is being thrown from

message profile
Luis
2022-08-18

Hello, I get this error: This Serverless Function has crashed. Your connection is working correctly. Vercel is working correctly. 500: INTERNAL_SERVER_ERROR Code: FUNCTION_INVOCATION_FAILED One question, what specific version of Python do you use?

message profile
Admin
2022-08-27

Check your function logs on vercel. You will see the exact cause of the error.

message profile
Joe
2022-10-07

i was unable to makemigration and also to connect remote mysql server

message profile
Afnan
2022-10-09

Hello sir I follow these steps but I have the following issue would you help me please Traceback (most recent call last): File "manage.py", line 20, in main() File "manage.py", line 13, in main "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Error: Command "./build_files.sh" exited with 1

message profile
Admin
2022-10-15

@afnan sorry I took so long to reply. If this error is on your local machine then its because you have not activated your virtual environment or you activated the wrong one.

message profile
Admin
2022-10-15

@joe sorry I took so long to reply. Use a postgreSQL database, I wrote another article on how to get one for free on supabase

Hosting PostgreSQL database on Supabase for free (devmaesters.com)

message profile
Aaron Tech
2022-12-06

Please how do I move my default sqlite3 database to PostgreSQL?

message profile
narasimha
2022-12-13

Error: No Output Directory named "staticfiles_build" found after the Build completed. You can configure the Output Directory in your Project Settings. please help me with this error

message profile
Admin
2022-12-13

@Aaron Tech

Checkout this link Migrating your PostgreSQL database from one hosting platform to another (e.g Heroku to Supabase) (devmaesters.com)

Although the link explains how to migrate from postgreSQL to postgreSQL, the process also works for migrating from dbsqlite to postgreSQL.

message profile
Admin
2022-12-13

@narasimha

I need you to;

  • Confirm that you have created a static folder in your root directory
  • Ensure that your media and static configurations are in your projects urls.py. Below are the configurations, paste them after the first urlpatterns in your urls.py
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Your urls.py should resemble the one shown below;

# your imports
urlpatterns = [
    #url paths
    
    
]
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

 

message profile
Meri
2023-01-10
Guys if you have problems with static files this might be the reason: Git doesn't track empty folders. So adding empty static folder is not enough. Add a empty txt file to it. So that you can push the empty folder to GitHub.
message profile
Mukesh
2023-01-14
Project is being deployed successfully but when i open url it's showing me an error "404: NOT_FOUND Code: NOT_FOUND" PLEASE HELP struggling since a week to deploy...
message profile
Martin
2023-03-13
Hey man, I got a problem when I'm trying to import mi Git on Vercel ./build_files.sh: line 3: python3.11.1: command not found Error: Command "./build_files.sh" exited with 127 BUILD_FAILED: Command "./build_files.sh" exited with 127 I worked my Django Project with Python 3.11 as Interpreter, so, what should I do?
message profile
nick gurr
2023-05-30
Fix for error "Error: No Output Directory named 'staticfiles_build'" : Try to install pip and python with the required version instead of giving default commands. Eg : echo " BUILD START" pip3 install -r requirements.txt python3.9 manage.py collectstatic --noinput --clear echo " BUILD END"
message profile
Tomi
2023-06-01
Thanks for this boss, amazing website by the way. Can I get your WhatsApp number I want to have a consultation about a small project with you
message profile
Admin
2023-06-02

Hey everyone, I apologize for the delayed responses. I am always eager to assist, and you can easily reach me through my contact details listed on this page here

message profile
Tintu Tom
2023-12-05
Is it possible to deploy drf ASGI project in vercel
message profile
faith
2023-12-10
woah.. i have ransacked all of google, even chatgpt is not helping..but this works thanks a lot man... i am an Ekiti guy oooo..lol
message profile
Admin
2023-12-12

@Faith

Happy to have been of help boss.

DEVMAESTERS

Newsletter

Services

Frontend Development |Backend Development |Full Website Development |Bootstrap Website upgrades | Website Debbugging | Website Hosting & deployment

Contact

Interested in hiring me or collaborating with me on a project, click on any of the links below to get my social media handle

Or contact me via Tel: (+234)-806-225-7480 | Email: abubakarzakari1703@gmail.com

Copywright@devmaesters.com
Privacy Policy

By using our website,
you agree that devmaesters can store cookies on your device and disclose information in accordance with our privacy policy.