Bookings backend
First of all you need to create backend classes in your models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django_rest_passwordreset.signals import reset_password_token_created from django.dispatch import receiver from django.urls import reverse from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from django.utils.html import strip_tags import random import string from datetime import datetime, timedelta from django.contrib.auth.models import User from django.conf import settings from django.core.exceptions import ValidationError class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields ): if not email: raise ValueError('Email is a required field') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): email = models.EmailField(max_length=200, unique=True) birthday = models.DateField(null=True, blank=True) username = models.CharField(max_length=200, null=True, blank=True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] @receiver(reset_password_token_created) def password_reset_token_created(reset_password_token, *args, **kwargs): sitelink = "http://localhost:5173/" token = "{}".format(reset_password_token.key) full_link = str(sitelink)+str("password-reset/")+str(token) print(token) print(full_link) context = { 'full_link': full_link, 'email_adress': reset_password_token.user.email } html_message = render_to_string("backend/email.html", context=context) plain_message = strip_tags(html_message) msg = EmailMultiAlternatives( subject = "Request for resetting password for {title}".format(title=reset_password_token.user.email), body=plain_message, from_email = "sender@example.com", to=[reset_password_token.user.email] ) msg.attach_alternative(html_message, "text/html") msg.send() # Helper function to generate a 12-digit booking ID def generate_booking_id(): return ''.join(random.choices(string.ascii_uppercase + string.digits, k=12)) # Custom validator to ensure the date is in the future (excluding today) def validate_future_date(value): if value

First of all you need to create backend classes in your models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.base_user import BaseUserManager
from django_rest_passwordreset.signals import reset_password_token_created
from django.dispatch import receiver
from django.urls import reverse
from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives
from django.utils.html import strip_tags
import random
import string
from datetime import datetime, timedelta
from django.contrib.auth.models import User
from django.conf import settings
from django.core.exceptions import ValidationError
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields ):
if not email:
raise ValueError('Email is a required field')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(email, password, **extra_fields)
class CustomUser(AbstractUser):
email = models.EmailField(max_length=200, unique=True)
birthday = models.DateField(null=True, blank=True)
username = models.CharField(max_length=200, null=True, blank=True)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
@receiver(reset_password_token_created)
def password_reset_token_created(reset_password_token, *args, **kwargs):
sitelink = "http://localhost:5173/"
token = "{}".format(reset_password_token.key)
full_link = str(sitelink)+str("password-reset/")+str(token)
print(token)
print(full_link)
context = {
'full_link': full_link,
'email_adress': reset_password_token.user.email
}
html_message = render_to_string("backend/email.html", context=context)
plain_message = strip_tags(html_message)
msg = EmailMultiAlternatives(
subject = "Request for resetting password for {title}".format(title=reset_password_token.user.email),
body=plain_message,
from_email = "sender@example.com",
to=[reset_password_token.user.email]
)
msg.attach_alternative(html_message, "text/html")
msg.send()
# Helper function to generate a 12-digit booking ID
def generate_booking_id():
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=12))
# Custom validator to ensure the date is in the future (excluding today)
def validate_future_date(value):
if value <= datetime.now().date():
raise ValidationError('The date must be in the future.')
class Booking(models.Model):
# Define the booking types
BOOKING_CHOICES = [
('booking', 'Booking'),
('installation', 'Installation'),
]
booking_id = models.CharField(max_length=12, unique=True, default=generate_booking_id)
booking_type = models.CharField(max_length=20, choices=BOOKING_CHOICES)
booking_date = models.DateField(validators=[validate_future_date])
# Use the custom user model via AUTH_USER_MODEL
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='bookings')
def __str__(self):
return f"Booking ID: {self.booking_id} - {self.booking_type} for {self.user.email}"
class Meta:
verbose_name = 'Booking'
verbose_name_plural = 'Bookings'
Then You need to migrate these changes.
Next serializers.py
from rest_framework import serializers
from .models import *
from django.contrib.auth import get_user_model
User = get_user_model()
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField()
def to_representation(self, instance):
ret = super().to_representation(instance)
ret.pop('password', None)
return ret
class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id','email','password')
extra_kwargs = { 'password': {'write_only':True}}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
return user
class BookingSerializer(serializers.ModelSerializer):
class Meta:
model = Booking
fields = ['booking_id', 'booking_type', 'booking_date', 'user']
# To ensure that the user is always the authenticated user, you can override the create method
def create(self, validated_data):
user = self.context['request'].user # Get the current authenticated user
validated_data['user'] = user
return super().create(validated_data)
and obviously views.py
from django.shortcuts import render
from rest_framework import viewsets, permissions, generics
from .serializers import *
from .models import *
from rest_framework.response import Response
from django.contrib.auth import get_user_model, authenticate
from knox.models import AuthToken
from rest_framework.permissions import IsAuthenticated
User = get_user_model()
class LoginViewset(viewsets.ViewSet):
permission_classes = [permissions.AllowAny]
serializer_class = LoginSerializer
def create(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
email = serializer.validated_data['email']
password = serializer.validated_data['password']
user = authenticate(request, email=email, password=password)
if user:
_, token = AuthToken.objects.create(user)
return Response(
{
"user": self.serializer_class(user).data,
"token": token
}
)
else:
return Response({"error":"Invalid credentials"}, status=401)
else:
return Response(serializer.errors,status=400)
class RegisterViewset(viewsets.ViewSet):
permission_classes = [permissions.AllowAny]
queryset = User.objects.all()
serializer_class = RegisterSerializer
def create(self,request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors,status=400)
class UserViewset(viewsets.ViewSet):
permission_classes = [permissions.IsAuthenticated]
queryset = User.objects.all()
serializer_class = RegisterSerializer
def list(self,request):
queryset = User.objects.all()
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data)
class BookingViewSet(viewsets.ModelViewSet):
queryset = Booking.objects.all()
serializer_class = BookingSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
# Only show bookings for the authenticated user
return Booking.objects.filter(user=self.request.user)
def perform_create(self, serializer):
# Ensure that the booking is created for the authenticated user
serializer.save(user=self.request.user)
Last but not least urls.py
from django.contrib import admin
from django.urls import path
from rest_framework.routers import DefaultRouter
from .views import *
router = DefaultRouter()
router.register('register', RegisterViewset, basename='register')
router.register('login', LoginViewset, basename='login')
router.register('users', UserViewset, basename='users')
# Register the new Booking ViewSet
router.register('bookings', BookingViewSet, basename='bookings')
urlpatterns = router.urls
Can also add admin functionality