You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

reports.py 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from django.template.defaultfilters import date
  2. from django.template import loader, Context
  3. from django.http import HttpResponse
  4. class ReportGenerator(object):
  5. """
  6. Top-level class that needs to be subclassed to provide a
  7. report generator.
  8. """
  9. filename_template = 'report-%s-to-%s.csv'
  10. mimetype = 'text/csv'
  11. code = ''
  12. description = '<insert report description>'
  13. def __init__(self, **kwargs):
  14. if 'start_date' in kwargs and 'end_date' in kwargs:
  15. self.start_date = kwargs['start_date']
  16. self.end_date = kwargs['end_date']
  17. self.formatter = self.formatters['%s_formatter' % kwargs['formatter']]()
  18. def generate(self, response):
  19. pass
  20. def filename(self):
  21. """
  22. Returns the filename for this report
  23. """
  24. return self.filename_template % (self.start_date, self.end_date)
  25. def is_available_to(self, user):
  26. """
  27. Checks whether this report is available to this user
  28. """
  29. return user.is_staff
  30. class ReportFormatter(object):
  31. def format_datetime(self, dt):
  32. return date(dt, 'DATETIME_FORMAT')
  33. def format_date(self, d):
  34. return date(d, 'DATE_FORMAT')
  35. def filename(self):
  36. return self.filename_template
  37. class ReportCSVFormatter(ReportFormatter):
  38. def generate_response(self, objects, **kwargs):
  39. response = HttpResponse(mimetype='text/csv')
  40. response['Content-Disposition'] = 'attachment; filename=%s' % self.filename(**kwargs)
  41. self.generate_csv(response, objects)
  42. return response
  43. class ReportHTMLFormatter(ReportFormatter):
  44. def generate_response(self, objects, **kwargs):
  45. template = loader.get_template(self.template)
  46. ctx = Context({'objects': objects})
  47. return template.render(ctx)