Simple CSV file Upload Form must be adapted for python 3 and Plone 5.2
from plone.autoform.form import AutoExtensibleForm
from zope import interface
from zope import schema
from zope import component
from z3c.form import form, button
from zope.interface import implementer
from Products.statusmessages.interfaces import IStatusMessage
from plone.namedfile.field import NamedFile
from Products.CMFPlone import PloneMessageFactory as _
import csv
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
import z3c.form.button
class IImportCSVFormSchema(interface.Interface):
""" Define fields used on the form """
csv_file = NamedFile(title=_(u'CSV file'))
class ImportCSVForm(AutoExtensibleForm, form.Form):
""" A sample form showing how to mass import users using an uploaded CSV file.
"""
name = _(u'Import Companies') # Form label
schema = IImportCSVFormSchema # Form schema
ignoreContext = True
def processCSV(self, data):
"""
"""
reader = csv.reader(
StringIO.StringIO(data),
delimiter=',',
dialect='excel',
quotechar='"'
)
header = reader.next()
updated = 0
for row in reader:
# process the data here as needed for the specific case
for idx, name in header:
value = row[idx]
updated += 1
return updated
@z3c.form.button.buttonAndHandler(_('Import CSV'), name='import')
def importCSV(self, action):
""" Create and handle form button
"""
# Extract form field values and errors from HTTP request
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
# get the actual data
file = data["csv_file"].data
# do the processing
number = self.processCSV(file)
# If everything was ok post success note
# Note you can also use self.status here unless you do redirects
if number is not None:
# mark only as finished if we get the new object
IStatusMessage(
self.request
).addStatusMessage(
_(u'Processed: {0}').format(number),
'info'
)
Simple CSV file Upload Form must be adapted for python 3 and Plone 5.2