Browse Source

Ajuste de warnings do Django 1.7: ModelForms usando todos os campos

Em tese esta nao eh uma boa pratica. Deveriamos listar explicitamente todos os campos em cada caso
producao
Marcio Mazza 10 years ago
parent
commit
20197f464d
  1. 1
      sigi/apps/casas/forms.py
  2. 1
      sigi/apps/diagnosticos/forms.py
  3. 67
      sigi/apps/servicos/admin.py
  4. 3
      sigi/apps/servidores/forms.py

1
sigi/apps/casas/forms.py

@ -15,3 +15,4 @@ class CasaLegislativaForm(forms.ModelForm):
class Meta: class Meta:
model = CasaLegislativa model = CasaLegislativa
fields = '__all__'

1
sigi/apps/diagnosticos/forms.py

@ -64,6 +64,7 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
} }
class Meta: class Meta:
model = Diagnostico model = Diagnostico
fields = '__all__'
def __init__(self, data=None, category=None, *args, **kwargs): def __init__(self, data=None, category=None, *args, **kwargs):
super(BaseDynamicEntityForm, self).__init__(data, *args, **kwargs) super(BaseDynamicEntityForm, self).__init__(data, *args, **kwargs)

67
sigi/apps/servicos/admin.py

@ -19,13 +19,14 @@ class LogServicoInline(admin.StackedInline):
class ServicoFormAdmin(ModelForm): class ServicoFormAdmin(ModelForm):
class Meta: class Meta:
model = Servico model = Servico
fields = '__all__'
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(ServicoFormAdmin, self).__init__(*args, **kwargs) super(ServicoFormAdmin, self).__init__(*args, **kwargs)
self.fields['contato_tecnico'].choices = () self.fields['contato_tecnico'].choices = ()
self.fields['contato_administrativo'].choices = () self.fields['contato_administrativo'].choices = ()
if self.instance.casa_legislativa_id: if self.instance.casa_legislativa_id:
id_casa = self.instance.casa_legislativa_id id_casa = self.instance.casa_legislativa_id
elif kwargs.has_key('initial') and kwargs['initial'].has_key('id_casa'): elif kwargs.has_key('initial') and kwargs['initial'].has_key('id_casa'):
@ -33,11 +34,11 @@ class ServicoFormAdmin(ModelForm):
self.instance.casa_legislativa_id = id_casa self.instance.casa_legislativa_id = id_casa
else: else:
id_casa = None id_casa = None
if id_casa: if id_casa:
print id_casa print id_casa
casa = CasaAtendida.objects.get(pk=id_casa) casa = CasaAtendida.objects.get(pk=id_casa)
contatos = [(f.id, unicode(f)) for f in casa.funcionario_set.all()] contatos = [(f.id, unicode(f)) for f in casa.funcionario_set.all()]
self.fields['contato_tecnico'].choices = contatos self.fields['contato_tecnico'].choices = contatos
self.fields['contato_administrativo'].choices = contatos self.fields['contato_administrativo'].choices = contatos
@ -75,36 +76,36 @@ class ServicoAdmin(admin.ModelAdmin):
return obj.casa_legislativa.codigo_interlegis return obj.casa_legislativa.codigo_interlegis
get_codigo_interlegis.short_description = u'Código Interlegis' get_codigo_interlegis.short_description = u'Código Interlegis'
get_codigo_interlegis.admin_order_field = 'casa_legislativa__codigo_interlegis' get_codigo_interlegis.admin_order_field = 'casa_legislativa__codigo_interlegis'
def get_uf(self, obj): def get_uf(self, obj):
return u'%s' % (obj.casa_legislativa.municipio.uf) return u'%s' % (obj.casa_legislativa.municipio.uf)
get_uf.short_description = 'UF' get_uf.short_description = 'UF'
get_uf.admin_order_field = 'casa_legislativa__municipio__uf' get_uf.admin_order_field = 'casa_legislativa__municipio__uf'
def getUrl(self, obj): def getUrl(self, obj):
return u'<a href="%s" target="_blank">%s</a>' % (obj.url, obj.url) return u'<a href="%s" target="_blank">%s</a>' % (obj.url, obj.url)
getUrl.short_description = 'Url' getUrl.short_description = 'Url'
getUrl.allow_tags = True getUrl.allow_tags = True
def get_link_erro(self, obj): def get_link_erro(self, obj):
if not obj.erro_atualizacao: if not obj.erro_atualizacao:
return u"" return u""
url = obj.url url = obj.url
if url[-1] != '/': if url[-1] != '/':
url += '/' url += '/'
url += obj.tipo_servico.string_pesquisa url += obj.tipo_servico.string_pesquisa
return u'<a href="%s" target="_blank">%s</a>' % (url, obj.erro_atualizacao) return u'<a href="%s" target="_blank">%s</a>' % (url, obj.erro_atualizacao)
get_link_erro.allow_tags = True get_link_erro.allow_tags = True
get_link_erro.short_description = u"Erro na atualização" get_link_erro.short_description = u"Erro na atualização"
get_link_erro.admin_order_field = 'erro_atualizacao' get_link_erro.admin_order_field = 'erro_atualizacao'
def calcular_data_uso(self, request, queryset): def calcular_data_uso(self, request, queryset):
for servico in queryset: for servico in queryset:
servico.atualiza_data_uso() servico.atualiza_data_uso()
self.message_user(request, "Atualização concluída. Os sites que não responderam foram deixados com a data em branco" ) self.message_user(request, "Atualização concluída. Os sites que não responderam foram deixados com a data em branco" )
return HttpResponseRedirect('.') return HttpResponseRedirect('.')
calcular_data_uso.short_description = u"Atualizar a data do último uso do(s) serviço(s)" calcular_data_uso.short_description = u"Atualizar a data do último uso do(s) serviço(s)"
def get_actions(self, request): def get_actions(self, request):
from django.utils.datastructures import SortedDict from django.utils.datastructures import SortedDict
actions = [self.get_action(action) for action in self.actions] actions = [self.get_action(action) for action in self.actions]
@ -112,53 +113,53 @@ class ServicoAdmin(admin.ModelAdmin):
actions.sort(lambda a,b: cmp(a[2].lower(), b[2].lower())) actions.sort(lambda a,b: cmp(a[2].lower(), b[2].lower()))
actions = SortedDict([ (name, (func, name, desc)) for func, name, desc in actions ]) actions = SortedDict([ (name, (func, name, desc)) for func, name, desc in actions ])
return actions return actions
def lookup_allowed(self, lookup, value): def lookup_allowed(self, lookup, value):
return super(ServicoAdmin, self).lookup_allowed(lookup, value) or \ return super(ServicoAdmin, self).lookup_allowed(lookup, value) or \
lookup in ['casa_legislativa__municipio__uf__codigo_ibge__exact'] lookup in ['casa_legislativa__municipio__uf__codigo_ibge__exact']
def add_view(self, request, form_url='', extra_context=None): def add_view(self, request, form_url='', extra_context=None):
id_casa = request.GET.get('id_casa', None) id_casa = request.GET.get('id_casa', None)
if not id_casa: if not id_casa:
raise Http404 raise Http404
return super(ServicoAdmin, self).add_view(request, form_url, extra_context=extra_context) return super(ServicoAdmin, self).add_view(request, form_url, extra_context=extra_context)
def response_add(self, request, obj): def response_add(self, request, obj):
opts = obj._meta opts = obj._meta
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
if request.POST.has_key("_addanother"): if request.POST.has_key("_addanother"):
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
return HttpResponseRedirect(request.path + '?id_casa=%s' % (obj.casa_legislativa.id,)) return HttpResponseRedirect(request.path + '?id_casa=%s' % (obj.casa_legislativa.id,))
elif request.POST.has_key("_save"): elif request.POST.has_key("_save"):
self.message_user(request, msg) self.message_user(request, msg)
return HttpResponseRedirect(reverse('admin:servicos_casaatendida_change', args=[obj.casa_legislativa.id])) return HttpResponseRedirect(reverse('admin:servicos_casaatendida_change', args=[obj.casa_legislativa.id]))
return super(ServicoAdmin, self).response_add(request, obj) return super(ServicoAdmin, self).response_add(request, obj)
def response_change(self, request, obj): def response_change(self, request, obj):
opts = obj._meta opts = obj._meta
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
if request.POST.has_key("_addanother"): if request.POST.has_key("_addanother"):
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
return HttpResponseRedirect("../add/?id_casa=%s" % (obj.casa_legislativa.id,)) return HttpResponseRedirect("../add/?id_casa=%s" % (obj.casa_legislativa.id,))
elif request.POST.has_key("_save"): elif request.POST.has_key("_save"):
self.message_user(request, msg) self.message_user(request, msg)
return HttpResponseRedirect(reverse('admin:servicos_casaatendida_change', args=[obj.casa_legislativa.id])) return HttpResponseRedirect(reverse('admin:servicos_casaatendida_change', args=[obj.casa_legislativa.id]))
return super(ServicoAdmin, self).response_change(request, obj) return super(ServicoAdmin, self).response_change(request, obj)
def save_form(self, request, form, change): def save_form(self, request, form, change):
obj = super( ServicoAdmin, self).save_form(request, form, change) obj = super( ServicoAdmin, self).save_form(request, form, change)
if not change: if not change:
id_casa = request.GET.get('id_casa', None) id_casa = request.GET.get('id_casa', None)
if not id_casa: if not id_casa:
raise Http404 raise Http404
obj.casa_legislativa = CasaAtendida.objects.get(pk=id_casa) obj.casa_legislativa = CasaAtendida.objects.get(pk=id_casa)
@ -180,7 +181,7 @@ class CasaAtendidaAdmin(admin.ModelAdmin):
}) })
,) ,)
readonly_fields = ('nome', 'logradouro', 'bairro', 'municipio', 'cep') readonly_fields = ('nome', 'logradouro', 'bairro', 'municipio', 'cep')
inlines = (ContatosInline,) inlines = (ContatosInline,)
list_filter = ('tipo', 'servico__tipo_servico', 'municipio__uf__nome', list_filter = ('tipo', 'servico__tipo_servico', 'municipio__uf__nome',
'servico__casa_legislativa__convenio__projeto') 'servico__casa_legislativa__convenio__projeto')
search_fields = ('search_text','cnpj', 'bairro', 'logradouro', search_fields = ('search_text','cnpj', 'bairro', 'logradouro',
@ -190,13 +191,13 @@ class CasaAtendidaAdmin(admin.ModelAdmin):
def get_servicos(self, obj): def get_servicos(self, obj):
result = [] result = []
for servico in obj.servico_set.all(): for servico in obj.servico_set.all():
result.append(u"%s (%s). Contato: %s" % (servico.tipo_servico.nome, 'ativo' if servico.data_desativacao is None result.append(u"%s (%s). Contato: %s" % (servico.tipo_servico.nome, 'ativo' if servico.data_desativacao is None
else 'Desativado', servico.contato_administrativo.nome)) else 'Desativado', servico.contato_administrativo.nome))
return "<ul><li>" + "</li><li>".join(result) + "</li></ul>" return "<ul><li>" + "</li><li>".join(result) + "</li></ul>"
get_servicos.allow_tags = True get_servicos.allow_tags = True
get_servicos.short_description = u"Serviços" get_servicos.short_description = u"Serviços"
def lookup_allowed(self, lookup, value): def lookup_allowed(self, lookup, value):
return super(CasaAtendidaAdmin, self).lookup_allowed(lookup, value) or \ return super(CasaAtendidaAdmin, self).lookup_allowed(lookup, value) or \
lookup in ['municipio__uf__codigo_ibge__exact', 'servico__tipo_servico__id__exact', ] lookup in ['municipio__uf__codigo_ibge__exact', 'servico__tipo_servico__id__exact', ]
@ -208,15 +209,15 @@ class CasaAtendidaAdmin(admin.ModelAdmin):
if casa.codigo_interlegis == '': if casa.codigo_interlegis == '':
casa.gerarCodigoInterlegis() casa.gerarCodigoInterlegis()
return super(CasaAtendidaAdmin, self).change_view(request, object_id, extra_context=extra_context) return super(CasaAtendidaAdmin, self).change_view(request, object_id, extra_context=extra_context)
def has_add_permission(self, request): def has_add_permission(self, request):
return False # Nunca é permitido inserir uma nova Casa Legislativa por aqui return False # Nunca é permitido inserir uma nova Casa Legislativa por aqui
def has_delete_permission(self, request, obj=None): def has_delete_permission(self, request, obj=None):
return False # Nunca deletar casas por aqui return False # Nunca deletar casas por aqui
admin.site.register(Servico, ServicoAdmin) admin.site.register(Servico, ServicoAdmin)
admin.site.register(TipoServico, TipoServicoAdmin) admin.site.register(TipoServico, TipoServicoAdmin)
admin.site.register(CasaAtendida, CasaAtendidaAdmin) admin.site.register(CasaAtendida, CasaAtendidaAdmin)

3
sigi/apps/servidores/forms.py

@ -10,6 +10,7 @@ from sigi.apps.servidores.models import Ferias, Licenca, Funcao, Servidor
class FeriasForm(forms.ModelForm): class FeriasForm(forms.ModelForm):
class Meta: class Meta:
model = Ferias model = Ferias
fields = '__all__'
def clean(self): def clean(self):
data = self.cleaned_data data = self.cleaned_data
@ -22,6 +23,7 @@ class FeriasForm(forms.ModelForm):
class LicencaForm(forms.ModelForm): class LicencaForm(forms.ModelForm):
class Meta: class Meta:
model = Licenca model = Licenca
fields = '__all__'
def clean(self): def clean(self):
data = self.cleaned_data data = self.cleaned_data
@ -34,6 +36,7 @@ class LicencaForm(forms.ModelForm):
class FuncaoForm(forms.ModelForm): class FuncaoForm(forms.ModelForm):
class Meta: class Meta:
model = Funcao model = Funcao
fields = '__all__'
def clean(self): def clean(self):
data = self.cleaned_data data = self.cleaned_data

Loading…
Cancel
Save