django:基于ModelForm字段创建HTML警报?

时间:2018-09-07 09:26:47

标签: python django

我正在研究user-leaves-managing-system

models.py

CHOICES = (('Earned Leave','Earned Leave'),('Casual Leave','Casual Leave'),('Sick Leave','Sick Leave'),('Paid Leave','Paid Leave'))
class User(models.Model)    

     type_of_leave = models.CharField(max_length = 15, choices = CHOICES)
     from_date = models.DateField()
     to_date = models.DateField()

forms.py

class RequestForm(ModelForm):
    class Meta:
        fields = ( "type_of_leave", "from_date", "to_date")
        model = Leave

        widgets =  {

            'from_date' : DateInput(attrs={'class': 'datepicker'}),
            'to_date' : DateInput(attrs={'class': 'datepicker'}),
                   }

views.py

def leaveRequest(request):

    if request.method == "POST":
        form = LeaveRequestForm(request.POST)
        if form.is_valid():
            leave = form.save(commit = False)
            leave.user = request.user
            form.save()
        return HttpResponseRedirect("/thanks/")
    else:
        ...

用户申请请假,对于每种请假,我已经通过10 days在数据库中给定了默认值admin。因此,如果用户申请的叶子多于他拥有的叶子,则我想生成一条带有消息的HTML警报,即,如果叶子被充分利用或becomes = 0

所以我很困惑在哪里以及如何定义它。

我已将其放在RequestForm类下的forms.py中,但没有用。

def clean(self):

        cleaned_data = super().clean()
        to_date = cleaned_data.get("to_date")
        from_date = cleaned_data.get("from_date")

        if from_date < to_date:
            pass
        else:
            raise forms.ValidationError(
                "From Date should be lesser than To Date "
            )

1 个答案:

答案 0 :(得分:0)

Take a look.

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject:
            # Only do something if both fields are valid so far.
            if "help" not in subject:
                raise forms.ValidationError(
                    "Did not send for 'help' in the subject despite "
                    "CC'ing yourself."
                )