Chirag's Blog
October 1, 2024
Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs. One of the most common requirements in web applications is user registration. In this article, we'll explore how to implement user registration using Django REST Framework.
Before we dive into the Django REST Framework, let's set up a new Django project. Follow these steps:
First, ensure we have Python installed on our system. We can download Python from python.org.
Install Django and Django REST Framework using pip
:
1pip install django djangorestframework
1django-admin startproject django_rest_demo2cd django_rest_demo
1python manage.py startapp user_auth
django_rest_demo/settings.py
and add the user_auth
and rest_framework
to INSTALLED_APPS
:1INSTALLED_APPS = [2 # ...3 'rest_framework',4 # Token authentication5 'rest_framework.authtoken',6 'user_auth',7]
1python manage.py migrate
Now that we have our Django project set up, let's configure Django REST Framework:
django_rest_demo/settings.py
, we can add any DRF-specific settings. For example:1REST_FRAMEWORK = {2 'DEFAULT_AUTHENTICATION_CLASSES': [3 'rest_framework.authentication.TokenAuthentication',4 ],5}
rest_framework.authtoken
to INSTALLED_APPS
as shown in step 5 above.Here's how our project structure might look:
1django_rest_demo/2│3├── user_auth/4│ ├── __init__.py5│ ├── admin.py6│ ├── apps.py7│ ├── models.py8│ ├── serializers.py9│ ├── tests.py10│ ├── views.py11│ └── urls.py12│13├── django_rest_demo/14│ ├── __init__.py15│ ├── asgi.py16│ ├── settings.py17│ ├── urls.py18│ └── wsgi.py19│20└── manage.py
Serializers in DRF allow complex data, such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. They also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
Let's create a serializer for user registration: In the user_auth/serializers.py
:
1from rest_framework import serializers2from django.contrib.auth.models import User34class UserRegistrationSerializer(serializers.ModelSerializer):5 password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)67 class Meta:8 model = User9 fields = ['username', 'email', 'password', 'password2']10 extra_kwargs = {11 'password': {'write_only': True}12 }1314 def validate(self, attrs):15 if attrs['password'] != attrs['password2']:16 raise serializers.ValidationError({"password": "Password fields didn't match."})17 return attrs1819 def create(self, validated_data):20 user = User.objects.create_user(21 username=validated_data['username'],22 email=validated_data['email'],23 password=validated_data['password']24 )25 return user
This serializer extends ModelSerializer and uses the User model. It includes a password confirmation field and custom validation to ensure the passwords match.
Now that we have our serializer, let's create a view to handle the registration process. In the user_auth/views.py
:
1from rest_framework import status2from rest_framework.response import Response3from rest_framework.views import APIView4from .serializers import UserRegistrationSerializer56class UserRegistrationView(APIView):7 def post(self, request):8 serializer = UserRegistrationSerializer(data=request.data)9 if serializer.is_valid():10 serializer.save()11 return Response({12 "message": "User registered successfully"13 }, status=status.HTTP_201_CREATED)14 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
This view uses the UserRegistrationSerializer to validate the incoming data and create a new user if the data is valid.
To complete our code, let's set up the URLs to make our registration view accessible.
In our user_auth/urls.py
(create this file if it doesn't exist):
1from django.urls import path2from .views import UserRegistrationView34urlpatterns = [5 path('register/', UserRegistrationView.as_view(), name='register'),6]
Then, in the project's django_rest_demo/urls.py
:
1from django.contrib import admin2from django.urls import path, include34urlpatterns = [5 path('admin/', admin.site.urls),6 path('api/', include('user_auth.urls')),7]
We can now run our Django development server:
1python manage.py runserver
To test the registration endpoint, we can use tools like curl, Postman, or even the Django REST Framework browsable API. Here's an example using curl:
1curl -X POST http://localhost:8000/api/register/2-H "Content-Type: application/json" -d3'{"username":"newuser",4"email":"[email protected]",5"password":"securepassword",6"password2":"securepassword"}'
If successful, we should receive a response indicating that the user was registered successfully.
In this article, we've covered how to set up a Django project named "django-rest-demo" from scratch and implement user registration using Django REST Framework in an app called "user_auth". We created a custom serializer to handle the registration data, including password confirmation and validation. We then created a view to process the registration and return appropriate responses.
This implementation provides a solid foundation for user registration in our DRF project. Remember to add appropriate permissions and authentication to our views as needed, and consider adding features like email verification for a more robust registration process.