plone / documentation

Plone Documentation
https://docs.plone.org
91 stars 153 forks source link

develop/plone/forms/files.rst #1113

Open frankar opened 4 years ago

frankar commented 4 years ago

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'
            )
stevepiercy commented 3 weeks ago

If we port the content from https://5.docs.plone.org/develop/plone/forms/files.html#simple-csv-file-upload-form, then we can update the code sample, removing Python 2 requirements, for Plone 6.