我有一个可能会重复多次的问题,但我根本听不懂。
我有一个视图,在该视图中,用户从选择下拉列表中选择一个值,然后输入要处理的整数。
如果用户输入“数量”中的5张,而所选选项中还剩下2张叶子,我希望在提交表格后或在该页面上收到通知,通知您您没有太多的叶子可以申请
view.py
def request_leave(request, emp_id): # Requesting leave
employee = Employee.objects.get(employee_name=emp_id)
if employee.allowed == True:
form = Leave_Form(request.POST, employee=employee)
if form.is_valid():
abc = form.save(commit=False)
abc.employee_leaves = request.user.employee
abc.save()
form = Leave_Form
context = {'employee': employee, 'form': form}
# context = {'form': form}
return render(request, 'projectfiles/reqleave.html', context)
else:
return render(request, "projectfiles/banned.html")
models.py
class Employee(models.Model):
allowed = models.BooleanField(default=True)
employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
employee_designation = models.CharField(max_length = 5)
employee_department = models.CharField(max_length = 5)
Annual_leave = models.PositiveSmallIntegerField(default=5)
Sick_leave = models.PositiveSmallIntegerField(default=5)
Casual_leave = models.PositiveSmallIntegerField(default=5)
Half_pay = models.PositiveSmallIntegerField(default=5)
Emergency_leave = models.PositiveSmallIntegerField(default=5)
forms.py
to_date = forms.DateField(
widget=forms.DateInput(format=('%m/%d/%y'),
attrs={'class': 'form-control',
'placeholder': ' Month/Date/Year'}))
from_date = forms.DateField(
widget=forms.DateInput(format=('%m/%d/%y'),
attrs={'class': 'form-control',
'placeholder':' Month/Date/Year'}))
def __init__(self, *args, **kwargs):
employee = kwargs.pop('employee', None)
if employee:
self.employee = employee
super(Leave_Form, self).__init__(*args, **kwargs)
def clean(self):
cleaned_data = super(Leave_Form, self).clean()
leave_qty = cleaned_data.get('leave_qty')
leave_type = cleaned_data.get('leave_Type')
#If form still submits, then please put a debugger here
if leave_type == "Annual_Leave": # Checking Leave Type and comparing leave_qty against that type of leave
if self.employee.Annual_Leave:
forms.ValidationError("You don't have enough Annual Leave")
if leave_type == "Sick_leave":
if self.employee.Sick_leave:
forms.ValidationError("You don't have enough Sick Leave")
# similarly add other else if logic for other types of leaves
return leave_qty
class Meta:
model = Leave
fields = ['leave_Type', 'description',
'from_date', 'to_date', 'leave_qty']
exclude = ['employee_leaves', 'submit_date', 'leave_status']
leave_type_choice = (
("Annual_leave", "Annual leave"),
("Sick_leave", "Sick leave"),
("Casual_leave", "Casual leave"),
("Emergency_leave", "Emergency leave"),
("Half_pay","Half Pay")
)
widgets = {
'leave_Type': forms.Select(choices = leave_type_choice, attrs={'class': 'form-control'}),
'description': forms.Textarea(
attrs={'class': 'form-control','placeholder': 'Enter description here', 'rows': 3, 'cols': 21})}
urls.py
url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
name='Leave-Page'), # leave request
req.html
{% include 'projectfiles/base.html' %}
<title>Request Leave</title>
{% block asd %}
<br><br>
<div class="container" align="center">
<form method="POST" style="width:190px">
{% csrf_token %}
{{form.as_p}}
<button class="btn btn-success my-2 my-sm-0" type="submit">Apply</button>
</form></div>
{% endblock %}
错误
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py" in request_leave
47. if form.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
183. return self.is_bound and not self.errors
File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
175. self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
386. self._post_clean()
File "C:\Python27\lib\site-packages\django\forms\models.py" in _post_clean
394. exclude = self._get_validation_exclusions()
File "C:\Python27\lib\site-packages\django\forms\models.py" in _get_validation_exclusions
354. field_value = self.cleaned_data.get(field)
Exception Type: AttributeError at /request/2
Exception Value: 'int' object has no attribute 'get'
日志
[31/May/2019 12:51:07] "POST /request/2 HTTP/1.1" 200 7906
========Annual_leave
________45
[31/May/2019 12:53:32] "POST /request/2 HTTP/1.1" 200 7906
=======================
========Sick_leave
________52
[31/May/2019 12:54:34] "POST /request/2 HTTP/1.1" 200 7906
更新
to_date = forms.DateField(
widget=forms.DateInput(format=('%m/%d/%y'),
attrs={'class': 'form-control',
'placeholder': ' Month/Date/Year'}))
from_date = forms.DateField(
widget=forms.DateInput(format=('%m/%d/%y'),
attrs={'class': 'form-control',
'placeholder':' Month/Date/Year'}))
def __init__(self, *args, **kwargs):
employee = kwargs.pop('employee', None)
if employee:
self.employee = employee
super(Leave_Form, self).__init__(*args, **kwargs)
def clean(self):
cleaned_data = super(Leave_Form, self).clean()
leave_qty = cleaned_data.get('leave_qty')
leave_type = cleaned_data.get('leave_Type')
if leave_type < leave_qty:
print "======== " + str(leave_type)
print "________ " + str(leave_qty)
raise forms.ValidationError("You don't have enough Annual Leave")
return cleaned_data
我希望在提交表单后或在页面上出现错误,我的老年人建议使用JS,但我对JS不熟悉。
答案 0 :(得分:0)
也许您可以在ModelForm
中使用clean
方法。您可以这样做:
要访问Employee
的当前请假计数,我们需要将Employee
对象传递给表单。因此,我们还必须重写Form的__init__
方法:
class Leave_Form(forms.ModelForm):
def __init__(self, *args, **kwargs):
employee = kwargs.pop('employee', None)
if employee:
self.employee = employee
super(Leave_Form, self).__init__(*args, **kwargs)
...
def clean(self):
cleaned_data = super(Leave_Form, self).clean()
leave_qty = cleaned_data.get('leave_qty')
leave_type = cleaned_data.get('leave_Type')
#If form still submits, then please put a debugger here
if leave_type == "Annual_leave": # Checking Leave Type and comparing leave_qty against that type of leave
if self.employee.Annual_leave < leave_qty:
raise forms.ValidationError("You don't have enough Annual Leave")
if leave_type == "Sick_leave":
if self.employee.Sick_leave < leave_qty:
raise forms.ValidationError("You don't have enough Sick Leave")
# similarly add other else if logic for other types of leaves
return cleaned_data
现在,我们可以像这样在request_leave
视图中使用此表单(我们将在表单中将 employee 对象作为关键字参数传递)
@login_required(login_url='LoginPage')
def request_leave(request, emp_id): # Requesting leave
employee = Employee.objects.get(employee_name=emp_id)
if employee.allowed == True:
form = Leave_Form(request.POST,employee=employee)
# rest of the code
最后,还要更新模板以显示错误(documentation
):
{% if form.non_field_errors %}
{% for err in form.non_field_errors %}
<p>{{ err }}</p>
{% endfor %}
{% endif %}