please i have an issue , i want to check the difference between two dates from my form, then allows to create the object using my class based_View if the date is bigger than an other attribute, if not render it to an other page without inserting nothing in the database.here is my
# 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',
]
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)
I'm not solving your specific problem I just deliver the idea or what can you do to jump over your problem
I found this solution to check the delay ! i was thinking class basedView are always the best
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.