1

I'm writing my RESTful service by hand. Form and view is as below:

forms.py

class RegistrationForm(forms.Form):
    email = forms.EmailField(required=True, label="E-Posta", help_text="E-postalar gerçek bir kişi olduğunuzu anlamamız için gereklidir.", min_length=3)
    username = forms.SlugField(required=True, label="Kullanıcı Adı", help_text="Kullanıcı adınız bir sefer seçilebilir. Daha sonra değiştirilemez. boşluk barındıramaz.")
    password = forms.CharField(required=True, label="Şifre", help_text="Parolanız en az 8 karakterden oluşmalıdır.", min_length=8)
    password_validate = forms.CharField(required=True, label="Tekrar Şifre", min_length=8)
    captcha = CaptchaField()

    def clean(self):
        password = self.cleaned_data.get("password")
        password_validate = self.cleaned_data.get("password_validate")

        if password != password_validate:
            raise forms.ValidationError("Şifreler uyuşmuyor.") # This is my error message.

views.py

def registration_validator(request):
    if request.method != "POST":
        response = HttpResponse("", content_type="text/plain")
        response.status_code = 405
        return response

    registration_form = web_forms.RegistrationForm(request.POST)

    if registration_form.is_valid() == False:
        response = HttpResponse("", content_type="text/plain") # Here I want to return the message of ValidationError which is raised in forms.py.
        response.status_code = 400
        return response

    response = HttpResponse("", content_type=content_type)
    response.status_code = 200
    return response

How can I return the message of ValidationError in views.py?

Environment

  • django 1.8.7

1 Answer 1

1

Exactly the same as you would in the template: by accessing the registration_form.errors dict.

Sign up to request clarification or add additional context in comments.

2 Comments

Which elements do that dictionary has? I mean, form.errors["message"] will work? Any documentation is okay.
docs.djangoproject.com/en/1.9/ref/forms/api/… - note that registration_form.errors.as_json() will probably be useful for you here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.