Django form validation: get errors in JSON format

2024/10/12 22:31:07

I have this very simple Django form

from django import formsclass RegistrationForm(forms.Form):Username = forms.CharField()Password = forms.CharField()

I manage this manually and don't use the template engine. Rather, I send data with ajax POST and expect to receive back validation errors. While I was working with other frameworks, I used to receive validation errors in JSON format in key-value pairs (the key being the name of the field with the error and the value being the error message).

{Username: "This field is required.",Password: "This field is required.",
}

I'm trying to achieve the same result in Django, but I don't understand how can I access the raw error messages (relative to a single field) and localize them.

form.errors give access to HTML code (as explained here: displaying django form validation errors for ModelForms). I don't need that. I'd prefer something like form.Username.validationError: does such a thing exists?

If yes, additionally I'd also like to know if the validation error message is automatically translated into the user language and, if not, the best way to do that.

Answer

Django let you send the forms errors as Json. You only need to use the errors in the following form form.errors.as_json().

A great addition to the library I must say.

Updated: updated link thanks donrondadon comment on this thread.

https://en.xdnf.cn/q/69605.html

Related Q&A

Django inheritance and polymorphism with proxy models

Im working on a Django project that I did not start and I am facing a problem of inheritance. I have a big model (simplified in the example) called MyModel that is supposed to represents different kind…

L suffix in long integer in Python 3.x

In Python 2.x there was a L suffix after long integer. As Python 3 treats all integers as long integer this has been removed. From Whats New In Python 3.0:The repr() of a long integer doesn’t include …

Custom Colormap

I want to plot a heatmap with a custom colormap similar to this one, although not exactly.Id like to have a colormap that goes like this. In the interval [-0.6, 0.6] the color is light grey. Above 0.6,…

Whats the point of @staticmethod in Python?

Ive developed this short test/example code, in order to understand better how static methods work in Python.class TestClass:def __init__(self, size):self.size = sizedef instance(self):print("regul…

logical or on list of pandas masks

I have a list of boolean masks obtained by applying different search criteria to a dataframe. Here is an example list containing 4 masks: mask_list = [mask1, mask2, mask3, mask4]I would like to find th…

How to view the implementation of pythons built-in functions in pycharm?

When I try to view the built-in function all() in PyCharm, I could just see "pass" in the function body. How to view the actual implementation so that I could know what exactly the built-in f…

How to gracefully fallback to `NaN` value while reading integers from a CSV with Pandas?

While using read_csv with Pandas, if i want a given column to be converted to a type, a malformed value will interrupt the whole operation, without an indication about the offending value.For example, …

Python - object layout

can somebody describe the following exception? What is the "object layout" and how it is defined? ThanksTraceback (most recent call last):File "test_gui.py", line 5, in <module…

Using Tor proxy with scrapy

I need help setting up Tor in Ubuntu and to use it within scrapy framework.I did some research and found out this guide:class RetryChangeProxyMiddleware(RetryMiddleware):def _retry(self, request, reaso…

Best practice for structuring module exceptions in Python3

Suppose I have a project with a folder structure like so./project__init__.pymain.py/__helpers__init__.pyhelpers.py...The module helpers.py defines some exception and contains some method that raises th…