In today's digital age, developing robust and secure web applications is essential. Django, one of the most popular frameworks for Python, offers powerful tools to build web applications efficiently. In this article, we will explore how to create a Django REST API that supports file uploads and user authentication. You will learn how to implement a system that allows users to register, log in, and securely upload files, thereby enhancing your application's interactivity and functionality. Let’s embark on this journey to turn your ideas into reality!

Introduction

In this tutorial, you will learn how to create a Django REST API that supports user authentication and file uploads. This API will allow users to register, log in, and upload files securely.

Prerequisites

Before we start, ensure you have the following installed on your system:

  • Python (version 3.6 or higher)
  • pip (Python package manager)

Step 1: Setting Up Your Django Project

1.1 Install Django and Django REST Framework

Start by installing Django and Django REST Framework using pip. Open your terminal and run:

myproject/settings.py

Step 2: User Authentication

2.1 Create a User Serializer

In myapp/serializers.py, create a serializer for the User model to handle user data:

myapp/views.py

2.3 Set Up URLs

In myapp/urls.py, define URLs for the registration and login views:

myproject/urls.py

Step 3: File Upload Functionality

3.1 Create a File Upload Serializer

In myapp/serializers.py, add a serializer to handle file uploads:

myapp/views.py

3.3 Set Up File Upload URLs

Update myapp/urls.py to include the file upload endpoint:

myproject/settings.py

4.2 Serve Media Files in Development

Update myproject/urls.py to serve media files during development:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Step 5: Run Your Server

Before running your server, apply migrations:

python manage.py migrate

Now start the server:

python manage.py runserver

Step 6: Testing the API

You can use tools like Postman or cURL to test your API endpoints.

6.1 Register a User

Send a POST request to register a user:

POST /api/register/
{
    "username": "testuser",
    "email": "[email protected]",
    "password": "password123"
}

6.2 Log In

Send a POST request to log in:

POST /api/login/
{
    "username": "testuser",
    "password": "password123"
}

6.3 Upload a File

Once logged in, you can upload a file:

POST /api/upload/
Authorization: Token <your_token> 
Content-Type: multipart/form-data
{
    "file": <your_file>
}

Conclusion

Congratulations! You have successfully built a Django REST API that includes user authentication and file upload functionality. You can now extend this API by adding more features such as JWT authentication, file storage solutions, or additional endpoints to enhance its capabilities.