How to process CSV files with Django, after being imported? [closed]

0

I need an explanation or orientation of the steps of how to process a csv file, to import it with the FileField field of the Django models but I need the information of the CSV to replicate in the databases. I appreciate your collaboration.

    
asked by Dantez Layton 01.08.2018 в 06:42
source

1 answer

1

To process the CSV you would have to generate a function manually using a library, such as link

If you are already using the CSV upload via a FileField, you could call this function when your object has been saved. Something like:

@receiver(post_save, sender=models.TuModelo)
def csv_handler(sender, instance, created, **kwargs):
    # Y aquí haces el tratamiento del CSV con la librería anterior

Anyway, I'm not sure why you store the CSV in a FileField. I personally would prefer to upload the CSV with a forms.Form instead of a forms.ModelForm , and do the CSV treatment directly in the function save of the form, or in the view.

Something like this:

# views.py
import csv
from django.views import generic

class ManageCSV(generic.FormView):
    form_class = forms.ManageCSVForm
    ...

    def form_valid(self, form):
        # Gestiona aquí tu CSV con la librería anterior
        # Podría ser algo así:
        with open(form.cleaned_data['csv_file'], 'rb') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                TuModelo.objects.create( ... )

        return super(ManageCSV, self).form_valid(form)

# forms.py
class ManageCSVForm(forms.Form):
    csv_file = forms.FileField()

    def __init__(self, *args, **kwargs):
        super(ManageCSVForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Fieldset(
                u'',
                'csv_file'
            )
        )
        self.helper.layout.append(Submit('guardar', 'Guardar'))

It's all unproven, because you do not give much information, but the thing would go there. It's pretty simple.

    
answered by 01.08.2018 в 10:12