标签云

微信群

扫码加入我们

WeChat QR Code

For form validation I need to send error messages, for that I am using validation error but instead of sending errors to template its showing validation error on its error page, you can see image. This is what I am getting

In my views

    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)

In my template

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

I am unable to figure out the problem or I am confused to use form validation, please help me out.


You really shouldn't be doing this validation in form_valid - that is for when the form is already valid. Indeed, you shouldn't do it in the view at all, but in the form itself.

2018年06月19日28分21秒

Thanks sir but its showing me this error - 'ReviewForm' object has no attribute 'cleaned_data'

2018年06月20日28分21秒

PankajSharma try to add request method validation. See updates.

2018年06月19日28分21秒

You are not triggering the cleaning and validation of the form, this is made by calling the form.is_valid() method, that's why you have no cleaned data.

2018年06月19日28分21秒

ohh, thanks a lot it worked , check if you could help me out in this also stackoverflow.com/questions/50822957/…

2018年06月19日28分21秒