Django引发forms.ValidationError不起作用 [英] Django raise forms.ValidationError not working

查看:195
本文介绍了Django引发forms.ValidationError不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将验证器添加到django模型表单中,这样,如果选择了特定值,则应在表单中输入其他字段(如果未输入该字段,则会显示验证错误)

I am trying to add a validator to django model form such that if specific value is selected then other field in the form should be entered if not entered it should give a validation error

如果用户从activity_name下拉列表中选择项目支持活动",则格式如下:

in the below form if the user selects "Project Support Activities" from the activity_name drop down then the project id field should be mandatory

Django表单

class ActivityTrackerModelForm(forms.ModelForm):
    date = forms.DateField(label='', widget=forms.DateInput(attrs={
                           "placeholder": "Select Date", 'id': 'datepicker', 'class': 'form-control w-100', 'autocomplete': 'off'}))
    activity_name = forms.ModelChoiceField(queryset=activity.objects.all().order_by(
        'activity_name'), label='', empty_label="Select Activity", widget=forms.Select(attrs={'class': 'form-control w-100'}))
    system_name = forms.ModelChoiceField(queryset=system.objects.all().order_by('system_name'), label='', empty_label="Select System", widget=forms.Select(attrs={
'class': 'form-control w-100'}))
    client_name = forms.ModelChoiceField(queryset=client.objects.all().order_by(
        'client_name'), label='',  empty_label="Select Client", widget=forms.Select(attrs={
'class': 'form-control w-100'}))
    hour_choice = [('', 'Choose Hours'), (0, 0), (1, 1), (2, 2),(3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8)]
    hours = forms.ChoiceField(label='', choices=hour_choice, widget=forms.Select(
        attrs={'class': 'form-control w-100'}))
    min_choice = [('', 'Choose Mins'), (0, 0), (15, 15), (30, 30), (45, 45)]
    mins = forms.ChoiceField(label='', choices=min_choice, widget=forms.Select(attrs={'class': 'form-control w-100'}))
    no_of_records = forms.IntegerField(label='', required=False, widget=forms.NumberInput(
        attrs={"placeholder": "Enter no. of Records", 'class': 'form-control w-100', 'autocomplete': 'off'}))
    project_id = forms.CharField(label='', required=False, widget=forms.TextInput(
        attrs={"placeholder": "Project ID", 'class': 'form-control w-100'}))
    user_comments = forms.CharField(
        label='',
        required=False,
        widget=forms.Textarea(
            attrs={
                "placeholder": "Enter Your Comments Here...",
                'rows': 6,
                'class': 'form-control w-100',
                'autocomplete': 'off'
            }
        )
    )

    class Meta:
        model = activity_tracker
        fields = ['date', 'activity_name', 'system_name', 'client_name',
                  'hours', 'mins', 'no_of_records', 'project_id', 'user_comments']


    def clean(self):
        cleaned_data = super(ActivityTrackerModelForm, self).clean()
        activity = cleaned_data.get('activity_name')
        project_1 = cleaned_data.get('project_id')
        if re.search("^Project.*Activities$", str(activity)) or project_1 is None:
            print('pass') # prints to console this is working
            raise forms.ValidationError('Please Add in Project ID')#raise form error this is not working

查看:


def MyTask(request):
    if request.method == 'POST':
        form = ActivityTrackerModelForm(request.POST or None)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user_name = request.user
            obj.approver = tascaty_user.objects.get(
                username=request.user).approver
            if request.user.is_team_lead:
                obj.status = activity_status.objects.get(pk=3)
            obj.save()
        return redirect('mytask')

    queryset1_PA = activity_tracker.objects.filter(
        user_name=request.user).filter(status__in=[1, 2, 4]).order_by('-id')
    queryset1_AP = activity_tracker.objects.filter(
        user_name=request.user).filter(status=3).order_by('-date')
    paginator_RA = Paginator(queryset1_AP, 10)
    paginator_PA = Paginator(queryset1_PA, 10)
    page = request.GET.get('page')

    context = {
        'title': 'TasCaty|My Task',
        'activity_form': ActivityTrackerModelForm(),
        'post_page_RA': paginator_RA.get_page(page),
        'post_page_PA': paginator_PA.get_page(page),
    }
    return render(request, "tascaty/mytask.html", context)

推荐答案

引发错误可以正常工作.但是,即使表单无效,您也始终会重定向,因此该错误将永远不会显示.

Raising the error is working fine. But you always redirect away, even if the form is not valid, so the error will never be displayed.

仅当is_valid为True时才应重定向,否则应重新显示该表单.这意味着将无效的表单传递回上下文-因此,仅当方法不是POST时,才应创建一个新表单.所以:

You should only redirect when is_valid is True, otherwise you should redisplay the form. That means passing the invalid form back to the context - so you should only create a new one when method is not POST. So:

if request.method == 'POST':
    form = ActivityTrackerModelForm(request.POST or None)
    if form.is_valid():
        ...
        obj.save()
        return redirect('mytask')   # indented here
else:
    ActivityTrackerModelForm()      # added this block, note it's aligned with the first if

...

context = {
    ...
    'activity_form': form,         # pass the existing form here
    ...
}
return render(request, "tascaty/mytask.html", context)

这篇关于Django引发forms.ValidationError不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