error_messages - Встроенная проверка полей Django

Опубликовано: 25 Февраля, 2022

Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. error_messages attribute is used to modify error messages that are displayed in the admin interface during failure of some constraint.

Например, вы можете заменить сообщение «Это поле обязательно» своим собственным сообщением. Это позволяет вам переопределить сообщения по умолчанию, которые появятся в этом поле. Передайте словарь с ключами, соответствующими сообщениям об ошибках, которые вы хотите переопределить. Ключи сообщений об ошибках включают null , blank , invalid , invalid_choice , unique и unique_for_date .

Syntax –

field_name = models.Field(error_messages = {"key": "message"})

Django Built-in Field Validation editable=False Explanation

Illustration of error_messages using an Example. Consider a project named geeksforgeeks having an app named geeks.

Refer to the following articles to check how to create a project and an app in Django.

  • How to Create a Basic Project using MVT in Django?
  • How to Create an App in Django ?

Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options.

from django.db import models
from django.db.models import Model
# Create your models here.
  
class GeeksModel(Model):
    geeks_field = models.CharField(
                    max_length = 200,  
                    unique = True
                    )

After running makemigrations and migrate on Django and rendering the above model, let us create an instance from Django admin interface with string “a“. Now to break the constraint of unique=True, let us try to create one more instance of the model using same string. Now it will show this error.

Now let us modify this error message to “The Geeks Field you enetered is not unique.” using error_messages. Change the models.py to

from django.db import models
from django.db.models import Model
# Create your models here.
  
class GeeksModel(Model):
    geeks_field = models.CharField(
                    max_length = 200,  
                    unique = True,
                    error_messages ={
                    "unique":"The Geeks Field you enetered is not unique."
                    }
                    )

Поскольку models.py изменен, запустите makemigrations и снова выполните миграцию проекта. Откройте интерфейс администратора и попробуйте снова создать экземпляр, используя строку «a».

You can see the modified error message. Therefore, error_messages modifies the field error messages. you can modify using other attributes such as null, blank, etc.

More Built-in Field Validations

Field OptionsDescription
NullIf True, Django will store empty values as NULL in the database. Default is False.
BlankIf True, the field is allowed to be blank. Default is False.
db_columnThe name of the database column to use for this field. If this isn’t given, Django will use the field’s name.
DefaultThe default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
help_textExtra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
primary_keyIf True, this field is the primary key for the model.
editableIf False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.
error_messagesThe error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override.
help_textExtra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
verbose_nameA human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
validatorsA list of validators to run for this field. See the validators documentation for more information.
UniqueIf True, this field must be unique throughout the table.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.