Browse Source

Criação do CRUD de Norma Juridica

pull/249/head
Eduardo Edson Batista Cordeiro Alves 9 years ago
parent
commit
ae68604669
  1. 96
      norma/forms.py
  2. 23
      norma/migrations/0011_auto_20160307_1153.py
  3. 2
      norma/models.py
  4. 14
      norma/urls.py
  5. 172
      norma/views.py
  6. 2
      templates/base.html
  7. 36
      templates/norma/list_pesquisa.html
  8. 7
      templates/norma/normajuridica_incluir.html
  9. 36
      templates/norma/normajuridica_list.html
  10. 3
      templates/norma/pesquisa.html

96
norma/forms.py

@ -24,14 +24,77 @@ class HorizontalRadioRenderer(forms.RadioSelect.renderer):
return mark_safe(u' '.join([u'%s ' % w for w in self])) return mark_safe(u' '.join([u'%s ' % w for w in self]))
class NormaJuridicaPesquisaForm(ModelForm):
periodo_inicial = forms.DateField(label=u'Período Inicial',
input_formats=['%d/%m/%Y'],
required=False,
widget=forms.DateInput(
format='%d/%m/%Y',
attrs={'class': 'dateinput'}))
periodo_final = forms.DateField(label=u'Período Final',
input_formats=['%d/%m/%Y'],
required=False,
widget=forms.DateInput(
format='%d/%m/%Y',
attrs={'class': 'dateinput'}))
publicação_inicial = forms.DateField(label=u'Publicação Inicial',
input_formats=['%d/%m/%Y'],
required=False,
widget=forms.DateInput(
format='%d/%m/%Y',
attrs={'class': 'dateinput'}))
publicação_final = forms.DateField(label=u'Publicação Final',
input_formats=['%d/%m/%Y'],
required=False,
widget=forms.DateInput(
format='%d/%m/%Y',
attrs={'class': 'dateinput'}))
class Meta:
model = NormaJuridica
fields = ['tipo',
'numero',
'ano',
'periodo_inicial',
'periodo_final',
'publicação_inicial',
'publicação_final']
def __init__(self, *args, **kwargs):
row1 = crispy_layout_mixin.to_row(
[('tipo', 12)])
row2 = crispy_layout_mixin.to_row(
[('numero', 6), ('ano', 6)])
row3 = crispy_layout_mixin.to_row(
[('periodo_inicial', 6), ('periodo_final', 6)])
row4 = crispy_layout_mixin.to_row(
[('publicação_inicial', 6), ('publicação_final', 6)])
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset('Pesquisa Norma Juridica',
row1, row2, row3, row4),
form_actions(save_label='Pesquisar')
)
super(NormaJuridicaPesquisaForm, self).__init__(*args, **kwargs)
class NormaJuridicaForm(ModelForm): class NormaJuridicaForm(ModelForm):
tipo_materia = forms.ModelChoiceField( tipo_materia = forms.ModelChoiceField(
label=_('Matéria Legislativa'), label='Matéria Legislativa',
required=False, required=False,
queryset=TipoMateriaLegislativa.objects.all(), queryset=TipoMateriaLegislativa.objects.all(),
empty_label='Selecione' empty_label='Selecione'
) )
numero_materia = forms.CharField(label='Número', required=False) numero_materia = forms.CharField(label='Número', required=False)
@ -55,30 +118,23 @@ class NormaJuridicaForm(ModelForm):
'ementa', 'ementa',
'indexacao', 'indexacao',
'observacao', 'observacao',
'texto_integral'] 'texto_integral',
]
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
row1 = crispy_layout_mixin.to_row( row1 = crispy_layout_mixin.to_row(
[('tipo', 4), [('tipo', 4), ('numero', 4), ('ano', 4)])
('numero', 4),
('ano', 4)])
row2 = crispy_layout_mixin.to_row( row2 = crispy_layout_mixin.to_row(
[('data', 4), [('data', 4), ('esfera_federacao', 4), ('complemento', 4)])
('esfera_federacao', 4),
('complemento', 4)])
row3 = crispy_layout_mixin.to_row( row3 = crispy_layout_mixin.to_row(
[('tipo_materia', 4), [('tipo_materia', 4), ('numero_materia', 4), ('ano_materia', 4)])
('numero_materia', 4),
('ano_materia', 4)])
row4 = crispy_layout_mixin.to_row( row4 = crispy_layout_mixin.to_row(
[('data_publicacao', 3), [('data_publicacao', 3), ('veiculo_publicacao', 3),
('veiculo_publicacao', 3), ('pagina_inicio_publicacao', 3), ('pagina_fim_publicacao', 3)])
('pagina_inicio_publicacao', 3),
('pagina_fim_publicacao', 3)])
row5 = crispy_layout_mixin.to_row( row5 = crispy_layout_mixin.to_row(
[('texto_integral', 12)]) [('texto_integral', 12)])
@ -94,10 +150,8 @@ class NormaJuridicaForm(ModelForm):
self.helper = FormHelper() self.helper = FormHelper()
self.helper.layout = Layout( self.helper.layout = Layout(
Fieldset(_('Cadastro de Norma Jurídica'), Fieldset('Identificação Básica',
Fieldset(_('Identificação Básica'), row1, row2, row3, row4, row5, row6, row7, row8),
row1, row2, row3, row4, row5, row6, row7, row8), form_actions()
form_actions()
)
) )
super(NormaJuridicaForm, self).__init__(*args, **kwargs) super(NormaJuridicaForm, self).__init__(*args, **kwargs)

