We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Alimentação da tabela TipoAutor automática
Preencher a tabela Tipor autor automaticamente para que autores que possuem models relacionadas já estejam disponíveis no sistema.
Apenas a criação de autores categorizados como "Outros" serão adicionados pelo usuário do sistema.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `sapl/base/models.py`
Content:
```
1 import reversion
2 from django.contrib.contenttypes.fields import GenericForeignKey
3 from django.contrib.contenttypes.models import ContentType
4 from django.db import models
5 from django.utils.translation import ugettext_lazy as _
6 
7 from sapl.utils import UF, YES_NO_CHOICES, get_settings_auth_user_model
8 
9 TIPO_DOCUMENTO_ADMINISTRATIVO = (('O', _('Ostensivo')),
10                                  ('R', _('Restritivo')))
11 
12 SEQUENCIA_NUMERACAO = (('A', _('Sequencial por ano')),
13                        ('L', _('Sequencial por legislatura')),
14                        ('U', _('Sequencial único')))
15 
16 
17 @reversion.register()
18 class CasaLegislativa(models.Model):
19     # TODO ajustar todos os max_length !!!!
20     # cod_casa => id (pk)
21 
22     codigo = models.CharField(max_length=100,
23                               blank=True,
24                               verbose_name=_('Codigo'))
25     nome = models.CharField(max_length=100, verbose_name=_('Nome'))
26     sigla = models.CharField(max_length=100, verbose_name=_('Sigla'))
27     endereco = models.CharField(max_length=100, verbose_name=_('Endereço'))
28     cep = models.CharField(max_length=100, verbose_name=_('CEP'))
29     municipio = models.CharField(max_length=100, verbose_name=_('Município'))
30     uf = models.CharField(max_length=100,
31                           choices=UF,
32                           verbose_name=_('UF'))
33     telefone = models.CharField(
34         max_length=100, blank=True, verbose_name=_('Telefone'))
35     fax = models.CharField(
36         max_length=100, blank=True, verbose_name=_('Fax'))
37     logotipo = models.ImageField(
38         blank=True,
39         upload_to='sapl/casa/logotipo/',
40         verbose_name=_('Logotipo'))
41     endereco_web = models.URLField(
42         max_length=100, blank=True, verbose_name=_('HomePage'))
43     email = models.EmailField(
44         max_length=100, blank=True, verbose_name=_('E-mail'))
45     informacao_geral = models.TextField(
46         max_length=100,
47         blank=True,
48         verbose_name=_('Informação Geral'))
49 
50     class Meta:
51         verbose_name = _('Casa Legislativa')
52         verbose_name_plural = _('Casa Legislativa')
53 
54     def __str__(self):
55         return _('Casa Legislativa de %(municipio)s') % {
56             'municipio': self.municipio}
57 
58 
59 @reversion.register()
60 class ProblemaMigracao(models.Model):
61     content_type = models.ForeignKey(ContentType,
62                                      verbose_name=_('Tipo de Content'))
63     object_id = models.PositiveIntegerField(verbose_name=_('ID do Objeto'))
64     content_object = GenericForeignKey('content_type', 'object_id')
65     nome_campo = models.CharField(max_length=100,
66                                   blank=True,
67                                   verbose_name=_('Nome do(s) Campo(s)'))
68     problema = models.CharField(max_length=300, verbose_name=_('Problema'))
69     descricao = models.CharField(max_length=300, verbose_name=_('Descrição'))
70     eh_stub = models.BooleanField(verbose_name=_('É stub?'))
71     critico = models.BooleanField(
72         default=False, verbose_name=_('Crítico'))
73 
74     class Meta:
75         verbose_name = _('Problema na Migração')
76         verbose_name_plural = _('Problemas na Migração')
77 
78 
79 @reversion.register()
80 class Constraint(models.Model):
81     nome_tabela = models.CharField(
82         max_length=50, verbose_name=_('Nome da tabela'))
83     nome_constraint = models.CharField(
84         max_length=100, verbose_name=_('Nome da constraint'))
85     nome_model = models.CharField(
86         max_length=50, verbose_name=_('Nome da model'))
87     tipo_constraint = models.CharField(
88         max_length=50, verbose_name=_('Tipo da constraint'))
89 
90     class Meta:
91         verbose_name = _('Constraint removida')
92         verbose_name_plural = _('Constraints removidas')
93 
94 
95 @reversion.register()
96 class Argumento(models.Model):
97     constraint = models.ForeignKey(Constraint)
98     argumento = models.CharField(
99         max_length=50, verbose_name=_('Argumento'))
100 
101     class Meta:
102         verbose_name = _('Argumento da constraint')
103         verbose_name_plural = _('Argumentos da constraint')
104 
105 
106 @reversion.register()
107 class AppConfig(models.Model):
108 
109     POLITICA_PROTOCOLO_CHOICES = (
110         ('O', _('Sempre Gerar Protocolo')),
111         ('C', _('Perguntar se é pra gerar protocolo ao incorporar')),
112         ('N', _('Nunca Protocolar ao incorporar uma proposição')),
113     )
114 
115     documentos_administrativos = models.CharField(
116         max_length=1,
117         verbose_name=_('Ostensivo/Restritivo'),
118         choices=TIPO_DOCUMENTO_ADMINISTRATIVO, default='O')
119 
120     sequencia_numeracao = models.CharField(
121         max_length=1,
122         verbose_name=_('Sequência de numeração'),
123         choices=SEQUENCIA_NUMERACAO, default='A')
124 
125     # TODO: a ser implementado na versão 3.2
126     # painel_aberto = models.BooleanField(
127     #     verbose_name=_('Painel aberto para usuário anônimo'),
128     #     choices=YES_NO_CHOICES, default=False)
129 
130     texto_articulado_proposicao = models.BooleanField(
131         verbose_name=_('Usar Textos Articulados para Proposições'),
132         choices=YES_NO_CHOICES, default=False)
133 
134     texto_articulado_materia = models.BooleanField(
135         verbose_name=_('Usar Textos Articulados para Matérias'),
136         choices=YES_NO_CHOICES, default=False)
137 
138     texto_articulado_norma = models.BooleanField(
139         verbose_name=_('Usar Textos Articulados para Normas'),
140         choices=YES_NO_CHOICES, default=True)
141 
142     proposicao_incorporacao_obrigatoria = models.CharField(
143         verbose_name=_('Regra de incorporação de proposições e protocolo'),
144         max_length=1, choices=POLITICA_PROTOCOLO_CHOICES, default='O')
145 
146     cronometro_discurso = models.TimeField(
147         verbose_name=_('Cronômetro do Discurso'),
148         blank=True,
149         null=True)
150 
151     cronometro_aparte = models.TimeField(
152         verbose_name=_('Cronômetro do Aparte'),
153         blank=True,
154         null=True)
155 
156     cronometro_ordem = models.TimeField(
157         verbose_name=_('Cronômetro da Ordem'),
158         blank=True,
159         null=True)
160 
161     mostrar_brasao_painel = models.BooleanField(
162         default=False,
163         verbose_name=_('Mostrar brasão da Casa no painel?'))
164 
165     class Meta:
166         verbose_name = _('Configurações da Aplicação')
167         verbose_name_plural = _('Configurações da Aplicação')
168         permissions = (
169             ('menu_sistemas', _('Renderizar Menu Sistemas')),
170             ('view_tabelas_auxiliares', _('Visualizar Tabelas Auxiliares')),
171         )
172 
173     @classmethod
174     def attr(cls, attr):
175         config = AppConfig.objects.first()
176 
177         if not config:
178             return ''
179 
180         return getattr(config, attr)
181 
182     def __str__(self):
183         return _('Configurações da Aplicação - %(id)s') % {
184             'id': self.id}
185 
186 
187 @reversion.register()
188 class TipoAutor(models.Model):
189     descricao = models.CharField(max_length=50, verbose_name=_('Descrição'))
190 
191     content_type = models.OneToOneField(
192         ContentType,
193         null=True, default=None,
194         verbose_name=_('Modelagem no SAPL'))
195 
196     class Meta:
197         ordering = ['descricao']
198         verbose_name = _('Tipo de Autor')
199         verbose_name_plural = _('Tipos de Autor')
200 
201     def __str__(self):
202         return self.descricao
203 
204 
205 @reversion.register()
206 class Autor(models.Model):
207 
208     user = models.OneToOneField(get_settings_auth_user_model(),
209                                 on_delete=models.SET_NULL,
210                                 null=True)
211 
212     tipo = models.ForeignKey(TipoAutor, verbose_name=_('Tipo do Autor'))
213 
214     content_type = models.ForeignKey(
215         ContentType,
216         blank=True, null=True, default=None)
217     object_id = models.PositiveIntegerField(
218         blank=True, null=True, default=None)
219     autor_related = GenericForeignKey('content_type', 'object_id')
220 
221     nome = models.CharField(
222         max_length=60, blank=True, verbose_name=_('Nome do Autor'))
223 
224     cargo = models.CharField(max_length=50, blank=True)
225 
226     class Meta:
227         verbose_name = _('Autor')
228         verbose_name_plural = _('Autores')
229         unique_together = (('content_type', 'object_id'), )
230         ordering = ('nome',)
231 
232     def __str__(self):
233 
234         if self.autor_related:
235             return str(self.autor_related)
236         else:
237             if str(self.cargo):
238                 return _('%(nome)s - %(cargo)s') % {
239                     'nome': self.nome, 'cargo': self.cargo}
240             else:
241                 return str(self.nome)
242         """if str(self.tipo) == 'Parlamentar' and self.parlamentar:
243             return self.parlamentar.nome_parlamentar
244         elif str(self.tipo) == 'Comissao' and self.comissao:
245             return str(self.comissao)
246         elif str(self.tipo) == 'Partido' and self.partido:
247             return str(self.partido)
248         else:
249         """
250
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/sapl/base/models.py b/sapl/base/models.py
--- a/sapl/base/models.py
+++ b/sapl/base/models.py
@@ -2,9 +2,16 @@
 from django.contrib.contenttypes.fields import GenericForeignKey
 from django.contrib.contenttypes.models import ContentType
 from django.db import models
+from django.db.models.signals import post_migrate
+from django.db.utils import DEFAULT_DB_ALIAS
 from django.utils.translation import ugettext_lazy as _
 
-from sapl.utils import UF, YES_NO_CHOICES, get_settings_auth_user_model
+from sapl.utils import (
+    UF,
+    YES_NO_CHOICES,
+    get_settings_auth_user_model,
+    models_with_gr_for_model
+    )
 
 TIPO_DOCUMENTO_ADMINISTRATIVO = (('O', _('Ostensivo')),
                                  ('R', _('Restritivo')))
@@ -247,3 +254,39 @@
             return str(self.partido)
         else:
         """
+
+
+def cria_models_tipo_autor(app_config, verbosity=2, interactive=True,
+                           using=DEFAULT_DB_ALIAS, **kwargs):
+
+    models = models_with_gr_for_model(Autor)
+
+    print("\n\033[93m\033[1m{}\033[0m".format(
+            _('Atualizando registros TipoAutor do SAPL:')))
+    for model in models:
+        content_type = ContentType.objects.get_for_model(model)
+        tipo_autor = TipoAutor.objects.filter(
+            content_type=content_type.id).exists()
+
+        if tipo_autor:
+            msg1 = "Carga de {} não efetuada.".format(
+                TipoAutor._meta.verbose_name)
+            msg2 = " Já Existe um {} {} relacionado...".format(
+                    TipoAutor._meta.verbose_name,
+                    model._meta.verbose_name)
+            msg = "  {}{}".format(msg1, msg2)
+        else:
+            novo_autor = TipoAutor()
+            novo_autor.content_type_id = content_type.id
+            novo_autor.descricao = model._meta.verbose_name
+            novo_autor.save()
+            msg1 = "Carga de {} efetuada.".format(
+                TipoAutor._meta.verbose_name)
+            msg2 = " {} {} criado...".format(
+                    TipoAutor._meta.verbose_name, content_type.model)
+            msg = "  {}{}".format(msg1, msg2)
+        print(msg)
+    # Disconecta função para evitar a chamada repetidas vezes.
+    post_migrate.disconnect(receiver=cria_models_tipo_autor)
+
+post_migrate.connect(receiver=cria_models_tipo_autor)

{"golden_diff": "diff --git a/sapl/base/models.py b/sapl/base/models.py\n--- a/sapl/base/models.py\n+++ b/sapl/base/models.py\n@@ -2,9 +2,16 @@\n from django.contrib.contenttypes.fields import GenericForeignKey\n from django.contrib.contenttypes.models import ContentType\n from django.db import models\n+from django.db.models.signals import post_migrate\n+from django.db.utils import DEFAULT_DB_ALIAS\n from django.utils.translation import ugettext_lazy as _\n \n-from sapl.utils import UF, YES_NO_CHOICES, get_settings_auth_user_model\n+from sapl.utils import (\n+    UF,\n+    YES_NO_CHOICES,\n+    get_settings_auth_user_model,\n+    models_with_gr_for_model\n+    )\n \n TIPO_DOCUMENTO_ADMINISTRATIVO = (('O', _('Ostensivo')),\n                                  ('R', _('Restritivo')))\n@@ -247,3 +254,39 @@\n             return str(self.partido)\n         else:\n         \"\"\"\n+\n+\n+def cria_models_tipo_autor(app_config, verbosity=2, interactive=True,\n+                           using=DEFAULT_DB_ALIAS, **kwargs):\n+\n+    models = models_with_gr_for_model(Autor)\n+\n+    print(\"\\n\\033[93m\\033[1m{}\\033[0m\".format(\n+            _('Atualizando registros TipoAutor do SAPL:')))\n+    for model in models:\n+        content_type = ContentType.objects.get_for_model(model)\n+        tipo_autor = TipoAutor.objects.filter(\n+            content_type=content_type.id).exists()\n+\n+        if tipo_autor:\n+            msg1 = \"Carga de {} n\u00e3o efetuada.\".format(\n+                TipoAutor._meta.verbose_name)\n+            msg2 = \" J\u00e1 Existe um {} {} relacionado...\".format(\n+                    TipoAutor._meta.verbose_name,\n+                    model._meta.verbose_name)\n+            msg = \"  {}{}\".format(msg1, msg2)\n+        else:\n+            novo_autor = TipoAutor()\n+            novo_autor.content_type_id = content_type.id\n+            novo_autor.descricao = model._meta.verbose_name\n+            novo_autor.save()\n+            msg1 = \"Carga de {} efetuada.\".format(\n+                TipoAutor._meta.verbose_name)\n+            msg2 = \" {} {} criado...\".format(\n+                    TipoAutor._meta.verbose_name, content_type.model)\n+            msg = \"  {}{}\".format(msg1, msg2)\n+        print(msg)\n+    # Disconecta fun\u00e7\u00e3o para evitar a chamada repetidas vezes.\n+    post_migrate.disconnect(receiver=cria_models_tipo_autor)\n+\n+post_migrate.connect(receiver=cria_models_tipo_autor)\n", "issue": "Alimenta\u00e7\u00e3o da tabela TipoAutor autom\u00e1tica\nPreencher a tabela Tipor autor automaticamente para que autores que possuem models relacionadas j\u00e1 estejam dispon\u00edveis no sistema.\r\nApenas a cria\u00e7\u00e3o de autores categorizados como \"Outros\" ser\u00e3o adicionados pelo usu\u00e1rio do sistema.\n", "before_files": [{"content": "import reversion\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom sapl.utils import UF, YES_NO_CHOICES, get_settings_auth_user_model\n\nTIPO_DOCUMENTO_ADMINISTRATIVO = (('O', _('Ostensivo')),\n                                 ('R', _('Restritivo')))\n\nSEQUENCIA_NUMERACAO = (('A', _('Sequencial por ano')),\n                       ('L', _('Sequencial por legislatura')),\n                       ('U', _('Sequencial \u00fanico')))\n\n\n@reversion.register()\nclass CasaLegislativa(models.Model):\n    # TODO ajustar todos os max_length !!!!\n    # cod_casa => id (pk)\n\n    codigo = models.CharField(max_length=100,\n                              blank=True,\n                              verbose_name=_('Codigo'))\n    nome = models.CharField(max_length=100, verbose_name=_('Nome'))\n    sigla = models.CharField(max_length=100, verbose_name=_('Sigla'))\n    endereco = models.CharField(max_length=100, verbose_name=_('Endere\u00e7o'))\n    cep = models.CharField(max_length=100, verbose_name=_('CEP'))\n    municipio = models.CharField(max_length=100, verbose_name=_('Munic\u00edpio'))\n    uf = models.CharField(max_length=100,\n                          choices=UF,\n                          verbose_name=_('UF'))\n    telefone = models.CharField(\n        max_length=100, blank=True, verbose_name=_('Telefone'))\n    fax = models.CharField(\n        max_length=100, blank=True, verbose_name=_('Fax'))\n    logotipo = models.ImageField(\n        blank=True,\n        upload_to='sapl/casa/logotipo/',\n        verbose_name=_('Logotipo'))\n    endereco_web = models.URLField(\n        max_length=100, blank=True, verbose_name=_('HomePage'))\n    email = models.EmailField(\n        max_length=100, blank=True, verbose_name=_('E-mail'))\n    informacao_geral = models.TextField(\n        max_length=100,\n        blank=True,\n        verbose_name=_('Informa\u00e7\u00e3o Geral'))\n\n    class Meta:\n        verbose_name = _('Casa Legislativa')\n        verbose_name_plural = _('Casa Legislativa')\n\n    def __str__(self):\n        return _('Casa Legislativa de %(municipio)s') % {\n            'municipio': self.municipio}\n\n\n@reversion.register()\nclass ProblemaMigracao(models.Model):\n    content_type = models.ForeignKey(ContentType,\n                                     verbose_name=_('Tipo de Content'))\n    object_id = models.PositiveIntegerField(verbose_name=_('ID do Objeto'))\n    content_object = GenericForeignKey('content_type', 'object_id')\n    nome_campo = models.CharField(max_length=100,\n                                  blank=True,\n                                  verbose_name=_('Nome do(s) Campo(s)'))\n    problema = models.CharField(max_length=300, verbose_name=_('Problema'))\n    descricao = models.CharField(max_length=300, verbose_name=_('Descri\u00e7\u00e3o'))\n    eh_stub = models.BooleanField(verbose_name=_('\u00c9 stub?'))\n    critico = models.BooleanField(\n        default=False, verbose_name=_('Cr\u00edtico'))\n\n    class Meta:\n        verbose_name = _('Problema na Migra\u00e7\u00e3o')\n        verbose_name_plural = _('Problemas na Migra\u00e7\u00e3o')\n\n\n@reversion.register()\nclass Constraint(models.Model):\n    nome_tabela = models.CharField(\n        max_length=50, verbose_name=_('Nome da tabela'))\n    nome_constraint = models.CharField(\n        max_length=100, verbose_name=_('Nome da constraint'))\n    nome_model = models.CharField(\n        max_length=50, verbose_name=_('Nome da model'))\n    tipo_constraint = models.CharField(\n        max_length=50, verbose_name=_('Tipo da constraint'))\n\n    class Meta:\n        verbose_name = _('Constraint removida')\n        verbose_name_plural = _('Constraints removidas')\n\n\n@reversion.register()\nclass Argumento(models.Model):\n    constraint = models.ForeignKey(Constraint)\n    argumento = models.CharField(\n        max_length=50, verbose_name=_('Argumento'))\n\n    class Meta:\n        verbose_name = _('Argumento da constraint')\n        verbose_name_plural = _('Argumentos da constraint')\n\n\n@reversion.register()\nclass AppConfig(models.Model):\n\n    POLITICA_PROTOCOLO_CHOICES = (\n        ('O', _('Sempre Gerar Protocolo')),\n        ('C', _('Perguntar se \u00e9 pra gerar protocolo ao incorporar')),\n        ('N', _('Nunca Protocolar ao incorporar uma proposi\u00e7\u00e3o')),\n    )\n\n    documentos_administrativos = models.CharField(\n        max_length=1,\n        verbose_name=_('Ostensivo/Restritivo'),\n        choices=TIPO_DOCUMENTO_ADMINISTRATIVO, default='O')\n\n    sequencia_numeracao = models.CharField(\n        max_length=1,\n        verbose_name=_('Sequ\u00eancia de numera\u00e7\u00e3o'),\n        choices=SEQUENCIA_NUMERACAO, default='A')\n\n    # TODO: a ser implementado na vers\u00e3o 3.2\n    # painel_aberto = models.BooleanField(\n    #     verbose_name=_('Painel aberto para usu\u00e1rio an\u00f4nimo'),\n    #     choices=YES_NO_CHOICES, default=False)\n\n    texto_articulado_proposicao = models.BooleanField(\n        verbose_name=_('Usar Textos Articulados para Proposi\u00e7\u00f5es'),\n        choices=YES_NO_CHOICES, default=False)\n\n    texto_articulado_materia = models.BooleanField(\n        verbose_name=_('Usar Textos Articulados para Mat\u00e9rias'),\n        choices=YES_NO_CHOICES, default=False)\n\n    texto_articulado_norma = models.BooleanField(\n        verbose_name=_('Usar Textos Articulados para Normas'),\n        choices=YES_NO_CHOICES, default=True)\n\n    proposicao_incorporacao_obrigatoria = models.CharField(\n        verbose_name=_('Regra de incorpora\u00e7\u00e3o de proposi\u00e7\u00f5es e protocolo'),\n        max_length=1, choices=POLITICA_PROTOCOLO_CHOICES, default='O')\n\n    cronometro_discurso = models.TimeField(\n        verbose_name=_('Cron\u00f4metro do Discurso'),\n        blank=True,\n        null=True)\n\n    cronometro_aparte = models.TimeField(\n        verbose_name=_('Cron\u00f4metro do Aparte'),\n        blank=True,\n        null=True)\n\n    cronometro_ordem = models.TimeField(\n        verbose_name=_('Cron\u00f4metro da Ordem'),\n        blank=True,\n        null=True)\n\n    mostrar_brasao_painel = models.BooleanField(\n        default=False,\n        verbose_name=_('Mostrar bras\u00e3o da Casa no painel?'))\n\n    class Meta:\n        verbose_name = _('Configura\u00e7\u00f5es da Aplica\u00e7\u00e3o')\n        verbose_name_plural = _('Configura\u00e7\u00f5es da Aplica\u00e7\u00e3o')\n        permissions = (\n            ('menu_sistemas', _('Renderizar Menu Sistemas')),\n            ('view_tabelas_auxiliares', _('Visualizar Tabelas Auxiliares')),\n        )\n\n    @classmethod\n    def attr(cls, attr):\n        config = AppConfig.objects.first()\n\n        if not config:\n            return ''\n\n        return getattr(config, attr)\n\n    def __str__(self):\n        return _('Configura\u00e7\u00f5es da Aplica\u00e7\u00e3o - %(id)s') % {\n            'id': self.id}\n\n\n@reversion.register()\nclass TipoAutor(models.Model):\n    descricao = models.CharField(max_length=50, verbose_name=_('Descri\u00e7\u00e3o'))\n\n    content_type = models.OneToOneField(\n        ContentType,\n        null=True, default=None,\n        verbose_name=_('Modelagem no SAPL'))\n\n    class Meta:\n        ordering = ['descricao']\n        verbose_name = _('Tipo de Autor')\n        verbose_name_plural = _('Tipos de Autor')\n\n    def __str__(self):\n        return self.descricao\n\n\n@reversion.register()\nclass Autor(models.Model):\n\n    user = models.OneToOneField(get_settings_auth_user_model(),\n                                on_delete=models.SET_NULL,\n                                null=True)\n\n    tipo = models.ForeignKey(TipoAutor, verbose_name=_('Tipo do Autor'))\n\n    content_type = models.ForeignKey(\n        ContentType,\n        blank=True, null=True, default=None)\n    object_id = models.PositiveIntegerField(\n        blank=True, null=True, default=None)\n    autor_related = GenericForeignKey('content_type', 'object_id')\n\n    nome = models.CharField(\n        max_length=60, blank=True, verbose_name=_('Nome do Autor'))\n\n    cargo = models.CharField(max_length=50, blank=True)\n\n    class Meta:\n        verbose_name = _('Autor')\n        verbose_name_plural = _('Autores')\n        unique_together = (('content_type', 'object_id'), )\n        ordering = ('nome',)\n\n    def __str__(self):\n\n        if self.autor_related:\n            return str(self.autor_related)\n        else:\n            if str(self.cargo):\n                return _('%(nome)s - %(cargo)s') % {\n                    'nome': self.nome, 'cargo': self.cargo}\n            else:\n                return str(self.nome)\n        \"\"\"if str(self.tipo) == 'Parlamentar' and self.parlamentar:\n            return self.parlamentar.nome_parlamentar\n        elif str(self.tipo) == 'Comissao' and self.comissao:\n            return str(self.comissao)\n        elif str(self.tipo) == 'Partido' and self.partido:\n            return str(self.partido)\n        else:\n        \"\"\"\n", "path": "sapl/base/models.py"}], "after_files": [{"content": "import reversion\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db import models\nfrom django.db.models.signals import post_migrate\nfrom django.db.utils import DEFAULT_DB_ALIAS\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom sapl.utils import (\n    UF,\n    YES_NO_CHOICES,\n    get_settings_auth_user_model,\n    models_with_gr_for_model\n    )\n\nTIPO_DOCUMENTO_ADMINISTRATIVO = (('O', _('Ostensivo')),\n                                 ('R', _('Restritivo')))\n\nSEQUENCIA_NUMERACAO = (('A', _('Sequencial por ano')),\n                       ('L', _('Sequencial por legislatura')),\n                       ('U', _('Sequencial \u00fanico')))\n\n\n@reversion.register()\nclass CasaLegislativa(models.Model):\n    # TODO ajustar todos os max_length !!!!\n    # cod_casa => id (pk)\n\n    codigo = models.CharField(max_length=100,\n                              blank=True,\n                              verbose_name=_('Codigo'))\n    nome = models.CharField(max_length=100, verbose_name=_('Nome'))\n    sigla = models.CharField(max_length=100, verbose_name=_('Sigla'))\n    endereco = models.CharField(max_length=100, verbose_name=_('Endere\u00e7o'))\n    cep = models.CharField(max_length=100, verbose_name=_('CEP'))\n    municipio = models.CharField(max_length=100, verbose_name=_('Munic\u00edpio'))\n    uf = models.CharField(max_length=100,\n                          choices=UF,\n                          verbose_name=_('UF'))\n    telefone = models.CharField(\n        max_length=100, blank=True, verbose_name=_('Telefone'))\n    fax = models.CharField(\n        max_length=100, blank=True, verbose_name=_('Fax'))\n    logotipo = models.ImageField(\n        blank=True,\n        upload_to='sapl/casa/logotipo/',\n        verbose_name=_('Logotipo'))\n    endereco_web = models.URLField(\n        max_length=100, blank=True, verbose_name=_('HomePage'))\n    email = models.EmailField(\n        max_length=100, blank=True, verbose_name=_('E-mail'))\n    informacao_geral = models.TextField(\n        max_length=100,\n        blank=True,\n        verbose_name=_('Informa\u00e7\u00e3o Geral'))\n\n    class Meta:\n        verbose_name = _('Casa Legislativa')\n        verbose_name_plural = _('Casa Legislativa')\n\n    def __str__(self):\n        return _('Casa Legislativa de %(municipio)s') % {\n            'municipio': self.municipio}\n\n\n@reversion.register()\nclass ProblemaMigracao(models.Model):\n    content_type = models.ForeignKey(ContentType,\n                                     verbose_name=_('Tipo de Content'))\n    object_id = models.PositiveIntegerField(verbose_name=_('ID do Objeto'))\n    content_object = GenericForeignKey('content_type', 'object_id')\n    nome_campo = models.CharField(max_length=100,\n                                  blank=True,\n                                  verbose_name=_('Nome do(s) Campo(s)'))\n    problema = models.CharField(max_length=300, verbose_name=_('Problema'))\n    descricao = models.CharField(max_length=300, verbose_name=_('Descri\u00e7\u00e3o'))\n    eh_stub = models.BooleanField(verbose_name=_('\u00c9 stub?'))\n    critico = models.BooleanField(\n        default=False, verbose_name=_('Cr\u00edtico'))\n\n    class Meta:\n        verbose_name = _('Problema na Migra\u00e7\u00e3o')\n        verbose_name_plural = _('Problemas na Migra\u00e7\u00e3o')\n\n\n@reversion.register()\nclass Constraint(models.Model):\n    nome_tabela = models.CharField(\n        max_length=50, verbose_name=_('Nome da tabela'))\n    nome_constraint = models.CharField(\n        max_length=100, verbose_name=_('Nome da constraint'))\n    nome_model = models.CharField(\n        max_length=50, verbose_name=_('Nome da model'))\n    tipo_constraint = models.CharField(\n        max_length=50, verbose_name=_('Tipo da constraint'))\n\n    class Meta:\n        verbose_name = _('Constraint removida')\n        verbose_name_plural = _('Constraints removidas')\n\n\n@reversion.register()\nclass Argumento(models.Model):\n    constraint = models.ForeignKey(Constraint)\n    argumento = models.CharField(\n        max_length=50, verbose_name=_('Argumento'))\n\n    class Meta:\n        verbose_name = _('Argumento da constraint')\n        verbose_name_plural = _('Argumentos da constraint')\n\n\n@reversion.register()\nclass AppConfig(models.Model):\n\n    POLITICA_PROTOCOLO_CHOICES = (\n        ('O', _('Sempre Gerar Protocolo')),\n        ('C', _('Perguntar se \u00e9 pra gerar protocolo ao incorporar')),\n        ('N', _('Nunca Protocolar ao incorporar uma proposi\u00e7\u00e3o')),\n    )\n\n    documentos_administrativos = models.CharField(\n        max_length=1,\n        verbose_name=_('Ostensivo/Restritivo'),\n        choices=TIPO_DOCUMENTO_ADMINISTRATIVO, default='O')\n\n    sequencia_numeracao = models.CharField(\n        max_length=1,\n        verbose_name=_('Sequ\u00eancia de numera\u00e7\u00e3o'),\n        choices=SEQUENCIA_NUMERACAO, default='A')\n\n    # TODO: a ser implementado na vers\u00e3o 3.2\n    # painel_aberto = models.BooleanField(\n    #     verbose_name=_('Painel aberto para usu\u00e1rio an\u00f4nimo'),\n    #     choices=YES_NO_CHOICES, default=False)\n\n    texto_articulado_proposicao = models.BooleanField(\n        verbose_name=_('Usar Textos Articulados para Proposi\u00e7\u00f5es'),\n        choices=YES_NO_CHOICES, default=False)\n\n    texto_articulado_materia = models.BooleanField(\n        verbose_name=_('Usar Textos Articulados para Mat\u00e9rias'),\n        choices=YES_NO_CHOICES, default=False)\n\n    texto_articulado_norma = models.BooleanField(\n        verbose_name=_('Usar Textos Articulados para Normas'),\n        choices=YES_NO_CHOICES, default=True)\n\n    proposicao_incorporacao_obrigatoria = models.CharField(\n        verbose_name=_('Regra de incorpora\u00e7\u00e3o de proposi\u00e7\u00f5es e protocolo'),\n        max_length=1, choices=POLITICA_PROTOCOLO_CHOICES, default='O')\n\n    cronometro_discurso = models.TimeField(\n        verbose_name=_('Cron\u00f4metro do Discurso'),\n        blank=True,\n        null=True)\n\n    cronometro_aparte = models.TimeField(\n        verbose_name=_('Cron\u00f4metro do Aparte'),\n        blank=True,\n        null=True)\n\n    cronometro_ordem = models.TimeField(\n        verbose_name=_('Cron\u00f4metro da Ordem'),\n        blank=True,\n        null=True)\n\n    mostrar_brasao_painel = models.BooleanField(\n        default=False,\n        verbose_name=_('Mostrar bras\u00e3o da Casa no painel?'))\n\n    class Meta:\n        verbose_name = _('Configura\u00e7\u00f5es da Aplica\u00e7\u00e3o')\n        verbose_name_plural = _('Configura\u00e7\u00f5es da Aplica\u00e7\u00e3o')\n        permissions = (\n            ('menu_sistemas', _('Renderizar Menu Sistemas')),\n            ('view_tabelas_auxiliares', _('Visualizar Tabelas Auxiliares')),\n        )\n\n    @classmethod\n    def attr(cls, attr):\n        config = AppConfig.objects.first()\n\n        if not config:\n            return ''\n\n        return getattr(config, attr)\n\n    def __str__(self):\n        return _('Configura\u00e7\u00f5es da Aplica\u00e7\u00e3o - %(id)s') % {\n            'id': self.id}\n\n\n@reversion.register()\nclass TipoAutor(models.Model):\n    descricao = models.CharField(max_length=50, verbose_name=_('Descri\u00e7\u00e3o'))\n\n    content_type = models.OneToOneField(\n        ContentType,\n        null=True, default=None,\n        verbose_name=_('Modelagem no SAPL'))\n\n    class Meta:\n        ordering = ['descricao']\n        verbose_name = _('Tipo de Autor')\n        verbose_name_plural = _('Tipos de Autor')\n\n    def __str__(self):\n        return self.descricao\n\n\n@reversion.register()\nclass Autor(models.Model):\n\n    user = models.OneToOneField(get_settings_auth_user_model(),\n                                on_delete=models.SET_NULL,\n                                null=True)\n\n    tipo = models.ForeignKey(TipoAutor, verbose_name=_('Tipo do Autor'))\n\n    content_type = models.ForeignKey(\n        ContentType,\n        blank=True, null=True, default=None)\n    object_id = models.PositiveIntegerField(\n        blank=True, null=True, default=None)\n    autor_related = GenericForeignKey('content_type', 'object_id')\n\n    nome = models.CharField(\n        max_length=60, blank=True, verbose_name=_('Nome do Autor'))\n\n    cargo = models.CharField(max_length=50, blank=True)\n\n    class Meta:\n        verbose_name = _('Autor')\n        verbose_name_plural = _('Autores')\n        unique_together = (('content_type', 'object_id'), )\n        ordering = ('nome',)\n\n    def __str__(self):\n\n        if self.autor_related:\n            return str(self.autor_related)\n        else:\n            if str(self.cargo):\n                return _('%(nome)s - %(cargo)s') % {\n                    'nome': self.nome, 'cargo': self.cargo}\n            else:\n                return str(self.nome)\n        \"\"\"if str(self.tipo) == 'Parlamentar' and self.parlamentar:\n            return self.parlamentar.nome_parlamentar\n        elif str(self.tipo) == 'Comissao' and self.comissao:\n            return str(self.comissao)\n        elif str(self.tipo) == 'Partido' and self.partido:\n            return str(self.partido)\n        else:\n        \"\"\"\n\n\ndef cria_models_tipo_autor(app_config, verbosity=2, interactive=True,\n                           using=DEFAULT_DB_ALIAS, **kwargs):\n\n    models = models_with_gr_for_model(Autor)\n\n    print(\"\\n\\033[93m\\033[1m{}\\033[0m\".format(\n            _('Atualizando registros TipoAutor do SAPL:')))\n    for model in models:\n        content_type = ContentType.objects.get_for_model(model)\n        tipo_autor = TipoAutor.objects.filter(\n            content_type=content_type.id).exists()\n\n        if tipo_autor:\n            msg1 = \"Carga de {} n\u00e3o efetuada.\".format(\n                TipoAutor._meta.verbose_name)\n            msg2 = \" J\u00e1 Existe um {} {} relacionado...\".format(\n                    TipoAutor._meta.verbose_name,\n                    model._meta.verbose_name)\n            msg = \"  {}{}\".format(msg1, msg2)\n        else:\n            novo_autor = TipoAutor()\n            novo_autor.content_type_id = content_type.id\n            novo_autor.descricao = model._meta.verbose_name\n            novo_autor.save()\n            msg1 = \"Carga de {} efetuada.\".format(\n                TipoAutor._meta.verbose_name)\n            msg2 = \" {} {} criado...\".format(\n                    TipoAutor._meta.verbose_name, content_type.model)\n            msg = \"  {}{}\".format(msg1, msg2)\n        print(msg)\n    # Disconecta fun\u00e7\u00e3o para evitar a chamada repetidas vezes.\n    post_migrate.disconnect(receiver=cria_models_tipo_autor)\n\npost_migrate.connect(receiver=cria_models_tipo_autor)\n", "path": "sapl/base/models.py"}]}