from django.shortcuts import render, get_object_or_404
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from .serializers import *
from .models import *
from rest_framework.permissions import IsAuthenticated
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def getStudent(request):
# Retrieve the current school year
current_school_year = get_object_or_404(SchoolYear, is_current=True)
code
# Filter students by user and current school year
students = Student.objects.filter(user=request.user, school_year=current_school_year).order_by("id")
serializer_student = StudentSerializer(students, many=True)
return Response({"Students": serializer_student.data})
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def getRentBook(request):
# Retrieve the current school year
current_school_year = get_object_or_404(SchoolYear, is_current=True)
code
# Filter RentBooks by user and current school year
rented_books = RentBook.objects.filter(user=request.user, school_year=current_school_year).order_by("id")
serializer_rent = RentSerializer(rented_books, many=True)
return Response({"Rented": serializer_rent.data})
# in case the user want make update, is not the user who is authentificated now.
if archive.user != request.user:
return Response(
{"Error": "Sorry, you can't update this archive model!"},
status=status.Http_403_FORBIDEN,
)
archive.first_name = request.data["first_name"]
archive.last_name = request.data["last_name"]
archive.birth_date = request.data["birth_date"]
archive.birth_place = request.data["birth_place"]
archive.class_name = request.data["class_name"]
archive.document_name = request.data["document_name"]
archive.save()
serializer = ArchiveSerializer(archive, many=False)
return Response({"Archive": serializer.data})
# in case the user want make update, is not the user who is authentificated now.
if archive.user != request.user:
return Response(
{"Error": "Sorry, you can't delete this archive model!"},
status=status.Http_403_FORBIDEN,
)
archive.delete()
return Response(
{"details": "Delete Archive model Successfully!!"}, status=status.HTTP_200_OK
)
@api_view(["POST"])
@permission_classes([IsAuthenticated])
def libraryCard(request):
data = request.data
serializer = LibraryCardSerializer(data=data)
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def getLibraryCard(request):
# Retrieve the current school year
current_school_year = get_object_or_404(SchoolYear, is_current=True)
code
# Assuming LibraryCard is linked to Student which is linked to SchoolYear
library_cards = LibraryCard.objects.filter(user=request.user, school_year=current_school_year).order_by("id")
serializer_card = LibraryCardSerializer(library_cards, many=True)
return Response({"LibraryCards": serializer_card.data})
if card.user != request.user:
return Response(
{"Error": "Sorry you can't make a delete operation, you are not authentificated"},
status=status.HTTP_403_FORBIDDEN
)
card.delete()
return Response(
{"Details": "A Library Card has been deleted succesfully"},
status=status.HTTP_200_OK
)
delete all library cards
@api_view(["delete"])
@permission_classes([IsAuthenticated])
def deleteAllLibraryCard(request):
try:
LibraryCard.objects.all().delete()
return Response(
{"Response": "All library Cards have been deleted"},
status=status.HTTP_200_OK
)
except Exception as e:
return Response({"Error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
i want when i add book student or rentbook it should automatic add to it the current school year , this my models for refrence from django.db import models
from django.contrib.auth.models import User
class StatusChoice(models.TextChoices):
RENTED = "rented"
AVAILABLE = "available"
LOST = "lost"
class SchoolYear(models.Model):
year = models.CharField(max_length=9, unique=True) # e.g., "2023/2024"
is_current = models.BooleanField(default=False)
code
def save(self, *args, **kwargs):
if self.is_current:
# If this school year is marked as current, unset others
SchoolYear.objects.filter(is_current=True).update(is_current=False)
super(SchoolYear, self).save(*args, **kwargs)
def __str__(self):
return self.year
To automatically assign the current school year when adding a Book, Student, or RentBook, you need to modify your view functions to fetch the current SchoolYear instance and associate it with the newly created objects. This ensures that the school_year field is set based on the current context rather than relying on the client to provide it.
Below are the steps and updated code snippets to achieve this:
Fetch the Current School Year
Create a utility function to fetch the current SchoolYear. This ensures consistency and reduces repetition across different view functions.
python
# utils.py (Create this file if it doesn't exist)
from django.shortcuts import get_object_or_404
from .models import SchoolYear
def get_current_school_year():
return get_object_or_404(SchoolYear, is_current=True)
Update the add_student View
Instead of requiring the client to provide school_year, fetch the current school year automatically.
python
# views.py
from .utils import get_current_school_year
@api_view(["POST"])
@permission_classes([IsAuthenticated])
def add_student(request):
data = request.data.copy() # Make a mutable copy of the request data
current_school_year = get_current_school_year()
serializer = StudentSerializer(data=data)
if serializer.is_valid():
new_student = Student.objects.create(
**data,
user=request.user,
school_year=current_school_year
)
result = StudentSerializer(new_student, many=False)
return Response({"New_Student": result.data}, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Update the rentBook View
Similarly, fetch the current school year automatically when creating a RentBook instance.
If your Book model does have a school_year field (it wasn't present in the models you provided), you can similarly assign the current school year automatically. Otherwise, you can skip this step.
Note: If the Book model does not have a school_year field, you can ignore this step or consider adding the field if it's logically required for your application.
Update Other Relevant Views
Ensure that any other views that create instances requiring a school_year also fetch and assign the current school year automatically. For example, libraryCard, add_archive, etc.
No Current School Year: Ensure that there is always a SchoolYear marked as current. You can add validations or administrative actions to set a current school year.
Multiple Current School Years: Although your SchoolYear model's save method should prevent multiple current years, you can add additional checks if necessary.
Ensure Consistency in Serializer Validation
Since you’re removing the requirement for clients to provide school_year, ensure that your serializers are updated accordingly. If school_year was a required field in your serializers, you might need to set it as read-only or handle it differently.
Example:
python
# serializers.py
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ['id', 'first_name', 'last_name', 'birth_date', 'birth_place', 'class_num']
# Remove 'school_year' if it was included and make it read-only or excluded
def create(self, validated_data):
user = self.context['request'].user
current_school_year = get_current_school_year()
return Student.objects.create(user=user, school_year=current_school_year, **validated_data)
Note: Adjust your serializers as needed to align with these changes.
Final Updated Views
Here is the complete updated views.py with the necessary changes:
python
Ensure SchoolYear Exists and Is Set as Current
Before performing operations that depend on the current school year, ensure that a SchoolYear instance is marked as current. You can manage this through the Django admin interface or create an API endpoint to set a school year as current.
Example: Setting a School Year as Current
python
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def set_current_school_year(request, pk):
school_year = get_object_or_404(SchoolYear, pk=pk)
school_year.is_current = True
school_year.save()
return Response({"message": f"School year {school_year.year} is now current."}, status=status.HTTP_200_OK)
Remember: Only one SchoolYear should be marked as current at any given time. The save method in your SchoolYear model already handles this by unsetting other instances when a new one is set as current.
Testing
After making these changes, thoroughly test each endpoint to ensure that:
Objects are created with the correct school_year.
Unauthorized access is properly handled.
Edge cases (e.g., no current school year) are managed gracefully.
By implementing these changes, you ensure that all relevant objects automatically associate with the current school year, enhancing data consistency and reducing the likelihood of client-side errors.