django在自己的错误页面上显示验证错误

时间:2018-06-14 05:13:37

标签: django django-forms django-templates django-validation

对于表单验证,我需要发送错误消息,因为我使用的是验证错误,但不是将错误发送到模板,在其错误页面上显示验证错误,您可以看到图像。 This is what I am getting

在我的观点中

    def form_valid(self, form):
    user = get_current_user(self.request)
    review = self.request.POST.get('review')
    user_profile = get_object_or_404(UserProfileModel, display_username=self.kwargs['display_username'])
    ratings = get_object_or_404(Rating,user_profile_model=user_profile)
    try:
        usr_rating = UserRating.objects.get(rating=ratings, user = user)
    except UserRating.DoesNotExist:
        usr_rating = None
    if usr_rating:
        usr_rating.review = review
        usr_rating.save()
    else:
        raise forms.ValidationError('Please rate first')
    return super(UserProfileView,self).form_valid(form)

在我的模板中

  {% if not form.is_valid %}
      {% for error in form.errors %}
          error
      {% endfor %}
    {% endif %}

我无法弄清问题或者我对使用表单验证感到困惑,请帮帮我。

1 个答案:

答案 0 :(得分:1)

Django不会将视图级别引发的错误视为表单错误。您需要使用add_error方法添加表单错误,而不是引发错误。您可以为此覆盖get_form方法:

def get_form(self, form_class=None):
    form = super().get_form(form_class)
    if self.request.method == 'POST':
        user = get_current_user(self.request)
        review = self.request.POST.get('review')
        user_profile = get_object_or_404(UserProfileModel, display_username=self.kwargs['display_username'])
        ratings = get_object_or_404(Rating,user_profile_model=user_profile)
        try:
            usr_rating = UserRating.objects.get(rating=ratings, user = user)
        except UserRating.DoesNotExist:
            usr_rating = None
        if usr_rating:
            usr_rating.review = review
            usr_rating.save()
        else:
            form.add_error(None, 'Please rate first')
    return form

这将添加non_feild_errors

{% if form.non_field_errors %}
    {{ form.non_field_errors }}
{% endif %}