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

问题描述 投票:0回答:1

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

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

我怎么能以这样的方式使用这个干净的方法,它将检查保存视图的此验证,但不会检查编辑视图。

编辑视图:

@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'}
django django-forms django-views
1个回答
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方法中检查实例

© www.soinside.com 2019 - 2024. All rights reserved.