基于条件的Django clean方法(两个视图中使用的一种形式)

时间:2018-01-03 07:02:58

标签: django django-forms django-views

我有一个用于两个视图的表单。一个保存,一个编辑/更新。我用它来检查独特的条件。 (表格有三个字段。三个字母的组合只能来一次。)

现在,当我使用相同的表单时,它会检查两个视图的这种情况 - 保存和编辑。这导致在编辑视图中抛出错误的表单,表明该值已存在。

我怎样才能使用这种干净的方法,它会检查保存视图的验证,但不会检查编辑视图。

修改视图:

@login_required
def permissionEditView(request, pk):
    data = models.PermissionModel.objects.get(pk=pk)
    p_form = forms.PermissionForm(instance=data)
    if request.method == 'POST':
        p_form = forms.PermissionForm(request.POST, instance=data)
        if p_form.is_valid():
            p_form.save()
            messages.success(request, 'Permission updated successfully.')
            return redirect(companyProfileView)
    return render(request, 'company_profile.html', {'p_form': p_form})

保存视图:

def permissionFormView(request):
    p_form = forms.PermissionForm()
    if request.method == 'POST':
        p_form = forms.PermissionForm(request.POST)
        if p_form.is_valid():
            p_form.save()
            messages.success(request, 'Permission added successfully.')
            return redirect(companyProfileView)
    return render(request, 'company_profile.html', {'p_form': p_form})

用干净的方法表格:

class PermissionForm(forms.ModelForm):
    class Meta:
        model = models.PermissionModel
        fields = '__all__'

    def clean(self):
        role = self.cleaned_data.get('role_name')
        feature = self.cleaned_data.get('feature')
        if models.PermissionModel.objects.filter(role_name=role, feature=feature).exists():
            raise forms.ValidationError('Permission exists.')

    def __init__(self, *args, **kwargs):
        super(PermissionForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs = {'class': 'form-control form-control-sm'}

1 个答案:

答案 0 :(得分:2)

def clean(self):
        role = self.cleaned_data.get('role_name')
        feature = self.cleaned_data.get('feature')
        if not form.instance:
            if models.PermissionModel.objects.filter(role_name=role, feature=feature).exists():
                raise forms.ValidationError('Permission exists.')

您可以在clean方法中检查实例