23
norma/migrations/0011_auto_20160307_1153.py

@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-03-07 14:53
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('norma', '0010_auto_20160216_1015'),
]
operations = [
migrations.AlterField(
model_name='normajuridica',
name='data',
field=models.DateField(default=datetime.datetime(2016, 3, 7, 14, 53, 52, 206255, tzinfo=utc), verbose_name='Data'),
preserve_default=False,
),
]

2
norma/models.py

@ -81,7 +81,7 @@ class NormaJuridica(models.Model):
max_length=1, max_length=1,
verbose_name=_('Esfera Federação'), verbose_name=_('Esfera Federação'),
choices=ESFERA_FEDERACAO_CHOICES) choices=ESFERA_FEDERACAO_CHOICES)
data = models.DateField(blank=True, null=True, verbose_name=_('Data')) data = models.DateField(verbose_name=_('Data'))
data_publicacao = models.DateField( data_publicacao = models.DateField(
blank=True, null=True, verbose_name=_('Data Publicação')) blank=True, null=True, verbose_name=_('Data Publicação'))
veiculo_publicacao = models.CharField( veiculo_publicacao = models.CharField(

14
norma/urls.py

@ -1,7 +1,9 @@
from django.conf.urls import include, url from django.conf.urls import include, url
from norma.views import (NormaIncluirView, NormaTaView, assunto_norma_crud, from norma.views import (NormaEditView, NormaIncluirView, NormaPesquisaView,
norma_temporario_crud, tipo_norma_crud) NormaTaView, PesquisaNormaListView,
assunto_norma_crud, norma_temporario_crud,
tipo_norma_crud)
# norma_url_patterns = norma_crud.urlpatterns + [] # norma_url_patterns = norma_crud.urlpatterns + []
norma_url_patterns = norma_temporario_crud.urlpatterns + [ norma_url_patterns = norma_temporario_crud.urlpatterns + [
@ -17,5 +19,11 @@ urlpatterns = [
url(r'^sistema/norma/tipo/', include(tipo_norma_crud.urls)), url(r'^sistema/norma/tipo/', include(tipo_norma_crud.urls)),
url(r'^sistema/norma/assunto/', include(assunto_norma_crud.urls)), url(r'^sistema/norma/assunto/', include(assunto_norma_crud.urls)),
url(r'^norma/incluir', NormaIncluirView.as_view(), name='norma-incluir'), url(r'^norma/incluir$', NormaIncluirView.as_view(), name='norma_incluir'),
url(r'^norma/(?P<pk>[0-9]+)/editar$',
NormaEditView.as_view(), name='norma_editar'),
url(r'^norma/pesquisa$',
NormaPesquisaView.as_view(), name='norma_pesquisa'),
url(r'^norma/pesquisa-resultado$',
PesquisaNormaListView.as_view(), name='list_pesquisa_norma'),
] ]

172
norma/views.py

@ -2,16 +2,20 @@ from datetime import datetime
from re import sub from re import sub
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.utils.html import strip_tags from django.utils.html import strip_tags
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, ListView
from django.views.generic.edit import FormMixin from django.views.generic.edit import FormMixin
from vanilla.views import GenericView from vanilla.views import GenericView
from compilacao.views import IntegracaoTaView from compilacao.views import IntegracaoTaView
from crud import Crud from crud import Crud, make_pagination
from materia.models import MateriaLegislativa, TipoMateriaLegislativa from materia.models import MateriaLegislativa, TipoMateriaLegislativa
from .forms import NormaJuridicaForm from .forms import NormaJuridicaForm, NormaJuridicaPesquisaForm
from .models import (AssuntoNorma, LegislacaoCitada, NormaJuridica, from .models import (AssuntoNorma, LegislacaoCitada, NormaJuridica,
TipoNormaJuridica) TipoNormaJuridica)
@ -22,54 +26,172 @@ norma_temporario_crud = Crud(NormaJuridica, 'normajuridica')
legislacao_citada_crud = Crud(LegislacaoCitada, '') legislacao_citada_crud = Crud(LegislacaoCitada, '')
class NormaIncluirView(FormMixin, GenericView): class NormaPesquisaView(GenericView):
template_name = "norma/pesquisa.html"
def get_success_url(self):
return reverse('normajuridica:norma_pesquisa')
def get(self, request, *args, **kwargs):
form = NormaJuridicaPesquisaForm()
return self.render_to_response({'form': form})
def post(self, request, *args, **kwargs):
form = NormaJuridicaPesquisaForm(request.POST)
if form.data['tipo']:
kwargs['tipo'] = form.data['tipo']
if form.data['numero']:
kwargs['numero'] = form.data['numero']
if form.data['ano']:
kwargs['ano'] = form.data['ano']
if form.data['periodo_inicial'] and form.data['periodo_final']:
kwargs['periodo_inicial'] = form.data['periodo_inicial']
kwargs['periodo_final'] = form.data['periodo_final']
if form.data['publicação_inicial'] and form.data['publicação_final']:
kwargs['publicação_inicial'] = form.data['publicação_inicial']
kwargs['publicação_final'] = form.data['publicação_final']
request.session['kwargs'] = kwargs
return redirect('list_pesquisa_norma')
class PesquisaNormaListView(ListView):
template_name = 'norma/list_pesquisa.html'
model = NormaJuridica
paginate_by = 10
def get_queryset(self):
kwargs = self.request.session['kwargs']
normas = NormaJuridica.objects.all().order_by('-ano', '-numero')
if 'periodo_inicial' and 'publicacao_inicial' in kwargs:
periodo_inicial = datetime.strptime(
kwargs['periodo_inicial'],
'%d/%m/%Y').strftime('%Y-%m-%d')
periodo_final = datetime.strptime(
kwargs['periodo_final'],
'%d/%m/%Y').strftime('%Y-%m-%d')
publicação_inicial = datetime.strptime(
kwargs['publicação_inicial'],
'%d/%m/%Y').strftime('%Y-%m-%d')
publicação_final = datetime.strptime(
kwargs['publicação_final'],
'%d/%m/%Y').strftime('%Y-%m-%d')
normas = normas.filter(
data__range=(periodo_inicial, periodo_final),
data_publicacao__range=(publicação_inicial, publicação_final))
if 'periodo_inicial' in kwargs:
inicial = datetime.strptime(kwargs['periodo_inicial'],
'%d/%m/%Y').strftime('%Y-%m-%d')
final = datetime.strptime(kwargs['periodo_inicial'],
'%d/%m/%Y').strftime('%Y-%m-%d')
normas = normas.filter(data__range=(inicial, final))
if 'publicação_inicial' in kwargs:
inicial = datetime.strptime(kwargs['publicação_inicial'],
'%d/%m/%Y').strftime('%Y-%m-%d')
final = datetime.strptime(kwargs['publicação_final'],
'%d/%m/%Y').strftime('%Y-%m-%d')
normas = normas.filter(data_publicacao__range=(inicial, final))
if 'tipo' in kwargs:
normas = normas.filter(tipo=kwargs['tipo'])
if 'numero' in kwargs:
normas = normas.filter(numero=kwargs['numero'])
if 'ano' in kwargs:
normas = normas.filter(ano=kwargs['ano'])
return normas
def get_context_data(self, **kwargs):
context = super(PesquisaNormaListView, self).get_context_data(
**kwargs)
paginator = context['paginator']
page_obj = context['page_obj']
context['page_range'] = make_pagination(
page_obj.number, paginator.num_pages)
return context
class NormaIncluirView(CreateView):
template_name = "norma/normajuridica_incluir.html" template_name = "norma/normajuridica_incluir.html"
form_class = NormaJuridicaForm
def get_success_url(self): def get_success_url(self):
return '/norma/' return reverse('normajuridica:list')
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
form = NormaJuridicaForm() form = NormaJuridicaForm()
return self.render_to_response({'form': form}) return self.render_to_response({'form': form})
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
form = NormaJuridicaForm(request.POST or None) form = self.get_form()
if form.is_valid(): if form.is_valid():
norma = form.save(commit=False) norma = form.save(commit=False)
if form.cleaned_data['tipo_materia']: if form.cleaned_data['tipo_materia']:
tipo = TipoMateriaLegislativa.objects.get(
id=form.cleaned_data['tipo_materia'])
try: try:
materia = MateriaLegislativa.objects.get( materia = MateriaLegislativa.objects.get(
tipo=tipo, tipo_id=form.cleaned_data['tipo_materia'],
numero=form.cleaned_data['numero'], numero=form.cleaned_data['numero_materia'],
ano=form.cleaned_data['ano']) ano=form.cleaned_data['ano_materia'])
except ObjectDoesNotExist: except ObjectDoesNotExist:
return self.render_to_response( msg = 'Matéria adicionada não existe!'
{'form': form, messages.add_message(request, messages.INFO, msg)
'error': _('Matéria adicionada não existe!')}) return self.render_to_response({'form': form})
else: else:
norma.materia = materia norma.materia = materia
norma.timestamp = datetime.now()
norma.save()
return HttpResponseRedirect(self.get_success_url())
else:
return self.render_to_response({'form': form})
if form.cleaned_data['indexacao']: class NormaEditView(CreateView):
norma.indexacao = sub( template_name = "norma/normajuridica_incluir.html"
'&nbsp;', ' ', strip_tags(form.cleaned_data['indexacao'])) form_class = NormaJuridicaForm
if form.cleaned_data['observacao']: def get(self, request, *args, **kwargs):
norma.observacao = sub( norma = NormaJuridica.objects.get(id=self.kwargs['pk'])
'&nbsp;', ' ', strip_tags(form.cleaned_data['observacao'])) form = NormaJuridicaForm(instance=norma)
return self.render_to_response({'form': form})
if 'texto_integral' in request.FILES: def post(self, request, *args, **kwargs):
norma.texto_integral = request.FILES['texto_integral'] norma = NormaJuridica.objects.get(id=self.kwargs['pk'])
form = NormaJuridicaForm(instance=norma, data=request.POST)
norma.ementa = sub( if form.is_valid():
'&nbsp;', ' ', strip_tags(form.cleaned_data['ementa'])) if form.data['tipo_materia']:
try:
materia = MateriaLegislativa.objects.get(
tipo_id=form.data['tipo_materia'],
numero=form.data['numero_materia'],
ano=form.data['ano_materia'])
except ObjectDoesNotExist:
msg = 'Matéria adicionada não existe!'
messages.add_message(request, messages.INFO, msg)
return self.render_to_response({'form': form})
else:
norma.materia = materia
norma = form.save(commit=False)
norma.timestamp = datetime.now() norma.timestamp = datetime.now()
norma.save() norma.save()
return self.form_valid(form) return HttpResponseRedirect(self.get_success_url())
else: else:
return self.form_invalid(form) return self.render_to_response({'form': form})
def get_success_url(self):
return reverse('normajuridica:list')
class NormaTaView(IntegracaoTaView): class NormaTaView(IntegracaoTaView):

2
templates/base.html

@ -81,7 +81,7 @@
<li class="dropdown"> <li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{% trans 'Legislação'%} <span class="caret"></span></a> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{% trans 'Legislação'%} <span class="caret"></span></a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li class="nav__sub-item"><a class="nav__sub-link" href="{% url 'normajuridica:list'%}">{% trans 'Normas Jurídicas'%}</a></li> <li class="nav__sub-item"><a class="nav__sub-link" href="{% url 'norma_pesquisa'%}">{% trans 'Pesquisar Normas Jurídicas'%}</a></li>
<!-- <li class="nav__sub-item"><a class="nav__sub-link" href="#">Índice de Assuntos</a></li> --> <!-- <li class="nav__sub-item"><a class="nav__sub-link" href="#">Índice de Assuntos</a></li> -->
</ul> </ul>
</li> </li>

36
templates/norma/list_pesquisa.html

@ -0,0 +1,36 @@
{% extends "crud/detail.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block actions %}{% endblock %}
{% block detail_content %}
<div class="actions btn-group pull-right" role="group">
<a href="{% url 'norma_incluir' %}" class="btn btn-default">Adicionar Norma Jurídica</a>
</div>
<br /><br /><br />
{% if object_list %}
<table class="table table-striped table-bordered">
<thead class="thead-default">
<tr>
<th>Tipo da Norma Juridica</th>
<th>Número</th>
<th>Ano</th>
<th>Data</th>
<th>Ementa</th>
</tr>
</thead>
{% for obj in object_list %}
<tr>
<td><a href="{% url 'normajuridica:detail' obj.id %}">{{obj.tipo}}</a></td>
<td>{{obj.numero}}</td>
<td>{{obj.ano}}</td>
<td>{{obj.data}}</td>
<td>{{obj.ementa|safe}}</td>
</tr>
{% endfor %}
</table>
{% include "paginacao.html" %}
{% else %}
<h2>Nenhum Registro recuperado</h2>
{% endif %}
{% endblock detail_content %}

7
templates/norma/normajuridica_incluir.html

@ -1,8 +1,3 @@
{% extends "norma/normajuridica_detail.html" %} {% extends "crud/form.html" %}
{% load i18n %} {% load i18n %}
{% load crispy_forms_tags %} {% load crispy_forms_tags %}
{% block detail_content %}
{% if error %} <h5 align="center"><font color="#FF0000">{{ error }}</font></h5> {% endif %}
{% crispy form %}
{% endblock %}

36
templates/norma/normajuridica_list.html

@ -0,0 +1,36 @@
{% extends "crud/list.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block base_content %}
<div class="actions btn-group pull-right" role="group">
<a href="{% url 'norma_incluir' %}" class="btn btn-default">
{% blocktrans with verbose_name=view.verbose_name %} Adicionar {{ verbose_name }} {% endblocktrans %}
</a>
</div>
<br /><br /><br />
{% if object_list %}
<table class="table table-striped table-bordered">
<thead class="thead-default">
<tr>
<th>Tipo da Norma Juridica</th>
<th>Número</th>
<th>Ano</th>
<th>Data</th>
<th>Ementa</th>
</tr>
</thead>
{% for obj in object_list %}
<tr>
<td><a href="{% url 'normajuridica:detail' obj.id %}">{{obj.tipo}}</a></td>
<td>{{obj.numero}}</td>
<td>{{obj.ano}}</td>
<td>{{obj.data}}</td>
<td>{{obj.ementa|safe}}</td>
</tr>
{% endfor %}
</table>
{% include "paginacao.html" %}
{% else %}
<h2>Nenhum Registro recuperado</h2>
{% endif %}
{% endblock %}

3
templates/norma/pesquisa.html

@ -0,0 +1,3 @@
{% extends "crud/form.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
Loading…
Cancel
Save