Django错误消息

时间:2018-01-01 05:51:53

标签: django django-forms django-templates django-views

我有一个案子。提交表单后,必须进行查询。如果查询存在,则必须发送错误消息。如果查询不存在,则必须保存数据。我写了如下的视图,它的工作原理。但唯一的问题是错误消息就像成功消息一样。我已经尝试在验证表单之前放置​​查询,但是,它仍然是相同的。我怎么能解决这个问题?

def permissionFormView(request):
    r_form = forms.RoleForm()
    p_form = forms.PermissionForm()
    if request.method == 'POST':
        p_form = forms.PermissionForm(request.POST)
        if p_form.is_valid():
            role = p_form.cleaned_data['role_name']
            feature = p_form.cleaned_data['feature']
            if models.PermissionModel.objects.filter(role_name=role,feature=feature).exists():
                messages.error(request, 'Permission exists.')
            else:
                p_form.save()
                messages.success(request, 'Permission added successfully.')
                return render(request, 'company_profile.html', {'r_form': r_form, 'p_form': p_form})
    return render(request,'company_profile.html',{'r_form':r_form,'p_form':p_form})

客户端表单代码:

<form action="{% url 'permission_form' %}" novalidate method="POST">
    {% csrf_token %}
    <div class="row">
        <div class="col">
        <label for="r_name"><small><strong>{{ p_form.role_name.label }}</strong></small></label>
        <p>{{p_form.role_name}}</p>
        {% for error in p_form.role_name.errors %}
        <p><small class="alert-danger">{{ error }}</small></p>
        {% endfor %}
        </div>
        <div class="col">
        <label for="r_feature"><small><strong>{{ p_form.feature.label }}</strong></small></label>
        <p>{{p_form.feature}}</p>
        {% for error in p_form.feature.errors %}
        <p><small class="alert-danger">{{ error }}</small></p>
        {% endfor %}
        </div>
        <div class="col">
        <label for="permission"><small><strong>{{ p_form.permission.label }}</strong></small></label>
        <p><input type="checkbox" class="form-control" id="permission" name="permission"
        {% if r_form.role_name.value is not None %}
        value="{{ p_form.permission.value }}"
        {% endif %}
        ></p>
        {% for error in p_form.permission.errors %}
        <p><small class="alert-danger">{{ error }}</small></p>
        {% endfor %}
        </div>
    </div>
    <input class='btn btn-primary btn-sm' type='submit' value='Save'>
</form>

各种错误讯息的图片: error screenshots 我想要的只是显示Permission存在的消息,如红色的错误。

1 个答案:

答案 0 :(得分:1)

您应该将其放入表单的clean方法中,以便它与所有其他表单验证逻辑一起运行。

class PermissionForm(forms.ModelForm):
    ...

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