【问题标题】:Django raise forms.ValidationError not workingDjango提出forms.ValidationError不工作
【发布时间】:2019-09-03 03:22:48
【问题描述】:

我正在尝试向 django 模型表单添加一个验证器,这样如果选择了特定值,则应输入表单中的其他字段,如果未输入,则应给出验证错误

在下面的表格中,如果用户从活动名称下拉列表中选择“项目支持活动”,则项目 ID 字段应为必填项

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)

【问题讨论】:

    标签: django django-forms django-validation


    【解决方案1】:

    如@Daniel Roseman 所述更改了我的视图并更改了表单验证器

    查看

    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)
    

    表单验证器

        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)) and project_1 == "":
                self.add_error('project_id', "Please Add Project ID")
            return cleaned_data
    

    【讨论】:

      【解决方案2】:

      引发错误可以正常工作。但是即使表单无效,您总是会重定向,因此永远不会显示错误。

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

      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)
      

      【讨论】:

      • 现在表单没有被保存,这是预期的,但它没有在表单上显示验证错误。
      • 您如何显示这些错误?显示模板。
      • 发现我的验证器也有一些问题,因为 project_id 是一个 CharField 它无法使用 Null 进行验证,因为没有输入更改了验证器,如下所示它可以工作 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)) and project_1 == "": self.add_error('project_id', "Please Add Project ID") return cleaned_data
      猜你喜欢
      • 1970-01-01
      • 2020-02-11
      • 2012-06-07
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      相关资源
      最近更新 更多