请问我有问题,我想检查我的表单中两个日期之间的区别,然后允许使用我的类based_View创建对象,如果日期大于其他属性,如果没有将其呈现到其他页面没有在数据库中插入任何内容。我的
# view
class AddVacation(LoginRequiredMixin, CreateView):
form_class = VacationCreateForm
template_name = 'vacation.html'
login_url = 'login'
def form_valid(self, form):
instance = form.save(commit=False)
instance.employee = self.request.user
return super(AddVacation, self).form_valid(form)
# form:
class VacationCreateForm(forms.ModelForm):
class Meta:
model = VacationModel
fields = [
'type',
'startDate',
'enddate',
]
答案 0 :(得分:0)
class VacationCreateForm(forms.ModelForm):
class Meta:
model = VacationModel
fields = [
'type',
'startDate',
'enddate',
]
def clean(self):
start_date = self.cleaned_data['start_date']
end_date = self.cleaned_data['end_date']
from dateutils import parse
start_date = parse(start_date)
end_date = parse(end_date)
# make your calculations
raise forms.ValidationError("message.")
class AddVacation(LoginRequiredMixin, CreateView):
form_class = VacationCreateForm
template_name = 'vavcation.html'
login_url = 'login'
def post(self, request, *args, **kwargs):
"""
Handles POST requests, instantiating a form instance with the passed
POST variables and then checked for validity.
"""
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
redirect(to_ur_another_view)
我没有解决您的具体问题我只是提出了这个想法,或者您可以做些什么来跳过您的问题
答案 1 :(得分:0)
我发现这个解决方案来检查延迟!我认为基于类的View总是最好的
def create_vacation(request):
form = VacationCreateForm(request.POST or None)
error_message = ""
if form.is_valid():
dateD = request.POST.get("Startdate")
dateF = request.POST.get("Enddate")
fmt = '%Y-%m-%d'
dS = datetime.strptime(str(dateS), fmt)
dE = datetime.strptime(str(dateE), fmt)
dateDiff = (dE - dS).days
q = Employee.objects.get(id__iexact=request.user.id)
if dateDiff < q.VacationDays:
instance = form.save(commit=False)
instance.employee = request.user
instance.save()
else:
error_message = "Impossible check Your demand"
context = {
"form": form,
"error_message": error_message,
}
return render(request, 'vacation.html', context)