O framework de verificação do sistema.¶
O framework de verificação do sistema é um conjunto de verificações estáticas para validação de projetos Django. Ele detecta problemas comuns e fornece dicas de como arrumá-los. O framework é extensível e você pode facilmente adicionar suas próprias validações.
Para detalhes de como adicionar suas próprias verificações e integrar isso com os sistema de verificação do Django, veja o Tópico sistema de verificação do giua..
Referência da API¶
CheckMessage¶
- class CheckMessage(level, msg, hint=None, obj=None, id=None)[código-fonte]¶
Os alertas e erros emitidos pelo sistema de verificação devem ser uma instância de CheckMessage. Uma instância encapsula um único erro ou aviso. Ele também fornece contexto e dicas aplicáveia a mensagem, e um identificador único que é usado para propósitos de filtragem.
Os argumentos do Construtor são:
levelA gravidade da mensagem. Use um dos valores pré-definidos:
DEBUG,INFO,WARNING,ERROR,CRITICAL. Se o nível é maior ou igual aERROR`, então o Django irá impedir que comandos de gerenciamento sejam exeutados. Mensagens com nível menor que ``ERROR(ex. alertas) são reportados no console, mas pode ser silenciados.msgUma string curta (menor que 80 caracetres) descrevendo o problema. A string não deve conter outras linhas.
hintUma string de uma única linha que forneça uma dica para arrumar o problema. Se não pode ser fornecida uma dica, ou a dica é auto-evidente baseado na mensagem de erro, a dica pode ser omitida, ou o valor
Nonepode ser usado.objOpcional. Um objeto que fornece contexto para a mensagem (por exemplo, o modelo onde o problema foi descoberto). O objeto deve ser um modelo, campo ou gerenciador ou qualquer outro objeto que defina um método
__str__(). O método é usado durante a exibição de todas as mensagens e seu resultado precede a mensagem.idString opcional. Um identificador único para esse problema. Identificadores devem seguir o formato padrão
applabel.X001, ondeXé uma das letras deCEWID, indicando a gravidade da mensagem (Cpara crítico,Epara erro e assim por diante). O número pode ser alocado pela aplicação, mas deve ser único dentro daquela aplicação.
Existem subclasses para tornar a criação de mensagens de níveis comuns mais fácil. Quando usá-los você pode omitir o argumento level porque ele está implícito no nome da classe.
- class Debug(msg, hint=None, obj=None, id=None)[código-fonte]¶
- class Info(msg, hint=None, obj=None, id=None)[código-fonte]¶
- class Warning(msg, hint=None, obj=None, id=None)[código-fonte]¶
- class Error(msg, hint=None, obj=None, id=None)[código-fonte]¶
- class Critical(msg, hint=None, obj=None, id=None)[código-fonte]¶
Verificações do núcleo do sistema¶
Suporte assíncrono¶
As seguintes checagens verificarão seu setup para Suporte assíncrono:
async.E001: Você não deve definir a variável de ambiente
DJANGO_ALLOW_ASYNC_UNSAFEem produção. Isso desabilita a proteção de segurança assíncrona.
Retrocompatibilidade¶
Testes de compatibilidade notificam sobre problemas que podem ocorrer após atualizar o Django.
2_0.W001: Sua URL
<pattern>tem umrouteque contém(?P<, começa com um^ou termina com um$. Isso provavelmente foi um descuido ao migrar deurl()parapath().4_0.E001: A partir do Django 4.0, os valores na configuração
CSRF_TRUSTED_ORIGINSdevem começar com um esquema (geralmentehttp://ouhttps://), mas foi encontrado<hostname>.
Caches¶
As verificações seguintes averiguam se seu CACHES está configurado corretamente:
caches.E001: Você deve definir um cache
'default'para a definição deCACHES.caches.W002: Sua configuração
<cache>pode expor o seu cache ou levar à corrupção dos seus dados porque aLOCATION<CACHES-LOCATION> coincide/está dentro/contém aMEDIA_ROOT/STATIC_ROOT/STATICFILES_DIRS.caches.W003: Your
<cache>cacheLOCATIONis relative. Use an absolute path instead.
Banco de dados¶
MySQL e MariaDB¶
If you’re using MySQL or MariaDB, the following checks will be performed:
mysql.E001: MySQL/MariaDB does not allow unique
CharFields to have amax_length> 255. This check was changed tomysql.W003in Django 3.1 as the real maximum size depends on many factors.mysql.W002: MySQL/MariaDB Strict Mode is not set for database connection
<alias>. See also Setting sql_mode.mysql.W003: MySQL/MariaDB may not allow unique
CharFields to have amax_length> 255.
Gerenciando arquivos¶
The following checks verify your setup for Gerenciando arquivos:
files.E001: The
FILE_UPLOAD_TEMP_DIRsetting refers to the nonexistent directory<path>.
Campos Modelos¶
fields.E001: Nomes de campos não devem terminar com “underscore”.
fields.E002: nome de campos não devem conter
"__".fields.E003:
pké uma palavra reservada que não pode ser usada como nome de campo.fields.E004:
choicesmust be a mapping (e.g. a dictionary) or an iterable (e.g. a list or tuple).fields.E005:
choicesmust be a mapping of actual values to human readable names or an iterable containing(actual value, human readable name)tuples.fields.E006:
db_indexdeve serNone,TrueouFalse.fields.E007: Chaves-primárias não devem ter
null=True.fields.E008: All
validatorsmust be callable.fields.E009:
max_lengthis too small to fit the longest value inchoices(<count>characters).fields.E010:
<field>default should be a callable instead of an instance so that it’s not shared between all field instances.fields.E011:
<database>does not support default database values with expressions (db_default).fields.E012:
<expression>cannot be used indb_default.fields.E100:
AutoFields devem setar primary_key=True.fields.E110:
BooleanFields do not accept null values. This check appeared before support for null values was added in Django 2.1.fields.E120:
CharFields deve definir um atributomax_length.fields.E121:
max_lengthdeve ser um inteiro positivo.fields.W122:
max_lengthis ignored when used with<integer field type>.fields.E130:
DecimalFields deve definir um atributodecimal_places.fields.E131:
decimal_placesdeve ser um inteiro não negativo.fields.E132:
DecimalFields deve ter um atributomax_digits.fields.E133:
max_digitsmust be a positive integer.fields.E134:
max_digitsdeve ser igual ou maior quedecimal_places.fields.E140:
FilePathFields deve terallow_filesouallow_foldersdefinidos como True.fields.E150:
GenericIPAddressFields cannot haveblank=Trueifnull=False, as blank values are stored as nulls.fields.E160: As opções
auto_now,auto_now_add, edefaultsão mutualmente exclusivas. Somente uma destas opções deve estar presente.fields.W161: Fornecido um valor fixo padrão.
fields.W162:
<database>does not support a database index on<field data type>columns.fields.W163:
<database>does not support comments on columns (db_comment).fields.E170:
BinaryField’sdefaultcannot be a string. Use bytes content instead.fields.E180:
<database>does not supportJSONFields.fields.E190:
<database>does not support a database collation on<field_type>s.fields.E220:
<database>does not supportGeneratedFields.fields.E221:
<database>does not support non-persistedGeneratedFields.fields.E222:
<database>does not support persistedGeneratedFields.fields.E223:
GeneratedField.output_fieldhas errors: …fields.W224:
GeneratedField.output_fieldhas warnings: …fields.E900:
IPAddressFieldfoi removido exceto para suportar migrações históricas.fields.W900:
IPAddressFieldestá obsoleto. O suporte para este (exceto para histórico de migrações) será removido no Django 1.9. Esta verificação apareceu em Django 1.7 and 1.8.fields.W901:
CommaSeparatedIntegerFieldhas been deprecated. Support for it (except in historical migrations) will be removed in Django 2.0. This check appeared in Django 1.10 and 1.11.fields.E901:
CommaSeparatedIntegerFieldis removed except for support in historical migrations.fields.W902:
FloatRangeFieldis deprecated and will be removed in Django 3.1. This check appeared in Django 2.2 and 3.0.fields.W903:
NullBooleanFieldis deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. This check appeared in Django 3.1 and 3.2.fields.E903:
NullBooleanFieldis removed except for support in historical migrations.fields.W904:
django.contrib.postgres.fields.JSONFieldis deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. This check appeared in Django 3.1 and 3.2.fields.E904:
django.contrib.postgres.fields.JSONFieldis removed except for support in historical migrations.fields.W905:
django.contrib.postgres.fields.CICharFieldis deprecated. Support for it (except in historical migrations) will be removed in Django 5.1. This check appeared in Django 4.2 and 5.0.fields.E905:
django.contrib.postgres.fields.CICharFieldis removed except for support in historical migrations.fields.W906:
django.contrib.postgres.fields.CIEmailFieldis deprecated. Support for it (except in historical migrations) will be removed in Django 5.1. This check appeared in Django 4.2 and 5.0.fields.E906:
django.contrib.postgres.fields.CIEmailFieldis removed except for support in historical migrations.fields.W907:
django.contrib.postgres.fields.CITextFieldis deprecated. Support for it (except in historical migrations) will be removed in Django 5.1. This check appeared in Django 4.2 and 5.0.fields.E907:
django.contrib.postgres.fields.CITextFieldis removed except for support for historical migrations.
Campos de Arquivo¶
fields.E200:
uniquenão é um argumento válido paraFileField. Esta verificação foi removida no Django 1.11.fields.E201:
primary_keynão é um argumento válido para umFileField.fields.E202:
FileField’supload_toargument must be a relative path, not an absolute path.fields.E210: Não é possível usar
ImageFieldporque o Pillow não está instalado.
Models¶
models.E001:
<swappable>não está no formatoapp_label.app_name.models.E002:
<SETTING>referencia<model>, o qual nao foi instalado, ou é abstrato.models.E003: The model has two identical many-to-many relations through the intermediate model
<app_label>.<model>.models.E004:
idsomente pode ser usado como nome de um campo se o campo também definirprimary_key=True.models.E005: O campo
<field name>do modelo pai<model>colide com o campo<field name>do modelo pai<model>.models.E006: The field
<field name>clashes with the field<field name>from model<model>.models.E007: Campo
<field name>tem o nome de coluna<column name>que é usado por outro campo.models.E008:
index_togethermust be a list or tuple. This check appeared before Django 5.1.models.E009: All
index_togetherelements must be lists or tuples. This check appeared before Django 5.1.models.E010:
unique_togetherdeve ser uma lista de tuplas.models.E011: Todos os elementos de
unique_togetherdevem ser uma lista de tuplas.models.E012:
constraints/indexes/unique_togetherrefers to the nonexistent field<field name>.models.E013:
constraints/indexes/unique_togetherrefers to aManyToManyField<field name>, butManyToManyFields are not supported for that option.models.E014:
orderingdeve ser uma tupla ou listat (mesmo que você queira ordernar por um único campo).models.E015:
orderingrefers to the nonexistent field, related field, or lookup<field name>.models.E016:
constraints/indexes/unique_togetherrefers to field<field_name>which is not local to model<model>.models.E017: O modelo proxy
<model>cotém campos de modelo.models.E018: Nome de coluna gerado automaticamente é muito longo para o campo
<field>. O comprimento máximo é<maximum length>para o banco de dados<alias>.models.E019: Nome de campo gerado automaticamente para o campo M2M
<M2M field>é muito longo. O comprimento máximo é<maximum length>para o banco de dados<alias>.models.E020: The
<model>.check()método da classe está neste momento sobrescrito.models.E021:
orderingeorder_with_respect_tonão podem ser usados juntos.models.E022:
<function>contains a lazy reference to<app label>.<model>, but app<app label>isn’t installed or doesn’t provide model<model>.models.E023: The model name
<model>cannot start or end with an underscore as it collides with the query lookup syntax.models.E024: The model name
<model>cannot contain double underscores as it collides with the query lookup syntax.models.E025: The property
<property name>clashes with a related field accessor.models.E026: The model cannot have more than one field with
primary_key=True.models.W027:
<database>does not support check constraints.models.E028:
db_table<db_table>is used by multiple models:<model list>.models.E029: index name
<index>is not unique for model<model>.models.E030: index name
<index>is not unique among models:<model list>.models.E031: constraint name
<constraint>is not unique for model<model>.models.E032: constraint name
<constraint>is not unique among models:<model list>.models.E033: The index name
<index>cannot start with an underscore or a number.models.E034: The index name
<index>cannot be longer than<max_length>characters.models.W035:
db_table<db_table>is used by multiple models:<model list>.models.W036:
<database>does not support unique constraints with conditions.models.W037:
<database>does not support indexes with conditions.models.W038:
<database>does not support deferrable unique constraints.models.W039:
<database>does not support unique constraints with non-key columns.models.W040:
<database>does not support indexes with non-key columns.models.E041:
constraintsrefers to the joined field<field name>.models.W042: Auto-created primary key used when not defining a primary key type, by default
django.db.models.AutoField.models.W043:
<database>does not support indexes on expressions.models.W044:
<database>does not support unique constraints on expressions.models.W045: Check constraint
<constraint>containsRawSQL()expression and won’t be validated during the modelfull_clean().models.W046:
<database>does not support comments on tables (db_table_comment).models.W047:
<database>does not support unique constraints with nulls distinct.
Segurança¶
The security checks do not make your site secure. They do not audit code, do intrusion detection, or do anything particularly complex. Rather, they help perform an automated, low-hanging-fruit checklist, that can help you to improve your site’s security.
Algumas dessas verificações talvez não sejam apropriadas para uma configuração de implantação particular. Por exemlo, se você faz redirecionamento do HTTP para HTTPS em um balanceador de carga, isso pode ser irritante de ser constantemente alertado sobre não ter habilitado o SECURE_SSL_REDIRECT. Use o SILENCED_SYSTEM_CHECKS para silenciar verificações desnecessárias.
As seguintes verificações são executadas se você usa a opção check --deploy:
security.W001: You do not have
django.middleware.security.SecurityMiddlewarein yourMIDDLEWAREso theSECURE_HSTS_SECONDS,SECURE_CONTENT_TYPE_NOSNIFF,SECURE_REFERRER_POLICY,SECURE_CROSS_ORIGIN_OPENER_POLICY, andSECURE_SSL_REDIRECTsettings will have no effect.security.W002: You do not have
django.middleware.clickjacking.XFrameOptionsMiddlewarein yourMIDDLEWARE, so your pages will not be served with an'x-frame-options'header. Unless there is a good reason for your site to be served in a frame, you should consider enabling this header to help prevent clickjacking attacks.security.W003: You don’t appear to be using Django’s built-in cross-site request forgery protection via the middleware (
django.middleware.csrf.CsrfViewMiddlewareis not in yourMIDDLEWARE). Enabling the middleware is the safest approach to ensure you don’t leave any holes.security.W004: Você não definiu um valor para a definição de
SECURE_HSTS_SECONDS. Se todo o seu site é servido via SSL, talvez queira considerar definir o valor e habilitar HTTP Strict Transport Security. Tenha certeza de ler a documentação primeiro; habilitando HSTS sem cuidados você pode causar problema sérios e irreversíveis.security.W005: Você não definiu a definição de
SECURE_HSTS_INCLUDE_SUBDOMAINSparaTrue. Sem isso, seu site está pontencialmente vulnerável a ataques através de uma conexão insegura para um subdomínio. Somente definica comoTruese você está certo de que todos os subdomínios do seu domínio devem ser servidos exclusivamente via SSL.security.W006: Your
SECURE_CONTENT_TYPE_NOSNIFFsetting is not set toTrue, so your pages will not be served with an'X-Content-Type-Options: nosniff'header. You should consider enabling this header to prevent the browser from identifying content types incorrectly.security.W007: Your
SECURE_BROWSER_XSS_FILTERsetting is not set toTrue, so your pages will not be served with an'X-XSS-Protection: 1; mode=block'header. You should consider enabling this header to activate the browser’s XSS filtering and help prevent XSS attacks. This check is removed in Django 3.0 as theX-XSS-Protectionheader is no longer honored by modern browsers.security.W008: Sua definição para
SECURE_SSL_REDIRECTnão éTrue. A menos que seu site deva estar disponível tanto para conexões SSL quanto para não SSL, você talvez queira definir este comoTrueou configurar o balanceador de carga ou o servidor de proxy reverso para redirecionar todas as conexões para HTTPS.security.W009: Your
SECRET_KEYhas less than 50 characters, less than 5 unique characters, or it’s prefixed with'django-insecure-'indicating that it was generated automatically by Django. Please generate a long and random value, otherwise many of Django’s security-critical features will be vulnerable to attack.security.W010: Você tem
django.contrib.sessionsno seuINSTALLED_APPSmas não definiuSESSION_COOKIE_SECUREcomoTrue. Usando uma “cookie” de sessão “somente-segura” é mais difícil para um “sniffer” de tráfego de rede capturar sessões do usuário.security.W011: You have
django.contrib.sessions.middleware.SessionMiddlewarein yourMIDDLEWARE, but you have not setSESSION_COOKIE_SECUREtoTrue. Using a secure-only session cookie makes it more difficult for network traffic sniffers to hijack user sessions.security.W012:
SESSION_COOKIE_SECUREnão éTrue. Usando uma “cookie” de sessão como “somente-segura” é mais difícil para um “sniffer” de tráfego de rede capturar sessões do usuário.security.W013: Você
django.contrib.sessionsno seuINSTALLED_APPS, mas não definiuSESSION_COOKIE_HTTPONLYcomoTrue. Usando uma “cookie” de sessãoHttpOnlyfaz com que seja mais difícil um ataque de script extra-site capturar sessões de usuários.security.W014: You have
django.contrib.sessions.middleware.SessionMiddlewarein yourMIDDLEWARE, but you have not setSESSION_COOKIE_HTTPONLYtoTrue. Using anHttpOnlysession cookie makes it more difficult for cross-site scripting attacks to hijack user sessions.security.W015:
SESSION_COOKIE_HTTPONLYnão está definido comoTrue. Usando uma cookie de sessão comoHttpOnlytorna mais difícil um ataque de script extra-site capturar sessões de usuários.security.W016:
CSRF_COOKIE_SECUREnão está comoTrue. Usando a “secure-only” para a “cookie” CSRF torna mais difícil para um “sniffer” de tráfego de rede roubar o token CSRF.security.W017:
CSRF_COOKIE_HTTPONLYis not set toTrue. Using anHttpOnlyCSRF cookie makes it more difficult for cross-site scripting attacks to steal the CSRF token. This check is removed in Django 1.11 as theCSRF_COOKIE_HTTPONLYsetting offers no practical benefit.security.W018: Você não deve definir
DEBUGcomoTrueem produção.security.W019: You have
django.middleware.clickjacking.XFrameOptionsMiddlewarein yourMIDDLEWARE, butX_FRAME_OPTIONSis not set to'DENY'. Unless there is a good reason for your site to serve other parts of itself in a frame, you should change it to'DENY'.security.W020:
ALLOWED_HOSTSnão deve estar vazio durante a implantação.security.W021: You have not set the
SECURE_HSTS_PRELOADsetting toTrue. Without this, your site cannot be submitted to the browser preload list.security.W022: You have not set the
SECURE_REFERRER_POLICYsetting. Without this, your site will not send a Referrer-Policy header. You should consider enabling this header to protect user privacy.security.E023: You have set the
SECURE_REFERRER_POLICYsetting to an invalid value.security.E024: You have set the
SECURE_CROSS_ORIGIN_OPENER_POLICYsetting to an invalid value.security.W025: Your
SECRET_KEY_FALLBACKS[n]has less than 50 characters, less than 5 unique characters, or it’s prefixed with'django-insecure-'indicating that it was generated automatically by Django. Please generate a long and random value, otherwise many of Django’s security-critical features will be vulnerable to attack.
The following checks verify that your security-related settings are correctly configured:
security.E100:
DEFAULT_HASHING_ALGORITHMmust be'sha1'or'sha256'. This check appeared in Django 3.1 and 3.2.security.E101: The CSRF failure view
'path.to.view'does not take the correct number of arguments.security.E102: The CSRF failure view
'path.to.view'could not be imported.
Signals¶
signals.E001:
<handler>was connected to the<signal>signal with a lazy reference to the sender<app label>.<model>, but app<app label>isn’t installed or doesn’t provide model<model>.
Templates¶
As verificações seguintes averiguam se sua definição de TEMPLATES está corretamente configurada.
templates.E001: You have
'APP_DIRS': Truein yourTEMPLATESbut also specify'loaders'inOPTIONS. Either removeAPP_DIRSor remove the'loaders'option. This check is removed in Django 5.1 as system checks may now raiseImproperlyConfiguredinstead.templates.E002:
string_if_invalidinTEMPLATESOPTIONSmust be a string but got:{value}({type}).templates.E003:
<name>is used for multiple template tag modules:<module list>. This check was changed totemplates.W003in Django 4.1.2.templates.W003:
<name>is used for multiple template tag modules:<module list>.
Translation¶
The following checks are performed on your translation configuration:
translation.E001: You have provided an invalid value for the
LANGUAGE_CODEsetting:<value>.translation.E002: You have provided an invalid language code in the
LANGUAGESsetting:<value>.translation.E003: You have provided an invalid language code in the
LANGUAGES_BIDIsetting:<value>.translation.E004: You have provided a value for the
LANGUAGE_CODEsetting that is not in theLANGUAGESsetting.
URLs¶
As verificações seguintes são realizadas na sua configuração de URL:
urls.W001: Your URL pattern
<pattern>usesinclude()with arouteending with a$. Remove the dollar from therouteto avoid problems including URLs.urls.W002: Your URL pattern
<pattern>has aroutebeginning with a/. Remove this slash as it is unnecessary. If this pattern is targeted in aninclude(), ensure theinclude()pattern has a trailing/.urls.W003: Seu formato padrão de
<pattern>tem umnameincluindo um:. Remova os dois-pontos para evitar referências anbíguas de domínios baseados em nomes.urls.E004: Your URL pattern
<pattern>is invalid. Ensure thaturlpatternsis a list ofpath()and/orre_path()instances.urls.W005: URL namespace
<namespace>isn’t unique. You may not be able to reverse all URLs in this namespace.urls.E006: The
MEDIA_URL/STATIC_URLsetting must end with a slash.urls.E007: The custom
handlerXXXview'path.to.view'does not take the correct number of arguments (…).urls.E008: The custom
handlerXXXview'path.to.view'could not be imported.urls.E009: Your URL pattern
<pattern>has an invalid view, pass<view>.as_view()instead of<view>.urls.W010: Your URL pattern
<pattern>has an unmatched<angle bracket>.
contrib app checks¶
admin¶
Verificações do Admin são todas realizadas como parte da etiqueta admin.
As seguintes verificações sào realizadas em qualquer ModelAdmin (ou subclasse) que está registrada com o site Admin:
admin.E001: O valor de
raw_id_fieldsdeve ser uma lista de tuplas.admin.E002: The value of
raw_id_fields[n]refers to<field name>, which is not a field of<model>.admin.E003: O valor de
raw_id_fields[n]deve ser uma chave estrangeira ou m campo muitos-para-muitos.admin.E004: O valor do
fieldsdeve ser uma lista de tuplas.admin.E005: Ambos
fieldsetsefieldssão especificados.admin.E006: O valor do
fieldscontém campo(s) duplicados.admin.E007: O valor do
fieldsetsdeve ser uma lista de tuplas.admin.E008: O valor do
fieldsets[n]deve ser uma lista de tuplas.admin.E009: O valor do
fieldsets[n]deve ter o comprimento igual a 2.admin.E010: O valor do
fieldsets[n][1]deve ser um dicionário.admin.E011: O valor do
fieldsets[n][1]deve conter a chavefields.admin.E012: Existem campo(s) ducplicados em
fieldsets[n][1].admin.E013: The value of
fields[n]/filter_horizontal[n]/filter_vertical[n]/fieldsets[n][m]cannot include theManyToManyField<field name>, because that field manually specifies a relationship model.admin.E014: O valor do
excludedeve ser uma lista de tuplas.admin.E015: O valor do
excludecontém campos duplicado(s).admin.E016: O valor do
formdeve herdar deBaseModelForm.admin.E017: O valor do
filter_verticaldeve ser uma lista de tuplas.admin.E018: O valor de
filter_horizontaldeve ser uma lista de tuplas.admin.E019: The value of
filter_vertical[n]/filter_horizontal[n]refers to<field name>, which is not a field of<model>.admin.E020: The value of
filter_vertical[n]/filter_horizontal[n]must be a many-to-many field.admin.E021: O valor de
radio_fieldsdeve ser um dicionário.admin.E022: The value of
radio_fieldsrefers to<field name>, which is not a field of<model>.admin.E023: The value of
radio_fieldsrefers to<field name>, which is not an instance ofForeignKey, and does not have achoicesdefinition.admin.E024: O valor de
radio_fields[<field name>]deve seradmin.HORIZONTALouadmin.VERTICAL.admin.E025: O valor de
view_on_sitedeve ser um “callable” ou um booleano.admin.E026: O valor de
prepopulated_fieldsdeve ser um dicionário.admin.E027: The value of
prepopulated_fieldsrefers to<field name>, which is not a field of<model>.admin.E028: The value of
prepopulated_fieldsrefers to<field name>, which must not be aDateTimeField, aForeignKey, aOneToOneField, or aManyToManyFieldfield.admin.E029: O valor de
prepopulated_fields[<field name>]deve ser uma lista de tuplas.admin.E030: The value of
prepopulated_fieldsrefers to<field name>, which is not a field of<model>.admin.E031: O valor de
orderingdeve ser uma lista de tuplas.admin.E032: O valor de
orderingtem o operador para ordem randômica?, mas contém outros campos também.admin.E033: The value of
orderingrefers to<field name>, which is not a field of<model>.admin.E034: O valor de
readonly_fieldsdeve ser uma lista de tuplas.admin.E035: The value of
readonly_fields[n]refers to<field_name>, which is not a callable, an attribute of<ModelAdmin class>, or an attribute of<model>.admin.E036: The value of
autocomplete_fieldsmust be a list or tuple.admin.E037: The value of
autocomplete_fields[n]refers to<field name>, which is not a field of<model>.admin.E038: The value of
autocomplete_fields[n]must be a foreign key or a many-to-many field.admin.E039: An admin for model
<model>has to be registered to be referenced by<modeladmin>.autocomplete_fields.admin.E040:
<modeladmin>must definesearch_fields, because it’s referenced by<other_modeladmin>.autocomplete_fields.
ModelAdmin¶
A verificações seguintes são realizadas para qualquer ModelAdmin que é registrada com site Admin:
admin.E101: O valor de
save_asdeve ser um booleano.admin.E102: O valor de
save_on_topdeve ser um booleano.admin.E103: O valor de
inlinesdeve ser uma lista de tuplas.admin.E104:
<InlineModelAdmin class>must inherit fromInlineModelAdmin.admin.E105:
<InlineModelAdmin class>deve ter um atributomodel.admin.E106: O valor de
<InlineModelAdmin class>.modeldeve ser umModel.admin.E107: O valor de
list_displaydeve ser uma lista de tuplas.admin.E108: The value of
list_display[n]refers to<label>, which is not a callable or attribute of<ModelAdmin class>, or an attribute, method, or field on<model>.admin.E109: The value of
list_display[n]must not be a many-to-many field or a reverse foreign key.admin.E110: O valor de
list_display_linksdeve ser uma lista, uma tupla, ouNone.admin.E111: O valor de
list_display_links[n]referencia a<label>, o qual não é definido nalist_display.admin.E112: O valor de
list_filterdeve ser uma lista de tuplas.admin.E113: O valor de
list_filter[n]deve herdar deListFilter.admin.E114: O valor de
list_filter[n]não deve herdar deFieldListFilter.admin.E115: O valor de
list_filter[n][1]deve herdar deFieldListFilter.admin.E116: O valor de
list_filter[n]refere a<label>, o qual não refere a um campo.admin.E117: O valor de
list_select_relateddeve ser um booleano, tuplas ou lista.admin.E118: O valor de
list_per_pagedeve ser um inteiro.admin.E119: O valor de
list_max_show_alldeve ser um inteiro.admin.E120: O valor de
list_editabledeve ser uma lista de tuplas.admin.E121: The value of
list_editable[n]refers to<label>, which is not a field of<model>.admin.E122: O valor de
list_editable[n]refere a<label>, o qual não está contido emlist_display.admin.E123: O valor de
list_editable[n]não pode estar em amboslist_editableelist_display_links.admin.E124: O valor de
list_editable[n]refere ao primeiro campo emlist_display(<label>), o qual não pode ser usado a menos quelist_display_linksseja definido.admin.E125: O valor de
list_editable[n]refere a<field name>, o qual não é editável através do admin.admin.E126: O valor de
search_fieldsdeve ser uma lista de tuplas.admin.E127: The value of
date_hierarchyrefers to<field name>, which does not refer to a Field.admin.E128: O valor de
date_hierarchydeve ser umDateFieldouDateTimeField.admin.E129:
<modeladmin>must define ahas_<foo>_permission()method for the<action>action.admin.E130:
__name__attributes of actions defined in<modeladmin>must be unique. Name<name>is not unique.
InlineModelAdmin¶
As verificações seguintes são realizadas em qualquer InlineModelAdmin que esteja registrado como uma “inline” na ModelAdmin.
admin.E201: Não pode excluir o campo
<field name>, porque ele é a chave-estrangeira para o modelo<app_label>.<model>.admin.E202:
<model>has noForeignKeyto<parent model>./<model>has more than oneForeignKeyto<parent model>. You must specify afk_nameattribute.admin.E203: O valor de
extradeve ser um inteiro.admin.E204: O valor de
max_numdeve ser um inteiro.admin.E205: O valor de
min_numdeve ser um inteiro.admin.E206: O valor de
formsetdeve herdar deBaseModelFormSet.
GenericInlineModelAdmin¶
As seguintes verificações são realizadas sobre qualquer GenericInlineModelAdmin que esteja registrado como “inline” no ModelAdmin.
admin.E301:
'ct_field'referencia a<label>, o qual não é um campo no<model>.admin.E302:
'ct_fk_field'referencia<label>, o qual não é um campo no<model>.admin.E303:
<model>não temGenericForeignKey.admin.E304:
<model>não temGenericForeignKeyusando o campo de tipo de conteúdo<field name>e um campo de ID do objeto<field name>.
AdminSite¶
As seguintes verificações são realizadas na AdminSite: padrão
admin.E401:
django.contrib.contenttypesmust be inINSTALLED_APPSin order to use the admin application.admin.E402:
django.contrib.auth.context_processors.authmust be enabled inDjangoTemplates(TEMPLATES) if using the default auth backend in order to use the admin application.admin.E403: A
django.template.backends.django.DjangoTemplatesinstance must be configured inTEMPLATESin order to use the admin application.admin.E404:
django.contrib.messages.context_processors.messagesmust be enabled inDjangoTemplates(TEMPLATES) in order to use the admin application.admin.E405:
django.contrib.authmust be inINSTALLED_APPSin order to use the admin application.admin.E406:
django.contrib.messagesmust be inINSTALLED_APPSin order to use the admin application.admin.E408:
django.contrib.auth.middleware.AuthenticationMiddlewaremust be inMIDDLEWAREin order to use the admin application.admin.E409:
django.contrib.messages.middleware.MessageMiddlewaremust be inMIDDLEWAREin order to use the admin application.admin.E410:
django.contrib.sessions.middleware.SessionMiddlewaremust be inMIDDLEWAREin order to use the admin application.admin.W411:
django.template.context_processors.requestmust be enabled inDjangoTemplates(TEMPLATES) in order to use the admin navigation sidebar.
auth¶
auth.E001:
REQUIRED_FIELDSdeve ser uma lista de tuplas.auth.E002: O campo definido como
USERNAME_FIELDpara um modelo de usuário personalizado não deve ser incluído noREQUIRED_FIELDS.auth.E003:
<field>deve ser único porque ele está definido comoUSERNAME_FIELD.auth.W004:
<field>é definido como oUSERNAME_FIELD, mas não é único.auth.E005: The permission codenamed
<codename>clashes with a builtin permission for model<model>.auth.E006: The permission codenamed
<codename>is duplicated for model<model>.auth.E007: The
verbose_nameof model<model>must be at most 244 characters for its builtin permission names to be at most 255 characters.auth.E008: The permission named
<name>of model<model>is longer than 255 characters.auth.C009:
<User model>.is_anonymousmust be an attribute or property rather than a method. Ignoring this is a security issue as anonymous users will be treated as authenticated!auth.C010:
<User model>.is_authenticatedmust be an attribute or property rather than a method. Ignoring this is a security issue as anonymous users will be treated as authenticated!auth.E011: The name of model
<model>must be at most 93 characters for its builtin permission names to be at most 100 characters.auth.E012: The permission codenamed
<codename>of model<model>is longer than 100 characters.auth.E013: In order to use
django.contrib.auth.middleware.LoginRequiredMiddleware,django.contrib.auth.middleware.AuthenticationMiddlewaremust be defined before it in MIDDLEWARE.
contenttypes¶
As verificação seguintes são realizadas quando um modelo contém um GenericForeignKey ou GenericRelation:
contenttypes.E001: The
GenericForeignKeyobject ID references the nonexistent field<field>.contenttypes.E002: The
GenericForeignKeycontent type references the nonexistent field<field>.contenttypes.E003:
<field>não é umaForeignKey.contenttypes.E004:
<field>não é umaForeignKeyparacontenttypes.ContentType.contenttypes.E005: Model names must be at most 100 characters.
postgres¶
The following checks are performed on django.contrib.postgres model
fields:
postgres.E001: Base field for array has errors: …
postgres.E002: Base field for array cannot be a related field.
postgres.E003:
<field>default should be a callable instead of an instance so that it’s not shared between all field instances. This check was changed tofields.E010in Django 3.1.postgres.W004: Base field for array has warnings: …
sites¶
As verificações seguintes são realizadas em qualquer modelo usando uma CurrentSiteManager:
sites.E001:
CurrentSiteManagernão pode achar um campo chamado<field name>.sites.E002:
CurrentSiteManagercannot use<field>as it is not a foreign key or a many-to-many field.
The following checks verify that django.contrib.sites is correctly
configured:
sites.E101: The
SITE_IDsetting must be an integer.
staticfiles¶
The following checks verify that django.contrib.staticfiles is correctly
configured:
staticfiles.E001: The
STATICFILES_DIRSsetting is not a tuple or list.staticfiles.E002: The
STATICFILES_DIRSsetting should not contain theSTATIC_ROOTsetting.staticfiles.E003: The prefix
<prefix>in theSTATICFILES_DIRSsetting must not end with a slash.staticfiles.W004: The directory
<directory>in theSTATICFILES_DIRSdoes not exist.staticfiles.E005: The
STORAGESsetting must define astaticfilesstorage.