PageRenderTime 80ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/common/admin.py

https://bitbucket.org/giussepi/resinmetal
Python | 357 lines | 350 code | 4 blank | 3 comment | 0 complexity | 81ae44d937f0421156d2e627f3ca405a MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. """ Common Admin """
  3. from django.contrib import admin
  4. from django.conf.urls.defaults import patterns, url
  5. from django.core.exceptions import ObjectDoesNotExist
  6. from django.shortcuts import get_object_or_404, render_to_response
  7. from django.template import RequestContext
  8. from django.views.decorators.csrf import csrf_exempt
  9. from common.forms import AdminObservacionForm, AdminFonoFormSet, \
  10. AdminDeleteTelefonoForm, AdminDireccionForm
  11. from common.models import Observacion, TipoTelefono, Telefono, Departamento, \
  12. Provincia, Distrito, Direccion
  13. from common.utils import json_response
  14. class ObservacionAdmin(admin.ModelAdmin):
  15. """ admin model that manages the observations """
  16. def get_urls(self):
  17. urls = super(self.__class__, self).get_urls()
  18. my_urls = patterns(
  19. '',
  20. url((r'^add_observacion/(?P<app>\w+)/(?P<model>\w+)/'
  21. '(?P<object_id>\d+)?/$'),
  22. self.admin_site.admin_view(self.add_observacion),
  23. name='admin_common_add_observacion'),
  24. url(r'^ajax_edit_observacion/$',
  25. self.admin_site.admin_view(self.ajax_edit_observacion),
  26. name='admin_common_ajax_edit_observacion'),
  27. url(r'^ajax_delete_observacion/$',
  28. self.admin_site.admin_view(self.ajax_delete_observacion),
  29. name='admin_common_ajax_delete_observacion'),
  30. )
  31. return my_urls + urls
  32. def add_observacion(self, request, app, model, object_id):
  33. """ handles the proccess of observation addition """
  34. exec 'from %s.models import %s' % (app, model)
  35. form = AdminObservacionForm()
  36. add_success = False
  37. obs = get_object_or_404(eval(model), id=object_id)
  38. if request.method == 'POST':
  39. form = AdminObservacionForm(request.POST)
  40. if form.is_valid():
  41. form = form.saveTo(obs.observaciones)
  42. add_success = True
  43. return render_to_response(
  44. 'admin/common/observacion/add_observacion.html',
  45. {'form': form, 'obsList': obs.observaciones.all(),
  46. 'add_success': add_success,
  47. 'is_popup': True},
  48. context_instance=RequestContext(request))
  49. def ajax_edit_observacion(self, request):
  50. """ returns the observation data """
  51. if request.method == 'GET':
  52. try:
  53. obs = Observacion.objects.get(id=request.GET['id'])
  54. data = {'id': obs.id,
  55. 'texto': obs.texto,
  56. 'tipo': obs.tipo}
  57. except ObjectDoesNotExist:
  58. data = {'response': 'error'}
  59. return json_response(data)
  60. return None
  61. @csrf_exempt
  62. def ajax_delete_observacion(self, request):
  63. """ Deletes the observation with the id = 'id' """
  64. if request.method == 'POST':
  65. try:
  66. obs = Observacion.objects.get(id=request.POST['id'])
  67. except ObjectDoesNotExist:
  68. data = {'response': 'error'}
  69. else:
  70. obs.delete()
  71. data = {'response': 'ok'}
  72. return json_response(data)
  73. return None
  74. class TipoTelefonoAdmin(admin.ModelAdmin):
  75. """ admin model that manages the telephone types """
  76. pass
  77. class TelefonoAdmin(admin.ModelAdmin):
  78. """ admin model that manages the telephones """
  79. def get_urls(self):
  80. urls = super(self.__class__, self).get_urls()
  81. my_urls = patterns(
  82. '',
  83. url((r'^add_telefono/(?P<app>\w+)/(?P<model>\w+)/'
  84. '(?P<object_id>\d+)?/$'),
  85. self.admin_site.admin_view(self.add_telefonos),
  86. name='admin_common_add_telefonos'),
  87. )
  88. return my_urls + urls
  89. def add_telefonos(self, request, app, model, object_id):
  90. """
  91. handles the proccess of telephone additions
  92. """
  93. fono_list = ''
  94. num_fonos = 0
  95. exec 'from %s.models import %s' % (app, model)
  96. formset = AdminFonoFormSet()
  97. add_success = del_fono = False
  98. if object_id:
  99. obj = get_object_or_404(eval(model), id=object_id)
  100. fono_list = obj.telefonos.iterator()
  101. num_fonos = obj.telefonos.count()
  102. if request.method == 'POST':
  103. if '_save' in request.POST:
  104. formset = AdminFonoFormSet(request.POST)
  105. if formset.is_valid():
  106. formset.save(obj)
  107. formset = AdminFonoFormSet()
  108. add_success = True
  109. fono_list = obj.telefonos.iterator()
  110. num_fonos = obj.telefonos.count()
  111. else:
  112. del_form = AdminDeleteTelefonoForm(request.POST)
  113. if del_form.is_valid():
  114. del_form.save()
  115. del_fono = True
  116. fono_list = obj.telefonos.iterator()
  117. num_fonos = obj.telefonos.count()
  118. return render_to_response('admin/common/telefono/add_telefono.html',
  119. {'formset': formset, 'fono_list': fono_list,
  120. 'add_success': add_success,
  121. 'num_fonos': num_fonos,
  122. 'del_fono': del_fono, 'is_popup': True, },
  123. context_instance=RequestContext(request))
  124. class DepartamentoAdmin(admin.ModelAdmin):
  125. """ admin model that manages the departments """
  126. pass
  127. class ProvinciaAdmin(admin.ModelAdmin):
  128. """ admin model that manages the provinces """
  129. def get_urls(self):
  130. urls = super(self.__class__, self).get_urls()
  131. my_urls = patterns(
  132. '',
  133. url(r'^ajax_get_provincias/$',
  134. self.admin_site.admin_view(self.ajax_get_provincias),
  135. name='admin_common_ajax_get_provincias'),
  136. url(r'^ajax_update_provincia_selection/$',
  137. self.admin_site.admin_view(
  138. self.ajax_update_provincia_selection),
  139. name='admin_common_ajax_update_provincia_selection'),
  140. )
  141. return my_urls + urls
  142. def ajax_get_provincias(self, request):
  143. """
  144. Gets all the provinces from the selected department and returns
  145. them wrapped with html code for a select tag.
  146. """
  147. if request.method == 'GET':
  148. try:
  149. department = Departamento.objects.get(
  150. id=request.GET['id'])
  151. except ObjectDoesNotExist:
  152. data = {'response': 'error'}
  153. else:
  154. queryset = department.provincia_set.all()
  155. data = '<option selected="selected" value="">\
  156. ---------</option>'
  157. data += ''.join('<option value="%d">%s\
  158. </option>' % (
  159. provincia.id, provincia.nombre) for provincia in queryset)
  160. data = {'html_code': data}
  161. return json_response(data)
  162. return None
  163. def ajax_update_provincia_selection(self, request):
  164. """
  165. return all the provinces corresponding to the deparment of the
  166. selected province, all of them wrapped in html for a select tag and
  167. with the selected province with its corresponding selected attribute
  168. """
  169. if request.method == 'GET':
  170. try:
  171. prov = Provincia.objects.get(id=request.GET['id'])
  172. except ObjectDoesNotExist:
  173. data = {'response': 'error'}
  174. else:
  175. prov_list = prov.departamento.provincia_set.all()
  176. data = '<option value="">---------</option>'
  177. for provincia in prov_list:
  178. if provincia.id == prov.id:
  179. data += '<option selected="selected" value="%d">%s\
  180. </option>' % (provincia.id, provincia.nombre)
  181. else:
  182. data += '<option value="%d">%s\
  183. </option>' % (provincia.id, provincia.nombre)
  184. data = {'html_code': data}
  185. return json_response(data)
  186. return None
  187. class DistritoAdmin(admin.ModelAdmin):
  188. """ admin model that manages the districts """
  189. def get_urls(self):
  190. urls = super(self.__class__, self).get_urls()
  191. my_urls = patterns(
  192. '',
  193. url(r'^ajax_get_distritos/$',
  194. self.admin_site.admin_view(self.ajax_get_distritos),
  195. name='admin_common_ajax_get_distritos'),
  196. url(r'^ajax_update_distrito_selection/$',
  197. self.admin_site.admin_view(
  198. self.ajax_update_distrito_selection),
  199. name='admin_common_ajax_update_distrito_selection'),
  200. )
  201. return my_urls + urls
  202. def ajax_get_distritos(self, request):
  203. """
  204. Gets all the districts from the selected province and returns
  205. them wrapped with html code for a select tag.
  206. """
  207. if request.method == 'GET':
  208. try:
  209. province = Provincia.objects.get(
  210. id=request.GET['id'])
  211. except ObjectDoesNotExist:
  212. data = {'response': 'error'}
  213. else:
  214. queryset = province.distrito_set.all()
  215. data = '<option selected="selected" value="">\
  216. ---------</option>'
  217. data += ''.join('<option value="%d">%s\
  218. </option>' % (
  219. district.id, district.nombre) for district in queryset)
  220. data = {'html_code': data}
  221. return json_response(data)
  222. return None
  223. def ajax_update_distrito_selection(self, request):
  224. """
  225. return all the districts corresponding to the province of the
  226. selected district, all of them wrapped in html for a select tag and
  227. with the selected district with its corresponding selected attribute
  228. """
  229. if request.method == 'GET':
  230. try:
  231. dist = Distrito.objects.get(id=request.GET['id'])
  232. except ObjectDoesNotExist:
  233. data = {'response': 'error'}
  234. else:
  235. dist_list = dist.provincia.distrito_set.all()
  236. data = '<option value="">---------</option>'
  237. for distrito in dist_list:
  238. if distrito.id == dist.id:
  239. data += '<option selected="selected" value="%d">%s\
  240. </option>' % (distrito.id, distrito.nombre)
  241. else:
  242. data += '<option value="%d">%s\
  243. </option>' % (distrito.id, distrito.nombre)
  244. data = {'html_code': data}
  245. return json_response(data)
  246. return None
  247. class DireccionAdmin(admin.ModelAdmin):
  248. """ admin model that manages the addresses """
  249. def get_urls(self):
  250. urls = super(self.__class__, self).get_urls()
  251. my_urls = patterns(
  252. '',
  253. url((r'^add_direccion/(?P<app>\w+)/(?P<model>\w+)/'
  254. '(?P<object_id>\d+)?/$'),
  255. self.admin_site.admin_view(self.add_direccion),
  256. name='admin_common_add_direccion'),
  257. url(r'^ajax_edit_direccion/$',
  258. self.admin_site.admin_view(self.ajax_edit_direccion),
  259. name='admin_common_ajax_edit_direccion'),
  260. url(r'^ajax_delete_direccion/$',
  261. self.admin_site.admin_view(self.ajax_delete_direccion),
  262. name='admin_common_ajax_delete_direccion'),
  263. )
  264. return my_urls + urls
  265. def add_direccion(self, request, app, model, object_id):
  266. """ View that handles the proccess of address addition """
  267. form = AdminDireccionForm()
  268. add_success = False
  269. exec 'from %s.models import %s' % (app, model)
  270. obj = get_object_or_404(eval(model), id=object_id)
  271. if request.method == 'POST':
  272. form = AdminDireccionForm(request.POST)
  273. if form.is_valid():
  274. form = form.saveTo(obj.direcciones)
  275. add_success = True
  276. return render_to_response(
  277. 'admin/common/direccion/add_direccion.html',
  278. {'form': form, 'dir_list': obj.direcciones.all(),
  279. 'add_success': add_success,
  280. 'is_popup': True},
  281. context_instance=RequestContext(request))
  282. def ajax_edit_direccion(self, request):
  283. """ returns the address data """
  284. if request.method == 'GET':
  285. try:
  286. obj = Direccion.objects.get(id=request.GET['id'])
  287. except ObjectDoesNotExist:
  288. data = {'response': 'error'}
  289. else:
  290. data = {'id': obj.id,
  291. 'texto': obj.texto,
  292. 'departamento': obj.departamento.id,
  293. 'provincia': obj.provincia.id,
  294. 'distrito': obj.distrito.id}
  295. return json_response(data)
  296. return None
  297. @csrf_exempt
  298. def ajax_delete_direccion(self, request):
  299. """ deletes the direccion with the id received """
  300. if request.method == 'POST':
  301. try:
  302. obj = Direccion.objects.get(id=request.POST['id'])
  303. except ObjectDoesNotExist:
  304. data = {'response': 'error'}
  305. else:
  306. # a tweak to make it work with personal and clients
  307. # personal = obj.personal_personal_related.all()[0]
  308. personal = obj.personal_personal_related.all() or \
  309. obj.clientes_cliente_related.all()
  310. personal = personal[0]
  311. if personal.direcciones.count() > 1:
  312. obj.delete()
  313. data = {'response': 'ok'}
  314. else:
  315. data = {'response': 'last address'}
  316. return json_response(data)
  317. return None
  318. admin.site.register(Observacion, ObservacionAdmin)
  319. admin.site.register(TipoTelefono, TipoTelefonoAdmin)
  320. admin.site.register(Telefono, TelefonoAdmin)
  321. admin.site.register(Departamento, DepartamentoAdmin)
  322. admin.site.register(Provincia, ProvinciaAdmin)
  323. admin.site.register(Distrito, DistritoAdmin)
  324. admin.site.register(Direccion, DireccionAdmin)