Сравнение даты и времени в Django Framework
У меня есть приложение. Я хотел бы сравнивать дату и время, когда пользователь создает список заданий. Дата задания не должна быть раньше текущей даты, а время окончания не должно быть раньше времени начала, а если задание происходит ночью, например, начинается в 22:00 вечера и заканчивается в 7:00 утра следующего дня, как мне их сравнить? Я не уверен в логике, где я должен поместить эту функцию compare_time? В модели или в представлении?
Вот мой код:
class Job(models.Model):
pub_date=models.DateTimeField('Date published',auto_now_add=True)
updated_date = models.DateTimeField(auto_now_add=True,null=True, blank=True)
job_date=models.DateTimeField('Date')
start_time = models.TimeField()
finish_time = models.TimeField()
published = models.BooleanField(default=False)
details=models.CharField(max_length=200, blank=True, null=True)
user=models.ForeignKey(get_user_model(),on_delete=models.CASCADE,null=True,blank=True) # the user could be employer, admin, staff or nurse. And if nurse reserves the shift, this field will be the same as nurse field.
time_reserved = models.DateTimeField(auto_now_add=True,null=True)
def __str__(self):
return f'{self.pub_date}'
#view
def createJob(request):
user=request.user
employer=Employer.objects.all()
form = JobForm()
if request.method == 'POST':
#print('Printing POST:', request.POST)
form = JobForm(request.POST)
if form.is_valid():
#to do1, one employer could not create job for other employers.#
#to do 2. date can't be past time, finish time could not be earlier than start time
if request.user.is_employer:
employer=request.user
form.save()
messages.success(request, "The job has been created")
return redirect('/')
context = {'form':form}
return render(request, 'create_job.html', context)
#form
class JobForm(ModelForm):
class Meta:
model = Job
fields = '__all__'
widgets = {
'job_date': DateInput(),
'start_time':TimeInput(),
'finish_time':TimeInput(),
}
# Я пытался написать следующий код, но не знаю, куда его вставить.
current_year=datetime.date.today().year
current_datetime=datetime.datetime.now() #2022-11-07 09:12:12.473393
current_date=datetime.date.today() #2022-11-07
current_time=datetime.datetime.now().time() #07:35:38.047247
job_date=Job.objects.filter(job_date=job_date)
start_time = Job.objects.filter(start_time__gt=time)
finish_time = Job.objects.filter(finish_time__gt=time)
"""
1)When publishing a job vancancy, the job date could not be earlier than publish date. If the publish date and job date are the same, the start time should be no ealier than the current time.
2)The finish time should not be earlier than start time.
3)If it's night shift job, e.g. start at 22:00 and the next day 5:00 am , how to compare then?
"""
def compare_time(job_date,current_date,start_time, current_time,finish_time):
if job_date is not None and job_date < current_date:
return False
elif job_date = current_date:
if start_time is not None and start_time < current_time:
return False
else:
if finish_time is not None and finish_time < start_time + datetime.timedelta(minutes = 300?)
return False
return True
Я пытаюсь понять, как работает функция сравнения времени в Django, особенно когда она охватывает разные даты.
Из того, что вы объяснили, я думаю, что это должно происходить на этапе валидации формы. Например, так:
from django.core.exceptions import ValidationError
class JobForm(ModelForm):
class Meta:
model = Job
fields = '__all__'
widgets = {
'job_date': DateInput(),
'start_time':TimeInput(),
'finish_time':TimeInput(),
}
def clean(self):
cleaned_data = super().clean()
job_date = cleaned_data['job_date']
start_time = cleaned_data['start_time']
finish_time = cleaned_data['finish_time']
current_date = datetime.datetime.now()
if job_date is not None and job_date < current_date:
return ValidationError("<Your error here>")
elif job_date = current_date:
if start_time is not None and start_time < current_time:
return ValidationError("<Your error here>")
else:
if finish_time is not None and finish_time < start_time + datetime.timedelta(minutes = 300?)
return ValidationError("<Your error here>")
Здесь вы можете отправить ошибки обратно пользователю, чтобы он мог ввести правильную информацию. Замените "<Your error here"
сообщениями об ошибках, относящимися к конкретному сбою условий.
Основываясь на ответе Льюиса, я добился дальнейшего прогресса. Ошибка валидации все еще не появилась.
import datetime
from django.utils import timezone
from datetime import date
import pytz
class JobForm(ModelForm):
class Meta:
model = Job
fields = '__all__'
widgets = {
'job_date': DateInput(),
'start_time':TimeInput(),
'finish_time':TimeInput(),
}
def clean(self):
cleaned_data = super().clean()
job_date = cleaned_data['job_date']
print("job_date is: ",job_date)
start_time = cleaned_data['start_time']
finish_time = cleaned_data['finish_time']
print(finish_time)
current_date =datetime.now(tz=pytz.timezone('UTC'))
print("current_date is:", current_date)
if job_date is not None and job_date < current_date:
raise forms.ValidationError("job_date could not be noun and job_date should not be ealier than current_date")
elif job_date == current_date:
if start_time is not None and start_time < current_time:
raise forms.ValidationError("start_time should be filled and start_time can not be ealier than current_time")
else:
if finish_time is not None and finish_time < start_time + datetime.timedelta(minutes = 300):
raise forms.ValidationError("finish_time can not be earlier than start time")
Я изменил return на raise, иначе получаю ошибку 'ValidationError' object has no attribute 'get'