Django ограничения для конечных пользователей - PullRequest
0 голосов
/ 31 мая 2019

У меня есть вопрос, который может повторяться несколько раз, но я вообще не могу понять ни одного из них.

У меня есть вид, в котором пользователь выбирает значение из выпадающего спискаи вводит целое число для обработки.

Если пользователь вводит, скажем, 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'

log

[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

Annual Leave

обновление

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.

1 Ответ

0 голосов
/ 31 мая 2019

Возможно, вы можете использовать метод clean в ModelForm. Вы можете сделать это так:

Для доступа к текущему количеству отпусков 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,<b>employee=employee</b>)
        # rest of the code

Наконец, обновите шаблон, чтобы отображались ошибки (documentation):

{% if form.non_field_errors %}

    {% for err in form.non_field_errors %}
      <p>{{ err }}</p>
    {% endfor %}

{% endif %}
...