We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Edição de norma: não recupera Esfera Federação
Ao editar dados de uma norma,  o campo Esfera Federação não é recuperado. A segunda figura mostra a tela de edição. O sistema acaba reclamando tal dado depois de salvar.
![captura de tela de 2018-09-19 11-14-15](https://user-images.githubusercontent.com/19169882/45759143-a4c08300-bbfd-11e8-8b91-52d5e116ba5b.png)
![captura de tela de 2018-09-19 11-14-30](https://user-images.githubusercontent.com/19169882/45759167-b013ae80-bbfd-11e8-912a-91595fa6845a.png)


--- 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/norma/views.py`
Content:
```
1 
2 import re
3 
4 from django.contrib.auth.mixins import PermissionRequiredMixin
5 from django.core.exceptions import ObjectDoesNotExist
6 from django.core.urlresolvers import reverse
7 from django.http import HttpResponse, JsonResponse
8 from django.template import RequestContext, loader
9 from django.utils import timezone
10 from django.utils.translation import ugettext_lazy as _
11 from django.views.generic import TemplateView, UpdateView
12 from django.views.generic.base import RedirectView
13 from django.views.generic.edit import FormView
14 from django_filters.views import FilterView
15 import weasyprint
16 import sapl
17 from sapl.base.models import AppConfig
18 from sapl.compilacao.views import IntegracaoTaView
19 from sapl.crud.base import (RP_DETAIL, RP_LIST, Crud, CrudAux,
20                             MasterDetailCrud, make_pagination)
21 from sapl.utils import show_results_filter_set
22 
23 from .forms import (AnexoNormaJuridicaForm, NormaFilterSet, NormaJuridicaForm,
24                     NormaPesquisaSimplesForm, NormaRelacionadaForm)
25 from .models import (AnexoNormaJuridica, AssuntoNorma, NormaJuridica, NormaRelacionada,
26                      TipoNormaJuridica, TipoVinculoNormaJuridica)
27 
28 
29 # LegislacaoCitadaCrud = Crud.build(LegislacaoCitada, '')
30 AssuntoNormaCrud = CrudAux.build(AssuntoNorma, 'assunto_norma_juridica',
31                                  list_field_names=['assunto', 'descricao'])
32 
33 
34 TipoNormaCrud = CrudAux.build(
35     TipoNormaJuridica, 'tipo_norma_juridica',
36     list_field_names=['sigla', 'descricao', 'equivalente_lexml'])
37 TipoVinculoNormaJuridicaCrud = CrudAux.build(
38     TipoVinculoNormaJuridica, '',
39     list_field_names=['sigla', 'descricao_ativa', 'descricao_passiva'])
40 
41 
42 class NormaRelacionadaCrud(MasterDetailCrud):
43     model = NormaRelacionada
44     parent_field = 'norma_principal'
45     help_topic = 'norma_juridica'
46 
47     class BaseMixin(MasterDetailCrud.BaseMixin):
48         list_field_names = ['norma_relacionada', 'tipo_vinculo']
49 
50     class CreateView(MasterDetailCrud.CreateView):
51         form_class = NormaRelacionadaForm
52 
53     class UpdateView(MasterDetailCrud.UpdateView):
54         form_class = NormaRelacionadaForm
55 
56         def get_initial(self):
57             initial = super(UpdateView, self).get_initial()
58             initial['tipo'] = self.object.norma_relacionada.tipo.id
59             initial['numero'] = self.object.norma_relacionada.numero
60             initial['ano'] = self.object.norma_relacionada.ano
61             initial['ementa'] = self.object.norma_relacionada.ementa
62             return initial
63 
64     class DetailView(MasterDetailCrud.DetailView):
65 
66         layout_key = 'NormaRelacionadaDetail'
67 
68 
69 class NormaPesquisaView(FilterView):
70     model = NormaJuridica
71     filterset_class = NormaFilterSet
72     paginate_by = 10
73 
74     def get_queryset(self):
75         qs = super().get_queryset()
76 
77         qs = qs.extra({
78             'nm_i': "CAST(regexp_replace(numero,'[^0-9]','', 'g') AS INTEGER)",
79             'norma_letra': "regexp_replace(numero,'[^a-zA-Z]','', 'g')"
80         }).order_by('-data', '-nm_i', '-norma_letra')
81 
82         return qs
83 
84     def get_context_data(self, **kwargs):
85         context = super(NormaPesquisaView, self).get_context_data(**kwargs)
86 
87         context['title'] = _('Pesquisar Norma Jurídica')
88 
89         self.filterset.form.fields['o'].label = _('Ordenação')
90 
91         qs = self.object_list
92         if 'o' in self.request.GET and not self.request.GET['o']:
93             qs = qs.order_by('-ano', 'tipo', '-numero')
94 
95         qr = self.request.GET.copy()
96 
97         if 'page' in qr:
98             del qr['page']
99 
100         paginator = context['paginator']
101         page_obj = context['page_obj']
102 
103         context['page_range'] = make_pagination(
104             page_obj.number, paginator.num_pages)
105 
106         context['filter_url'] = ('&' + qr.urlencode()) if len(qr) > 0 else ''
107 
108         context['show_results'] = show_results_filter_set(qr)
109 
110         return context
111 
112 
113 class AnexoNormaJuridicaCrud(MasterDetailCrud):
114     model = AnexoNormaJuridica
115     parent_field = 'norma'
116     help_topic = 'anexonormajuridica'
117     public = [RP_LIST, RP_DETAIL]
118 
119     class BaseMixin(MasterDetailCrud.BaseMixin):
120         list_field_names = ['id', 'anexo_arquivo', 'assunto_anexo']
121 
122     class CreateView(MasterDetailCrud.CreateView):
123         form_class = AnexoNormaJuridicaForm
124         layout_key = 'AnexoNormaJuridica'
125 
126         def get_initial(self):
127             initial = super(MasterDetailCrud.CreateView, self).get_initial()
128             initial['norma'] = NormaJuridica.objects.get(id=self.kwargs['pk'])
129             return initial
130 
131     class UpdateView(MasterDetailCrud.UpdateView):
132         form_class = AnexoNormaJuridicaForm
133         layout_key = 'AnexoNormaJuridica'
134 
135         def get_initial(self):
136             initial = super(UpdateView, self).get_initial()
137             initial['norma'] = self.object.norma
138             initial['anexo_arquivo'] = self.object.anexo_arquivo
139             initial['assunto_anexo'] = self.object.assunto_anexo
140             initial['ano'] = self.object.ano
141             return initial
142 
143     class DetailView(MasterDetailCrud.DetailView):
144         form_class = AnexoNormaJuridicaForm
145         layout_key = 'AnexoNormaJuridica'
146 
147 
148 class NormaTaView(IntegracaoTaView):
149     model = NormaJuridica
150     model_type_foreignkey = TipoNormaJuridica
151     map_fields = {
152         'data': 'data',
153         'ementa': 'ementa',
154         'observacao': 'observacao',
155         'numero': 'numero',
156         'ano': 'ano',
157         'tipo': 'tipo',
158     }
159 
160     map_funcs = {
161         'publicacao_func': True
162     }
163 
164     def get(self, request, *args, **kwargs):
165         """
166         Para manter a app compilacao isolada das outras aplicações,
167         este get foi implementado para tratar uma prerrogativa externa
168         de usuário.
169         """
170         if AppConfig.attr('texto_articulado_norma'):
171             return IntegracaoTaView.get(self, request, *args, **kwargs)
172         else:
173             return self.get_redirect_deactivated()
174 
175 
176 class NormaCrud(Crud):
177     model = NormaJuridica
178     help_topic = 'norma_juridica'
179     public = [RP_LIST, RP_DETAIL]
180 
181     class BaseMixin(Crud.BaseMixin):
182         list_field_names = ['tipo', 'numero', 'ano', 'ementa']
183 
184         list_url = ''
185 
186         @property
187         def search_url(self):
188             namespace = self.model._meta.app_config.name
189             return reverse('%s:%s' % (namespace, 'norma_pesquisa'))
190 
191     class DetailView(Crud.DetailView):
192         pass
193 
194     class DeleteView(Crud.DeleteView):
195 
196         def get_success_url(self):
197             return self.search_url
198 
199     class CreateView(Crud.CreateView):
200         form_class = NormaJuridicaForm
201 
202         @property
203         def cancel_url(self):
204             return self.search_url
205 
206         def get_initial(self):
207             try:
208                 esfera = sapl.base.models.AppConfig.objects.last(
209                 ).esfera_federacao
210                 self.initial['esfera_federacao'] = esfera
211             except:
212                 pass
213             self.initial['complemento'] = False
214             return self.initial
215 
216         layout_key = 'NormaJuridicaCreate'
217 
218     class ListView(Crud.ListView, RedirectView):
219 
220         def get_redirect_url(self, *args, **kwargs):
221             namespace = self.model._meta.app_config.name
222             return reverse('%s:%s' % (namespace, 'norma_pesquisa'))
223 
224         def get(self, request, *args, **kwargs):
225             return RedirectView.get(self, request, *args, **kwargs)
226 
227     class UpdateView(Crud.UpdateView):
228         form_class = NormaJuridicaForm
229 
230         layout_key = 'NormaJuridicaCreate'
231 
232         def get_initial(self):
233             initial = super(UpdateView, self).get_initial()
234             norma = NormaJuridica.objects.get(id=self.kwargs['pk'])
235             if norma.materia:
236                 initial['tipo_materia'] = norma.materia.tipo
237                 initial['ano_materia'] = norma.materia.ano
238                 initial['numero_materia'] = norma.materia.numero
239             return initial
240 
241 
242 def recuperar_norma(request):
243     tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])
244     numero = request.GET['numero']
245     ano = request.GET['ano']
246 
247     try:
248         norma = NormaJuridica.objects.get(tipo=tipo,
249                                           ano=ano,
250                                           numero=numero)
251         response = JsonResponse({'ementa': norma.ementa,
252                                  'id': norma.id})
253     except ObjectDoesNotExist:
254         response = JsonResponse({'ementa': '', 'id': 0})
255 
256     return response
257 
258 
259 def recuperar_numero_norma(request):
260     tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])
261     ano = request.GET.get('ano', '')
262     param = {'tipo': tipo}
263     param['ano'] = ano if ano else timezone.now().year
264     norma = NormaJuridica.objects.filter(**param).order_by(
265         'tipo', 'ano', 'numero').values_list('numero', 'ano').last()
266     if norma:
267         response = JsonResponse({'numero': int(re.sub("[^0-9].*", '', norma[0])) + 1,
268                                  'ano': norma[1]})
269     else:
270         response = JsonResponse(
271             {'numero': 1, 'ano': ano})
272 
273     return response
274 
275 
276 class ImpressosView(PermissionRequiredMixin, TemplateView):
277     template_name = 'materia/impressos/impressos.html'
278     permission_required = ('materia.can_access_impressos', )
279 
280 
281 def gerar_pdf_impressos(request, context, template_name):
282     template = loader.get_template(template_name)
283     html = template.render(RequestContext(request, context))
284     pdf = weasyprint.HTML(string=html, base_url=request.build_absolute_uri()
285                           ).write_pdf()
286 
287     response = HttpResponse(pdf, content_type='application/pdf')
288     response['Content-Disposition'] = (
289         'inline; filename="relatorio_impressos.pdf"')
290     response['Content-Transfer-Encoding'] = 'binary'
291 
292     return response
293 
294 
295 class NormaPesquisaSimplesView(PermissionRequiredMixin, FormView):
296     form_class = NormaPesquisaSimplesForm
297     template_name = 'materia/impressos/norma.html'
298     permission_required = ('materia.can_access_impressos', )
299 
300     def form_valid(self, form):
301         normas = NormaJuridica.objects.all().order_by(
302             'numero')
303         template_norma = 'materia/impressos/normas_pdf.html'
304 
305         titulo = form.cleaned_data['titulo']
306 
307         if form.cleaned_data['tipo_norma']:
308             normas = normas.filter(tipo=form.cleaned_data['tipo_norma'])
309 
310         if form.cleaned_data['data_inicial']:
311             normas = normas.filter(
312                 data__gte=form.cleaned_data['data_inicial'],
313                 data__lte=form.cleaned_data['data_final'])
314 
315         qtd_resultados = len(normas)
316         if qtd_resultados > 2000:
317             normas = normas[:2000]
318 
319         context = {'quantidade': qtd_resultados,
320                    'titulo': titulo,
321                    'normas': normas}
322 
323         return gerar_pdf_impressos(self.request, context, template_norma)
324
```
--- 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/norma/views.py b/sapl/norma/views.py
--- a/sapl/norma/views.py
+++ b/sapl/norma/views.py
@@ -236,6 +236,7 @@
                 initial['tipo_materia'] = norma.materia.tipo
                 initial['ano_materia'] = norma.materia.ano
                 initial['numero_materia'] = norma.materia.numero
+                initial['esfera_federacao'] = norma.esfera_federacao
             return initial

{"golden_diff": "diff --git a/sapl/norma/views.py b/sapl/norma/views.py\n--- a/sapl/norma/views.py\n+++ b/sapl/norma/views.py\n@@ -236,6 +236,7 @@\n                 initial['tipo_materia'] = norma.materia.tipo\n                 initial['ano_materia'] = norma.materia.ano\n                 initial['numero_materia'] = norma.materia.numero\n+                initial['esfera_federacao'] = norma.esfera_federacao\n             return initial\n", "issue": "Edi\u00e7\u00e3o de norma: n\u00e3o recupera Esfera Federa\u00e7\u00e3o\nAo editar dados de uma norma,  o campo Esfera Federa\u00e7\u00e3o n\u00e3o \u00e9 recuperado. A segunda figura mostra a tela de edi\u00e7\u00e3o. O sistema acaba reclamando tal dado depois de salvar.\r\n![captura de tela de 2018-09-19 11-14-15](https://user-images.githubusercontent.com/19169882/45759143-a4c08300-bbfd-11e8-8b91-52d5e116ba5b.png)\r\n![captura de tela de 2018-09-19 11-14-30](https://user-images.githubusercontent.com/19169882/45759167-b013ae80-bbfd-11e8-912a-91595fa6845a.png)\r\n\n", "before_files": [{"content": "\nimport re\n\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, JsonResponse\nfrom django.template import RequestContext, loader\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.generic import TemplateView, UpdateView\nfrom django.views.generic.base import RedirectView\nfrom django.views.generic.edit import FormView\nfrom django_filters.views import FilterView\nimport weasyprint\nimport sapl\nfrom sapl.base.models import AppConfig\nfrom sapl.compilacao.views import IntegracaoTaView\nfrom sapl.crud.base import (RP_DETAIL, RP_LIST, Crud, CrudAux,\n                            MasterDetailCrud, make_pagination)\nfrom sapl.utils import show_results_filter_set\n\nfrom .forms import (AnexoNormaJuridicaForm, NormaFilterSet, NormaJuridicaForm,\n                    NormaPesquisaSimplesForm, NormaRelacionadaForm)\nfrom .models import (AnexoNormaJuridica, AssuntoNorma, NormaJuridica, NormaRelacionada,\n                     TipoNormaJuridica, TipoVinculoNormaJuridica)\n\n\n# LegislacaoCitadaCrud = Crud.build(LegislacaoCitada, '')\nAssuntoNormaCrud = CrudAux.build(AssuntoNorma, 'assunto_norma_juridica',\n                                 list_field_names=['assunto', 'descricao'])\n\n\nTipoNormaCrud = CrudAux.build(\n    TipoNormaJuridica, 'tipo_norma_juridica',\n    list_field_names=['sigla', 'descricao', 'equivalente_lexml'])\nTipoVinculoNormaJuridicaCrud = CrudAux.build(\n    TipoVinculoNormaJuridica, '',\n    list_field_names=['sigla', 'descricao_ativa', 'descricao_passiva'])\n\n\nclass NormaRelacionadaCrud(MasterDetailCrud):\n    model = NormaRelacionada\n    parent_field = 'norma_principal'\n    help_topic = 'norma_juridica'\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['norma_relacionada', 'tipo_vinculo']\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = NormaRelacionadaForm\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        form_class = NormaRelacionadaForm\n\n        def get_initial(self):\n            initial = super(UpdateView, self).get_initial()\n            initial['tipo'] = self.object.norma_relacionada.tipo.id\n            initial['numero'] = self.object.norma_relacionada.numero\n            initial['ano'] = self.object.norma_relacionada.ano\n            initial['ementa'] = self.object.norma_relacionada.ementa\n            return initial\n\n    class DetailView(MasterDetailCrud.DetailView):\n\n        layout_key = 'NormaRelacionadaDetail'\n\n\nclass NormaPesquisaView(FilterView):\n    model = NormaJuridica\n    filterset_class = NormaFilterSet\n    paginate_by = 10\n\n    def get_queryset(self):\n        qs = super().get_queryset()\n\n        qs = qs.extra({\n            'nm_i': \"CAST(regexp_replace(numero,'[^0-9]','', 'g') AS INTEGER)\",\n            'norma_letra': \"regexp_replace(numero,'[^a-zA-Z]','', 'g')\"\n        }).order_by('-data', '-nm_i', '-norma_letra')\n\n        return qs\n\n    def get_context_data(self, **kwargs):\n        context = super(NormaPesquisaView, self).get_context_data(**kwargs)\n\n        context['title'] = _('Pesquisar Norma Jur\u00eddica')\n\n        self.filterset.form.fields['o'].label = _('Ordena\u00e7\u00e3o')\n\n        qs = self.object_list\n        if 'o' in self.request.GET and not self.request.GET['o']:\n            qs = qs.order_by('-ano', 'tipo', '-numero')\n\n        qr = self.request.GET.copy()\n\n        if 'page' in qr:\n            del qr['page']\n\n        paginator = context['paginator']\n        page_obj = context['page_obj']\n\n        context['page_range'] = make_pagination(\n            page_obj.number, paginator.num_pages)\n\n        context['filter_url'] = ('&' + qr.urlencode()) if len(qr) > 0 else ''\n\n        context['show_results'] = show_results_filter_set(qr)\n\n        return context\n\n\nclass AnexoNormaJuridicaCrud(MasterDetailCrud):\n    model = AnexoNormaJuridica\n    parent_field = 'norma'\n    help_topic = 'anexonormajuridica'\n    public = [RP_LIST, RP_DETAIL]\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['id', 'anexo_arquivo', 'assunto_anexo']\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = AnexoNormaJuridicaForm\n        layout_key = 'AnexoNormaJuridica'\n\n        def get_initial(self):\n            initial = super(MasterDetailCrud.CreateView, self).get_initial()\n            initial['norma'] = NormaJuridica.objects.get(id=self.kwargs['pk'])\n            return initial\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        form_class = AnexoNormaJuridicaForm\n        layout_key = 'AnexoNormaJuridica'\n\n        def get_initial(self):\n            initial = super(UpdateView, self).get_initial()\n            initial['norma'] = self.object.norma\n            initial['anexo_arquivo'] = self.object.anexo_arquivo\n            initial['assunto_anexo'] = self.object.assunto_anexo\n            initial['ano'] = self.object.ano\n            return initial\n\n    class DetailView(MasterDetailCrud.DetailView):\n        form_class = AnexoNormaJuridicaForm\n        layout_key = 'AnexoNormaJuridica'\n\n\nclass NormaTaView(IntegracaoTaView):\n    model = NormaJuridica\n    model_type_foreignkey = TipoNormaJuridica\n    map_fields = {\n        'data': 'data',\n        'ementa': 'ementa',\n        'observacao': 'observacao',\n        'numero': 'numero',\n        'ano': 'ano',\n        'tipo': 'tipo',\n    }\n\n    map_funcs = {\n        'publicacao_func': True\n    }\n\n    def get(self, request, *args, **kwargs):\n        \"\"\"\n        Para manter a app compilacao isolada das outras aplica\u00e7\u00f5es,\n        este get foi implementado para tratar uma prerrogativa externa\n        de usu\u00e1rio.\n        \"\"\"\n        if AppConfig.attr('texto_articulado_norma'):\n            return IntegracaoTaView.get(self, request, *args, **kwargs)\n        else:\n            return self.get_redirect_deactivated()\n\n\nclass NormaCrud(Crud):\n    model = NormaJuridica\n    help_topic = 'norma_juridica'\n    public = [RP_LIST, RP_DETAIL]\n\n    class BaseMixin(Crud.BaseMixin):\n        list_field_names = ['tipo', 'numero', 'ano', 'ementa']\n\n        list_url = ''\n\n        @property\n        def search_url(self):\n            namespace = self.model._meta.app_config.name\n            return reverse('%s:%s' % (namespace, 'norma_pesquisa'))\n\n    class DetailView(Crud.DetailView):\n        pass\n\n    class DeleteView(Crud.DeleteView):\n\n        def get_success_url(self):\n            return self.search_url\n\n    class CreateView(Crud.CreateView):\n        form_class = NormaJuridicaForm\n\n        @property\n        def cancel_url(self):\n            return self.search_url\n\n        def get_initial(self):\n            try:\n                esfera = sapl.base.models.AppConfig.objects.last(\n                ).esfera_federacao\n                self.initial['esfera_federacao'] = esfera\n            except:\n                pass\n            self.initial['complemento'] = False\n            return self.initial\n\n        layout_key = 'NormaJuridicaCreate'\n\n    class ListView(Crud.ListView, RedirectView):\n\n        def get_redirect_url(self, *args, **kwargs):\n            namespace = self.model._meta.app_config.name\n            return reverse('%s:%s' % (namespace, 'norma_pesquisa'))\n\n        def get(self, request, *args, **kwargs):\n            return RedirectView.get(self, request, *args, **kwargs)\n\n    class UpdateView(Crud.UpdateView):\n        form_class = NormaJuridicaForm\n\n        layout_key = 'NormaJuridicaCreate'\n\n        def get_initial(self):\n            initial = super(UpdateView, self).get_initial()\n            norma = NormaJuridica.objects.get(id=self.kwargs['pk'])\n            if norma.materia:\n                initial['tipo_materia'] = norma.materia.tipo\n                initial['ano_materia'] = norma.materia.ano\n                initial['numero_materia'] = norma.materia.numero\n            return initial\n\n\ndef recuperar_norma(request):\n    tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])\n    numero = request.GET['numero']\n    ano = request.GET['ano']\n\n    try:\n        norma = NormaJuridica.objects.get(tipo=tipo,\n                                          ano=ano,\n                                          numero=numero)\n        response = JsonResponse({'ementa': norma.ementa,\n                                 'id': norma.id})\n    except ObjectDoesNotExist:\n        response = JsonResponse({'ementa': '', 'id': 0})\n\n    return response\n\n\ndef recuperar_numero_norma(request):\n    tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])\n    ano = request.GET.get('ano', '')\n    param = {'tipo': tipo}\n    param['ano'] = ano if ano else timezone.now().year\n    norma = NormaJuridica.objects.filter(**param).order_by(\n        'tipo', 'ano', 'numero').values_list('numero', 'ano').last()\n    if norma:\n        response = JsonResponse({'numero': int(re.sub(\"[^0-9].*\", '', norma[0])) + 1,\n                                 'ano': norma[1]})\n    else:\n        response = JsonResponse(\n            {'numero': 1, 'ano': ano})\n\n    return response\n\n\nclass ImpressosView(PermissionRequiredMixin, TemplateView):\n    template_name = 'materia/impressos/impressos.html'\n    permission_required = ('materia.can_access_impressos', )\n\n\ndef gerar_pdf_impressos(request, context, template_name):\n    template = loader.get_template(template_name)\n    html = template.render(RequestContext(request, context))\n    pdf = weasyprint.HTML(string=html, base_url=request.build_absolute_uri()\n                          ).write_pdf()\n\n    response = HttpResponse(pdf, content_type='application/pdf')\n    response['Content-Disposition'] = (\n        'inline; filename=\"relatorio_impressos.pdf\"')\n    response['Content-Transfer-Encoding'] = 'binary'\n\n    return response\n\n\nclass NormaPesquisaSimplesView(PermissionRequiredMixin, FormView):\n    form_class = NormaPesquisaSimplesForm\n    template_name = 'materia/impressos/norma.html'\n    permission_required = ('materia.can_access_impressos', )\n\n    def form_valid(self, form):\n        normas = NormaJuridica.objects.all().order_by(\n            'numero')\n        template_norma = 'materia/impressos/normas_pdf.html'\n\n        titulo = form.cleaned_data['titulo']\n\n        if form.cleaned_data['tipo_norma']:\n            normas = normas.filter(tipo=form.cleaned_data['tipo_norma'])\n\n        if form.cleaned_data['data_inicial']:\n            normas = normas.filter(\n                data__gte=form.cleaned_data['data_inicial'],\n                data__lte=form.cleaned_data['data_final'])\n\n        qtd_resultados = len(normas)\n        if qtd_resultados > 2000:\n            normas = normas[:2000]\n\n        context = {'quantidade': qtd_resultados,\n                   'titulo': titulo,\n                   'normas': normas}\n\n        return gerar_pdf_impressos(self.request, context, template_norma)\n", "path": "sapl/norma/views.py"}], "after_files": [{"content": "\nimport re\n\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, JsonResponse\nfrom django.template import RequestContext, loader\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.generic import TemplateView, UpdateView\nfrom django.views.generic.base import RedirectView\nfrom django.views.generic.edit import FormView\nfrom django_filters.views import FilterView\nimport weasyprint\nimport sapl\nfrom sapl.base.models import AppConfig\nfrom sapl.compilacao.views import IntegracaoTaView\nfrom sapl.crud.base import (RP_DETAIL, RP_LIST, Crud, CrudAux,\n                            MasterDetailCrud, make_pagination)\nfrom sapl.utils import show_results_filter_set\n\nfrom .forms import (AnexoNormaJuridicaForm, NormaFilterSet, NormaJuridicaForm,\n                    NormaPesquisaSimplesForm, NormaRelacionadaForm)\nfrom .models import (AnexoNormaJuridica, AssuntoNorma, NormaJuridica, NormaRelacionada,\n                     TipoNormaJuridica, TipoVinculoNormaJuridica)\n\n\n# LegislacaoCitadaCrud = Crud.build(LegislacaoCitada, '')\nAssuntoNormaCrud = CrudAux.build(AssuntoNorma, 'assunto_norma_juridica',\n                                 list_field_names=['assunto', 'descricao'])\n\n\nTipoNormaCrud = CrudAux.build(\n    TipoNormaJuridica, 'tipo_norma_juridica',\n    list_field_names=['sigla', 'descricao', 'equivalente_lexml'])\nTipoVinculoNormaJuridicaCrud = CrudAux.build(\n    TipoVinculoNormaJuridica, '',\n    list_field_names=['sigla', 'descricao_ativa', 'descricao_passiva'])\n\n\nclass NormaRelacionadaCrud(MasterDetailCrud):\n    model = NormaRelacionada\n    parent_field = 'norma_principal'\n    help_topic = 'norma_juridica'\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['norma_relacionada', 'tipo_vinculo']\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = NormaRelacionadaForm\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        form_class = NormaRelacionadaForm\n\n        def get_initial(self):\n            initial = super(UpdateView, self).get_initial()\n            initial['tipo'] = self.object.norma_relacionada.tipo.id\n            initial['numero'] = self.object.norma_relacionada.numero\n            initial['ano'] = self.object.norma_relacionada.ano\n            initial['ementa'] = self.object.norma_relacionada.ementa\n            return initial\n\n    class DetailView(MasterDetailCrud.DetailView):\n\n        layout_key = 'NormaRelacionadaDetail'\n\n\nclass NormaPesquisaView(FilterView):\n    model = NormaJuridica\n    filterset_class = NormaFilterSet\n    paginate_by = 10\n\n    def get_queryset(self):\n        qs = super().get_queryset()\n\n        qs = qs.extra({\n            'nm_i': \"CAST(regexp_replace(numero,'[^0-9]','', 'g') AS INTEGER)\",\n            'norma_letra': \"regexp_replace(numero,'[^a-zA-Z]','', 'g')\"\n        }).order_by('-data', '-nm_i', '-norma_letra')\n\n        return qs\n\n    def get_context_data(self, **kwargs):\n        context = super(NormaPesquisaView, self).get_context_data(**kwargs)\n\n        context['title'] = _('Pesquisar Norma Jur\u00eddica')\n\n        self.filterset.form.fields['o'].label = _('Ordena\u00e7\u00e3o')\n\n        qs = self.object_list\n        if 'o' in self.request.GET and not self.request.GET['o']:\n            qs = qs.order_by('-ano', 'tipo', '-numero')\n\n        qr = self.request.GET.copy()\n\n        if 'page' in qr:\n            del qr['page']\n\n        paginator = context['paginator']\n        page_obj = context['page_obj']\n\n        context['page_range'] = make_pagination(\n            page_obj.number, paginator.num_pages)\n\n        context['filter_url'] = ('&' + qr.urlencode()) if len(qr) > 0 else ''\n\n        context['show_results'] = show_results_filter_set(qr)\n\n        return context\n\n\nclass AnexoNormaJuridicaCrud(MasterDetailCrud):\n    model = AnexoNormaJuridica\n    parent_field = 'norma'\n    help_topic = 'anexonormajuridica'\n    public = [RP_LIST, RP_DETAIL]\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['id', 'anexo_arquivo', 'assunto_anexo']\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = AnexoNormaJuridicaForm\n        layout_key = 'AnexoNormaJuridica'\n\n        def get_initial(self):\n            initial = super(MasterDetailCrud.CreateView, self).get_initial()\n            initial['norma'] = NormaJuridica.objects.get(id=self.kwargs['pk'])\n            return initial\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        form_class = AnexoNormaJuridicaForm\n        layout_key = 'AnexoNormaJuridica'\n\n        def get_initial(self):\n            initial = super(UpdateView, self).get_initial()\n            initial['norma'] = self.object.norma\n            initial['anexo_arquivo'] = self.object.anexo_arquivo\n            initial['assunto_anexo'] = self.object.assunto_anexo\n            initial['ano'] = self.object.ano\n            return initial\n\n    class DetailView(MasterDetailCrud.DetailView):\n        form_class = AnexoNormaJuridicaForm\n        layout_key = 'AnexoNormaJuridica'\n\n\nclass NormaTaView(IntegracaoTaView):\n    model = NormaJuridica\n    model_type_foreignkey = TipoNormaJuridica\n    map_fields = {\n        'data': 'data',\n        'ementa': 'ementa',\n        'observacao': 'observacao',\n        'numero': 'numero',\n        'ano': 'ano',\n        'tipo': 'tipo',\n    }\n\n    map_funcs = {\n        'publicacao_func': True\n    }\n\n    def get(self, request, *args, **kwargs):\n        \"\"\"\n        Para manter a app compilacao isolada das outras aplica\u00e7\u00f5es,\n        este get foi implementado para tratar uma prerrogativa externa\n        de usu\u00e1rio.\n        \"\"\"\n        if AppConfig.attr('texto_articulado_norma'):\n            return IntegracaoTaView.get(self, request, *args, **kwargs)\n        else:\n            return self.get_redirect_deactivated()\n\n\nclass NormaCrud(Crud):\n    model = NormaJuridica\n    help_topic = 'norma_juridica'\n    public = [RP_LIST, RP_DETAIL]\n\n    class BaseMixin(Crud.BaseMixin):\n        list_field_names = ['tipo', 'numero', 'ano', 'ementa']\n\n        list_url = ''\n\n        @property\n        def search_url(self):\n            namespace = self.model._meta.app_config.name\n            return reverse('%s:%s' % (namespace, 'norma_pesquisa'))\n\n    class DetailView(Crud.DetailView):\n        pass\n\n    class DeleteView(Crud.DeleteView):\n\n        def get_success_url(self):\n            return self.search_url\n\n    class CreateView(Crud.CreateView):\n        form_class = NormaJuridicaForm\n\n        @property\n        def cancel_url(self):\n            return self.search_url\n\n        def get_initial(self):\n            try:\n                esfera = sapl.base.models.AppConfig.objects.last(\n                ).esfera_federacao\n                self.initial['esfera_federacao'] = esfera\n            except:\n                pass\n            self.initial['complemento'] = False\n            return self.initial\n\n        layout_key = 'NormaJuridicaCreate'\n\n    class ListView(Crud.ListView, RedirectView):\n\n        def get_redirect_url(self, *args, **kwargs):\n            namespace = self.model._meta.app_config.name\n            return reverse('%s:%s' % (namespace, 'norma_pesquisa'))\n\n        def get(self, request, *args, **kwargs):\n            return RedirectView.get(self, request, *args, **kwargs)\n\n    class UpdateView(Crud.UpdateView):\n        form_class = NormaJuridicaForm\n\n        layout_key = 'NormaJuridicaCreate'\n\n        def get_initial(self):\n            initial = super(UpdateView, self).get_initial()\n            norma = NormaJuridica.objects.get(id=self.kwargs['pk'])\n            if norma.materia:\n                initial['tipo_materia'] = norma.materia.tipo\n                initial['ano_materia'] = norma.materia.ano\n                initial['numero_materia'] = norma.materia.numero\n                initial['esfera_federacao'] = norma.esfera_federacao\n            return initial\n\n\ndef recuperar_norma(request):\n    tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])\n    numero = request.GET['numero']\n    ano = request.GET['ano']\n\n    try:\n        norma = NormaJuridica.objects.get(tipo=tipo,\n                                          ano=ano,\n                                          numero=numero)\n        response = JsonResponse({'ementa': norma.ementa,\n                                 'id': norma.id})\n    except ObjectDoesNotExist:\n        response = JsonResponse({'ementa': '', 'id': 0})\n\n    return response\n\n\ndef recuperar_numero_norma(request):\n    tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])\n    ano = request.GET.get('ano', '')\n    param = {'tipo': tipo}\n    param['ano'] = ano if ano else timezone.now().year\n    norma = NormaJuridica.objects.filter(**param).order_by(\n        'tipo', 'ano', 'numero').values_list('numero', 'ano').last()\n    if norma:\n        response = JsonResponse({'numero': int(re.sub(\"[^0-9].*\", '', norma[0])) + 1,\n                                 'ano': norma[1]})\n    else:\n        response = JsonResponse(\n            {'numero': 1, 'ano': ano})\n\n    return response\n\n\nclass ImpressosView(PermissionRequiredMixin, TemplateView):\n    template_name = 'materia/impressos/impressos.html'\n    permission_required = ('materia.can_access_impressos', )\n\n\ndef gerar_pdf_impressos(request, context, template_name):\n    template = loader.get_template(template_name)\n    html = template.render(RequestContext(request, context))\n    pdf = weasyprint.HTML(string=html, base_url=request.build_absolute_uri()\n                          ).write_pdf()\n\n    response = HttpResponse(pdf, content_type='application/pdf')\n    response['Content-Disposition'] = (\n        'inline; filename=\"relatorio_impressos.pdf\"')\n    response['Content-Transfer-Encoding'] = 'binary'\n\n    return response\n\n\nclass NormaPesquisaSimplesView(PermissionRequiredMixin, FormView):\n    form_class = NormaPesquisaSimplesForm\n    template_name = 'materia/impressos/norma.html'\n    permission_required = ('materia.can_access_impressos', )\n\n    def form_valid(self, form):\n        normas = NormaJuridica.objects.all().order_by(\n            'numero')\n        template_norma = 'materia/impressos/normas_pdf.html'\n\n        titulo = form.cleaned_data['titulo']\n\n        if form.cleaned_data['tipo_norma']:\n            normas = normas.filter(tipo=form.cleaned_data['tipo_norma'])\n\n        if form.cleaned_data['data_inicial']:\n            normas = normas.filter(\n                data__gte=form.cleaned_data['data_inicial'],\n                data__lte=form.cleaned_data['data_final'])\n\n        qtd_resultados = len(normas)\n        if qtd_resultados > 2000:\n            normas = normas[:2000]\n\n        context = {'quantidade': qtd_resultados,\n                   'titulo': titulo,\n                   'normas': normas}\n\n        return gerar_pdf_impressos(self.request, context, template_norma)\n", "path": "sapl/norma/views.py"}]}