Chirag's Blog

How to Register Users in Django REST Framework?

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.

Setting Up Django REST Framework

Before we dive into the Django REST Framework, let's set up a new Django project. Follow these steps:

  1. First, ensure we have Python installed on our system. We can download Python from python.org.

  2. Install Django and Django REST Framework using pip:

1pip install django djangorestframework
  1. Create a new Django project:
1django-admin startproject django_rest_demo
2cd django_rest_demo
  1. Create a new Django app:
1python manage.py startapp user_auth
  1. Open django_rest_demo/settings.py and add the user_auth and rest_framework to INSTALLED_APPS:
1INSTALLED_APPS = [
2 # ...
3 'rest_framework',
4 # Token authentication
5 'rest_framework.authtoken',
6 'user_auth',
7]
  1. Run initial migrations:
1python manage.py migrate

Now that we have our Django project set up, let's configure Django REST Framework:

  1. In the 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}
  1. If we're using token authentication, make sure we've added 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__.py
5│ ├── admin.py
6│ ├── apps.py
7│ ├── models.py
8│ ├── serializers.py
9│ ├── tests.py
10│ ├── views.py
11│ └── urls.py
12
13├── django_rest_demo/
14│ ├── __init__.py
15│ ├── asgi.py
16│ ├── settings.py
17│ ├── urls.py
18│ └── wsgi.py
19
20└── manage.py

Creating a Registration Serializer

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 serializers
2from django.contrib.auth.models import User
3
4class UserRegistrationSerializer(serializers.ModelSerializer):
5 password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)
6
7 class Meta:
8 model = User
9 fields = ['username', 'email', 'password', 'password2']
10 extra_kwargs = {
11 'password': {'write_only': True}
12 }
13
14 def validate(self, attrs):
15 if attrs['password'] != attrs['password2']:
16 raise serializers.ValidationError({"password": "Password fields didn't match."})
17 return attrs
18
19 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.

Handling User Registration with Views

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 status
2from rest_framework.response import Response
3from rest_framework.views import APIView
4from .serializers import UserRegistrationSerializer
5
6class 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.

Example Code

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 path
2from .views import UserRegistrationView
3
4urlpatterns = [
5 path('register/', UserRegistrationView.as_view(), name='register'),
6]

Then, in the project's django_rest_demo/urls.py:

1from django.contrib import admin
2from django.urls import path, include
3
4urlpatterns = [
5 path('admin/', admin.site.urls),
6 path('api/', include('user_auth.urls')),
7]

Testing the Registration Endpoint

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" -d
3'{"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.

api-call-success

Conclusion

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.