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!
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.
Before we start, ensure you have the following installed on your system:
Start by installing Django and Django REST Framework using pip. Open your terminal and run:
pip install django djangorestframework
Create a new Django project by running the following commands:
django-admin startproject myproject cd myproject
Within your project, create a new app where we will implement the API:
python manage.py startapp myapp
Open myproject/settings.py
and add 'myapp'
and 'rest_framework'
to the INSTALLED_APPS
list:
INSTALLED_APPS = [ ... 'rest_framework', 'myapp', ]
In myapp/serializers.py
, create a serializer for the User model to handle user data:
from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email']
In myapp/views.py
, implement views for user registration and login:
from django.contrib.auth.models import User from django.contrib.auth import authenticate from rest_framework import generics from rest_framework.response import Response from rest_framework.permissions import AllowAny from .serializers import UserSerializer class RegisterView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [AllowAny] class LoginView(generics.GenericAPIView): permission_classes = [AllowAny] def post(self, request): username = request.data.get("username") password = request.data.get("password") user = authenticate(username=username, password=password) if user is not None: return Response({"message": "Login successful"}) return Response({"message": "Invalid credentials"}, status=400)
In myapp/urls.py
, define URLs for the registration and login views:
from django.urls import path from .views import RegisterView, LoginView urlpatterns = [ path('register/', RegisterView.as_view(), name='register'), path('login/', LoginView.as_view(), name='login'), ]
Then, include these URLs in your main myproject/urls.py
:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('myapp.urls')), ]
In myapp/serializers.py
, add a serializer to handle file uploads:
from rest_framework import serializers class FileUploadSerializer(serializers.Serializer): file = serializers.FileField()
Add a view in myapp/views.py
to handle the file upload:
from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated class FileUploadView(APIView): permission_classes = [IsAuthenticated] def post(self, request): serializer = FileUploadSerializer(data=request.data) if serializer.is_valid(): file = serializer.validated_data['file'] # Handle the file (e.g., save it) return Response({"message": "File uploaded successfully"}) return Response(serializer.errors, status=400)
Update myapp/urls.py
to include the file upload endpoint:
urlpatterns += [ path('upload/', FileUploadView.as_view(), name='file-upload'), ]
In myproject/settings.py
, configure media settings to handle file uploads:
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
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)
Before running your server, apply migrations:
python manage.py migrate
Now start the server:
python manage.py runserver
You can use tools like Postman or cURL to test your API endpoints.
Send a POST request to register a user:
POST /api/register/ { "username": "testuser", "email": "[email protected]", "password": "password123" }
Send a POST request to log in:
POST /api/login/ { "username": "testuser", "password": "password123" }
Once logged in, you can upload a file:
POST /api/upload/ Authorization: Token <your_token> Content-Type: multipart/form-data { "file": <your_file> }
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.