I am new to python programming and I need to write a python code for giving access controls to the users based on their roles like doctors, nurses, staffs, managers, etc. using enum implementation. I need this for a hospital management system. I have created an app called core and written the following codes:
in views.py :
from .serializers import UserCreateSerializer, UserSerializer
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
from rest_framework import status
@api_view(
['POST']
)
def login(request):
if request.method == 'POST':
serializer = UserSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user=authenticate(
username=serializer.validated_data['username'],
password=serializer.validated_data['password'],
role=serializer.validated_data['role'],
)
if user:
token, _ = Token.objects.get_or_create(user=user)
return Response(
{
'token': token.key,
'user' : user.username,
}
)
return Response(
{
'error': 'Invalid credentials',
},
status = status.HTTP_401_UNAUTHORIZED,
)
@api_view(
['POST']
)
def register(request):
serializer = UserCreateSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(
{
'details': 'User created successfully',
}
)
in serializers.py :
from django.forms import ValidationError
from rest_framework import serializers
from django.contrib.auth import get_user_model
User = get_user_model()
class UserSerializer(serializers.Serializer):
username = serializers.CharField(max_length=255)
password = serializers.CharField(max_length=255)
role = serializers.CharField(max_length=50)
class UserCreateSerializer(serializers.Serializer):
username = serializers.CharField(max_length=255)
password = serializers.CharField(max_length=255)
confirm_password = serializers.CharField(max_length=255)
role = serializers.CharField(max_length=50)
def validate(self, attrs):
if attrs['password'] != attrs['confirm_password']:
raise ValidationError({
'confirm_password': 'Passwords do not match',
})
return attrs
def create(self, validated_data):
validated_data.pop('confirm_password')
return User.objects.create_user(**validated_data)`
Now my question is : Where do I write the code using enum?? If anyone can help me out with this, please feel free to help
I’ve having difficult writing the code using enumyour text
New contributor