/common/admin.py
Python | 357 lines | 350 code | 4 blank | 3 comment | 0 complexity | 81ae44d937f0421156d2e627f3ca405a MD5 | raw file
- # -*- coding: utf-8 -*-
- """ Common Admin """
- from django.contrib import admin
- from django.conf.urls.defaults import patterns, url
- from django.core.exceptions import ObjectDoesNotExist
- from django.shortcuts import get_object_or_404, render_to_response
- from django.template import RequestContext
- from django.views.decorators.csrf import csrf_exempt
- from common.forms import AdminObservacionForm, AdminFonoFormSet, \
- AdminDeleteTelefonoForm, AdminDireccionForm
- from common.models import Observacion, TipoTelefono, Telefono, Departamento, \
- Provincia, Distrito, Direccion
- from common.utils import json_response
- class ObservacionAdmin(admin.ModelAdmin):
- """ admin model that manages the observations """
- def get_urls(self):
- urls = super(self.__class__, self).get_urls()
- my_urls = patterns(
- '',
- url((r'^add_observacion/(?P<app>\w+)/(?P<model>\w+)/'
- '(?P<object_id>\d+)?/$'),
- self.admin_site.admin_view(self.add_observacion),
- name='admin_common_add_observacion'),
- url(r'^ajax_edit_observacion/$',
- self.admin_site.admin_view(self.ajax_edit_observacion),
- name='admin_common_ajax_edit_observacion'),
- url(r'^ajax_delete_observacion/$',
- self.admin_site.admin_view(self.ajax_delete_observacion),
- name='admin_common_ajax_delete_observacion'),
- )
- return my_urls + urls
- def add_observacion(self, request, app, model, object_id):
- """ handles the proccess of observation addition """
- exec 'from %s.models import %s' % (app, model)
- form = AdminObservacionForm()
- add_success = False
- obs = get_object_or_404(eval(model), id=object_id)
- if request.method == 'POST':
- form = AdminObservacionForm(request.POST)
- if form.is_valid():
- form = form.saveTo(obs.observaciones)
- add_success = True
- return render_to_response(
- 'admin/common/observacion/add_observacion.html',
- {'form': form, 'obsList': obs.observaciones.all(),
- 'add_success': add_success,
- 'is_popup': True},
- context_instance=RequestContext(request))
- def ajax_edit_observacion(self, request):
- """ returns the observation data """
- if request.method == 'GET':
- try:
- obs = Observacion.objects.get(id=request.GET['id'])
- data = {'id': obs.id,
- 'texto': obs.texto,
- 'tipo': obs.tipo}
- except ObjectDoesNotExist:
- data = {'response': 'error'}
- return json_response(data)
- return None
- @csrf_exempt
- def ajax_delete_observacion(self, request):
- """ Deletes the observation with the id = 'id' """
- if request.method == 'POST':
- try:
- obs = Observacion.objects.get(id=request.POST['id'])
- except ObjectDoesNotExist:
- data = {'response': 'error'}
- else:
- obs.delete()
- data = {'response': 'ok'}
- return json_response(data)
- return None
- class TipoTelefonoAdmin(admin.ModelAdmin):
- """ admin model that manages the telephone types """
- pass
- class TelefonoAdmin(admin.ModelAdmin):
- """ admin model that manages the telephones """
- def get_urls(self):
- urls = super(self.__class__, self).get_urls()
- my_urls = patterns(
- '',
- url((r'^add_telefono/(?P<app>\w+)/(?P<model>\w+)/'
- '(?P<object_id>\d+)?/$'),
- self.admin_site.admin_view(self.add_telefonos),
- name='admin_common_add_telefonos'),
- )
- return my_urls + urls
- def add_telefonos(self, request, app, model, object_id):
- """
- handles the proccess of telephone additions
- """
- fono_list = ''
- num_fonos = 0
- exec 'from %s.models import %s' % (app, model)
- formset = AdminFonoFormSet()
- add_success = del_fono = False
- if object_id:
- obj = get_object_or_404(eval(model), id=object_id)
- fono_list = obj.telefonos.iterator()
- num_fonos = obj.telefonos.count()
- if request.method == 'POST':
- if '_save' in request.POST:
- formset = AdminFonoFormSet(request.POST)
- if formset.is_valid():
- formset.save(obj)
- formset = AdminFonoFormSet()
- add_success = True
- fono_list = obj.telefonos.iterator()
- num_fonos = obj.telefonos.count()
- else:
- del_form = AdminDeleteTelefonoForm(request.POST)
- if del_form.is_valid():
- del_form.save()
- del_fono = True
- fono_list = obj.telefonos.iterator()
- num_fonos = obj.telefonos.count()
- return render_to_response('admin/common/telefono/add_telefono.html',
- {'formset': formset, 'fono_list': fono_list,
- 'add_success': add_success,
- 'num_fonos': num_fonos,
- 'del_fono': del_fono, 'is_popup': True, },
- context_instance=RequestContext(request))
- class DepartamentoAdmin(admin.ModelAdmin):
- """ admin model that manages the departments """
- pass
- class ProvinciaAdmin(admin.ModelAdmin):
- """ admin model that manages the provinces """
- def get_urls(self):
- urls = super(self.__class__, self).get_urls()
- my_urls = patterns(
- '',
- url(r'^ajax_get_provincias/$',
- self.admin_site.admin_view(self.ajax_get_provincias),
- name='admin_common_ajax_get_provincias'),
- url(r'^ajax_update_provincia_selection/$',
- self.admin_site.admin_view(
- self.ajax_update_provincia_selection),
- name='admin_common_ajax_update_provincia_selection'),
- )
- return my_urls + urls
- def ajax_get_provincias(self, request):
- """
- Gets all the provinces from the selected department and returns
- them wrapped with html code for a select tag.
- """
- if request.method == 'GET':
- try:
- department = Departamento.objects.get(
- id=request.GET['id'])
- except ObjectDoesNotExist:
- data = {'response': 'error'}
- else:
- queryset = department.provincia_set.all()
- data = '<option selected="selected" value="">\
- ---------</option>'
- data += ''.join('<option value="%d">%s\
- </option>' % (
- provincia.id, provincia.nombre) for provincia in queryset)
- data = {'html_code': data}
- return json_response(data)
- return None
- def ajax_update_provincia_selection(self, request):
- """
- return all the provinces corresponding to the deparment of the
- selected province, all of them wrapped in html for a select tag and
- with the selected province with its corresponding selected attribute
- """
- if request.method == 'GET':
- try:
- prov = Provincia.objects.get(id=request.GET['id'])
- except ObjectDoesNotExist:
- data = {'response': 'error'}
- else:
- prov_list = prov.departamento.provincia_set.all()
- data = '<option value="">---------</option>'
- for provincia in prov_list:
- if provincia.id == prov.id:
- data += '<option selected="selected" value="%d">%s\
- </option>' % (provincia.id, provincia.nombre)
- else:
- data += '<option value="%d">%s\
- </option>' % (provincia.id, provincia.nombre)
- data = {'html_code': data}
- return json_response(data)
- return None
- class DistritoAdmin(admin.ModelAdmin):
- """ admin model that manages the districts """
- def get_urls(self):
- urls = super(self.__class__, self).get_urls()
- my_urls = patterns(
- '',
- url(r'^ajax_get_distritos/$',
- self.admin_site.admin_view(self.ajax_get_distritos),
- name='admin_common_ajax_get_distritos'),
- url(r'^ajax_update_distrito_selection/$',
- self.admin_site.admin_view(
- self.ajax_update_distrito_selection),
- name='admin_common_ajax_update_distrito_selection'),
- )
- return my_urls + urls
- def ajax_get_distritos(self, request):
- """
- Gets all the districts from the selected province and returns
- them wrapped with html code for a select tag.
- """
- if request.method == 'GET':
- try:
- province = Provincia.objects.get(
- id=request.GET['id'])
- except ObjectDoesNotExist:
- data = {'response': 'error'}
- else:
- queryset = province.distrito_set.all()
- data = '<option selected="selected" value="">\
- ---------</option>'
- data += ''.join('<option value="%d">%s\
- </option>' % (
- district.id, district.nombre) for district in queryset)
- data = {'html_code': data}
- return json_response(data)
- return None
- def ajax_update_distrito_selection(self, request):
- """
- return all the districts corresponding to the province of the
- selected district, all of them wrapped in html for a select tag and
- with the selected district with its corresponding selected attribute
- """
- if request.method == 'GET':
- try:
- dist = Distrito.objects.get(id=request.GET['id'])
- except ObjectDoesNotExist:
- data = {'response': 'error'}
- else:
- dist_list = dist.provincia.distrito_set.all()
- data = '<option value="">---------</option>'
- for distrito in dist_list:
- if distrito.id == dist.id:
- data += '<option selected="selected" value="%d">%s\
- </option>' % (distrito.id, distrito.nombre)
- else:
- data += '<option value="%d">%s\
- </option>' % (distrito.id, distrito.nombre)
- data = {'html_code': data}
- return json_response(data)
- return None
- class DireccionAdmin(admin.ModelAdmin):
- """ admin model that manages the addresses """
- def get_urls(self):
- urls = super(self.__class__, self).get_urls()
- my_urls = patterns(
- '',
- url((r'^add_direccion/(?P<app>\w+)/(?P<model>\w+)/'
- '(?P<object_id>\d+)?/$'),
- self.admin_site.admin_view(self.add_direccion),
- name='admin_common_add_direccion'),
- url(r'^ajax_edit_direccion/$',
- self.admin_site.admin_view(self.ajax_edit_direccion),
- name='admin_common_ajax_edit_direccion'),
- url(r'^ajax_delete_direccion/$',
- self.admin_site.admin_view(self.ajax_delete_direccion),
- name='admin_common_ajax_delete_direccion'),
- )
- return my_urls + urls
- def add_direccion(self, request, app, model, object_id):
- """ View that handles the proccess of address addition """
- form = AdminDireccionForm()
- add_success = False
- exec 'from %s.models import %s' % (app, model)
- obj = get_object_or_404(eval(model), id=object_id)
- if request.method == 'POST':
- form = AdminDireccionForm(request.POST)
- if form.is_valid():
- form = form.saveTo(obj.direcciones)
- add_success = True
- return render_to_response(
- 'admin/common/direccion/add_direccion.html',
- {'form': form, 'dir_list': obj.direcciones.all(),
- 'add_success': add_success,
- 'is_popup': True},
- context_instance=RequestContext(request))
- def ajax_edit_direccion(self, request):
- """ returns the address data """
- if request.method == 'GET':
- try:
- obj = Direccion.objects.get(id=request.GET['id'])
- except ObjectDoesNotExist:
- data = {'response': 'error'}
- else:
- data = {'id': obj.id,
- 'texto': obj.texto,
- 'departamento': obj.departamento.id,
- 'provincia': obj.provincia.id,
- 'distrito': obj.distrito.id}
- return json_response(data)
- return None
- @csrf_exempt
- def ajax_delete_direccion(self, request):
- """ deletes the direccion with the id received """
- if request.method == 'POST':
- try:
- obj = Direccion.objects.get(id=request.POST['id'])
- except ObjectDoesNotExist:
- data = {'response': 'error'}
- else:
- # a tweak to make it work with personal and clients
- # personal = obj.personal_personal_related.all()[0]
- personal = obj.personal_personal_related.all() or \
- obj.clientes_cliente_related.all()
- personal = personal[0]
- if personal.direcciones.count() > 1:
- obj.delete()
- data = {'response': 'ok'}
- else:
- data = {'response': 'last address'}
- return json_response(data)
- return None
- admin.site.register(Observacion, ObservacionAdmin)
- admin.site.register(TipoTelefono, TipoTelefonoAdmin)
- admin.site.register(Telefono, TelefonoAdmin)
- admin.site.register(Departamento, DepartamentoAdmin)
- admin.site.register(Provincia, ProvinciaAdmin)
- admin.site.register(Distrito, DistritoAdmin)
- admin.site.register(Direccion, DireccionAdmin)