Appointment is being registered although I am providing before time in start time for appointment.
models.py
class Appointment(models.Model):
status = models.CharField(
choices=APPOINMENT_STATUSES,
max_length=20,
default=SCHEDULED,
help_text="",
)
full_name = models.CharField(max_length=100)
gender = models.CharField(choices=GENDER_TYPE, max_length=10, default=MALE)
email = models.EmailField()
phone_no = models.CharField(max_length=10, validators=[validate_phone_no])
start = models.DateTimeField(max_length=50, help_text="Appointment start Date & Time")
end = models.DateTimeField(max_length=50, help_text="Appointment End Date & Time")
doctor = models.ForeignKey(Doctor, on_delete=models.PROTECT, blank=True, null=True)
message = models.TextField()
def __str__(self):
return self.full_name
serializers.py
class AppointmentCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Appointment
fields = '__all__'
def create(self, validated_data):
return super().create(validated_data)
def validate(self, attrs):
# check appointment start and end time
if attrs["start"] < timezone.now():
raise serializers.ValidationError("Appointment date cannot be in the past")
if attrs["start"] >= attrs["end"]:
raise serializers.ValidationError(
f"Appointment end date/time should be after than start/date time."
)
return super().validate(attrs)
Description:
This is my appointment model and serializer for that. Why my validation is not working.
I want, the user wont be able to create appointment if the start date and time is before current date and time. ----------------> But Appointment is getting registered, if User is entering today date but before time .
What's Wrong with this? and What can be better solution for this problem?
CodePudding user response:
I think that your validation is working correctly. The reason why you don't see it probably is timezone. Let's say you have timezone = "UTC" in settings and now is 18:00 in your local time and 11:00 according to UTC (the difference is 7 hours). If you send "start" in request without timezone indication for example 2022-12-27T17:00 so the server will think that it's 17:00 according to UTC and so 17:00 is later then 11:00.
try to send start date with indication of amounts of hours from utc and see if it works. In my example it would be 2022-12-27T17:00:00 07:00 and so server should convert it to 10:00 in utc (or other timezone you are using in settings) what is earlier then 11:00