How to Register Users in Django REST Framework?
Last Updated :
01 Oct, 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:
pip install django djangorestframework
3. Create a new Django project:
django-admin startproject django_rest_demo
cd django_rest_demo
4. Create a new Django app:
python manage.py startapp user_auth
5. Open django_rest_demo/settings.py and add the user_auth and rest_framework to INSTALLED_APPS:
Python
INSTALLED_APPS = [
# ...
'rest_framework',
# Token authentication
'rest_framework.authtoken',
'user_auth',
]
6. Run initial migrations:
python 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:
Python
# ...
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
2. 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:
django_rest_demo/
│
├── user_auth/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── serializers.py
│ ├── tests.py
│ ├── views.py
│ └── urls.py
│
├── django_rest_demo/
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
│
└── 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:
Python
from rest_framework import serializers
from django.contrib.auth.models import User
class UserRegistrationSerializer(serializers.ModelSerializer):
password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)
class Meta:
model = User
fields = ['username', 'email', 'password', 'password2']
extra_kwargs = {
'password': {'write_only': True}
}
def validate(self, attrs):
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError({"password": "Password fields didn't match."})
return attrs
def create(self, validated_data):
user = User.objects.create_user(
username=validated_data['username'],
email=validated_data['email'],
password=validated_data['password']
)
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:
Python
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import UserRegistrationSerializer
class UserRegistrationView(APIView):
def post(self, request):
serializer = UserRegistrationSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({
"message": "User registered successfully"
}, status=status.HTTP_201_CREATED)
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):
Python
from django.urls import path
from .views import UserRegistrationView
urlpatterns = [
path('register/', UserRegistrationView.as_view(), name='register'),
]
Then, in the project's django_rest_demo/urls.py:
Python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('user_auth.urls')),
]
Testing the Registration Endpoint
We can now run our Django development server:
python 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:
curl -X POST http://localhost:8000/api/register/
-H "Content-Type: application/json" -d
'{"username":"newuser",
"email":"[email protected]",
"password":"securepassword",
"password2":"securepassword"}'
If successful, we should receive a response indicating that the user was registered successfully.
Success returned on calling the register user API endpointConclusion
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.
Similar Reads
ListField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
4 min read
Get Request.User in Django-Rest-Framework Serializer
In Django Rest Framework (DRF), serializers are used to transform complex data types, such as queryset and model instances, into native Python data types. One common requirement is to access the request.user within a serializer, which is particularly useful when you need to customize the serializati
4 min read
How to return custom JSON in Django REST Framework ?
In this article, we will create class-based views and combine this with the serializer class to return JSON representation for each HTTP request. For our class-based views, we will make use of a set of generic views, which help to achieve minimum lines code. Generic Classes and ViewsetsHTTP request
9 min read
Nestest Serializer in Django Framework
In web development, creating and consuming APIs (Application Programming Interfaces) is commonplace. Django Rest Framework (DRF) serves as a robust toolkit for building APIs in Django-based web applications. Within DRF, a pivotal concept is serializers. In this article, we will delve into the concep
4 min read
How To Filter A Nested Serializer In Django Rest Framework?
When building APIs with Django Rest Framework (DRF), nested serializers are commonly used to represent relationships between models. A nested serializer allows us to include data from related models within a serializer. However, there are instances where we might want to filter the data returned by
6 min read
JSONField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
4 min read
IPAddressField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
4 min read
How to throttle API with Django Rest Framework
Have you ever passed through an overbridge and noticed the sign stating the bridge weight restriction? Those restrictions are put in place to ensure public safety. Django REST Framework uses a similar process named throttling that controls the rate of requests that the client can make to an API. Thi
4 min read
ModelSerializer in serializers - Django REST Framework
ModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds. There are three stages before creating a API throu
7 min read
Serializer Relations - Django REST Framework
Serialization is one of the most important concepts in RESTful Webservices. Â It facilitates the conversion of complex data (such as model instances) to native Python data types that can be rendered using JSON, XML, or other content types. In Django REST Framework, we have different types of serializ
15+ min read