Source code for jmb.core.views.import_data

# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from django.contrib import messages
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from django.views.generic import FormView

from jmb.core.utils.data_import import XlsFile
from jmb.core.admin.forms import ImportDataForm


[docs]class ImportDataView(FormView): template_name = 'admin/import_data.html' form_class = ImportDataForm import_class = XlsFile def get_context_data(self, **kwargs): context = super(ImportDataView, self).get_context_data(**kwargs) breadcrumbs = ( (_('Home'), '/admin/'), ) context['is_popup'] = "_popup" in self.request.REQUEST context['breadcrumbs'] = breadcrumbs context['import_form'] = self.form_class return context
[docs] def form_valid(self, form): file_to_import = form.cleaned_data['file_to_import'] import_data = self.import_class( file_contents=file_to_import.read(), auto=True, opts=form.cleaned_data ) import_data.read() # esegue il do() per ogni riga if import_data.messages['inserted'] > 0: messages.success( self.request, _("{} rows have been inserted".format(import_data.messages['inserted'])) ) if import_data.messages['modified'] > 0: messages.warning( self.request, _("{0} rows have been modified".format(import_data.messages['modified'])) ) if import_data.messages['errors']: for error in import_data.messages['errors']: messages.error(self.request, error) return super(ImportDataView, self).form_valid(form)