对于表单验证,我需要发送错误消息,因为我使用的是验证错误,但不是将错误发送到模板,在其错误页面上显示验证错误,您可以看到图像。
在我的观点中
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 %}
我无法弄清问题或者我对使用表单验证感到困惑,请帮帮我。
答案 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 %}