Django React Login | How to setup a login page
By Andrew on 9/6/2024
Implementing a Django React login system can be challenging, but it’s a crucial feature for many web applications. This guide will walk you through the process of setting up authentication using Django on the backend and React on the frontend. If you are looking for a more complete solution, check out our starter kit.
Setting Up Django for Authentication
-
Install required packages:
pip install django djangorestframework djangorestframework-simplejwt
-
Create a new Django project and app:
django-admin startproject myproject cd myproject python manage.py startapp myapp
-
Update
settings.py
:INSTALLED_APPS = [ # ... 'rest_framework', 'rest_framework_simplejwt', 'myapp', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) }
-
Create a serializer in
myapp/serializers.py
:from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email')
-
Set up views in
myapp/views.py
:from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth import authenticate from .serializers import UserSerializer class LoginView(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if user: refresh = RefreshToken.for_user(user) return Response({ 'refresh': str(refresh), 'access': str(refresh.access_token), 'user': UserSerializer(user).data }) return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
-
Update
myproject/urls.py
:from django.urls import path from myapp.views import LoginView urlpatterns = [ path('api/login/', LoginView.as_view(), name='login'), ]
Implementing React Frontend
-
Create a new React app:
npx create-react-app frontend cd frontend
-
Install axios:
npm install axios
-
Create a Login component in
src/components/Login.js
:import React, { useState } from 'react'; import axios from 'axios'; const Login = () => { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const handleLogin = async (e) => { e.preventDefault(); try { const response = await axios.post('http://localhost:8000/api/login/', { username, password }); localStorage.setItem('token', response.data.access); // Handle successful login (e.g., redirect to dashboard) } catch (error) { console.error('Login failed:', error.response.data); // Handle login error (e.g., show error message) } }; return ( <form onSubmit={handleLogin}> <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} placeholder="Username" required /> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" required /> <button type="submit">Login</button> </form> ); }; export default Login;
-
Use the Login component in your main App.js or relevant page.
Connecting Django and React
-
Enable CORS in Django:
- Install django-cors-headers:
pip install django-cors-headers
- Add to INSTALLED_APPS in settings.py:
'corsheaders',
- Add middleware in settings.py:
'corsheaders.middleware.CorsMiddleware',
- Set CORS_ALLOW_ALL_ORIGINS = True in settings.py (for development only)
- Install django-cors-headers:
-
Update React API calls:
- Ensure axios is using the correct Django backend URL
- Add token to request headers for authenticated requests:
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`;
Testing Your Django React Login
- Run Django server:
python manage.py runserver
- In a new terminal, run React app:
npm start
- Navigate to http://localhost:3000 and test the login functionality
Security Considerations
- Use HTTPS in production
- Implement proper CORS settings for production
- Regularly update dependencies
- Use environment variables for sensitive information
- Implement token refresh mechanism
By following this guide, you’ll have a functional Django React login system. Remember to adapt the code to your specific project requirements and always prioritize security in your implementation.
Keep in mind that this is a basic implementation and may need to be adapted to fit the specific needs of your project. If you need a more complete, production-ready solution that handles CSRF, cors, social authentication, two factor authentication, and more, check out our starter kit.
Get SlimSaaS!