Boanerges7
Boanerges7

Reputation: 41

Read a csv file and fill in database with it's data in django application

in my Django application, i created a form which permit user to upload csv file. What i want is when user upload the csv file, the contained data is read and database is filled in with them. It works but not correctly. data are saved as tuples.

Look the first row

Here's my code

forms.py

class SupplierCSVForm(forms.ModelForm):
    class Meta:
        model = SuplierCsv
        fields = '__all__'
        exclude = ('slug',)

views.py

@login_required
def l_supplier(request):
    suppliers_list = Supplier.objects.all()
    paginator = Paginator(suppliers_list, 3, 2)

    page = request.GET.get('page')
    suppliers = paginator.get_page(page)

    # Supplier csv form
    if request.method == 'POST':
        form = SupplierCSVForm(request.POST, request.FILES)

        if form.is_valid():

            uploaded_file = request.FILES['csvfile']
            with open('f.csv', 'wb') as destination:
                for chunk in uploaded_file.chunks():
                    destination.write(chunk)
                    destination.close()
            #csvfile = io.TextIOWrapper(open('f.csv', 'rb'))

            with open('f.csv', 'r') as the_source:
                source_reader = csv.reader(sthe_source)
                next(source_reader)
                for Name, Email, Contact, City, Website, Activity, Cc, slug in source_reader:

                    new_supplier = Supplier()
                    new_supplier.name=Name,
                    new_supplier.email=Email,
                    new_supplier.contact=Contact,
                    new_supplier.city=City,
                    new_supplier.website=Website,
                    new_supplier.activity=Activity,
                    new_supplier.cc=Cc,
                    new_supplier.slug=slug,
                    new_supplier.save()

            return redirect('good:l_good')

    else:
        form = SupplierCSVForm()

    context = {
    'suppliers': suppliers,
    'form': form,
    }

    return render(request, 'supplier/l_supplier.html', context)

Upvotes: 0

Views: 811

Answers (2)

Adi Eyal
Adi Eyal

Reputation: 338

You have unnecessary commas at the end of your lines:

new_supplier.name=Name,

should be

new_supplier.name=Name

Python thinks that you are creating a tuple i.e. x, == (x,)

Upvotes: 1

the-chaos-magus
the-chaos-magus

Reputation: 119

Remove the commas where you are assigning the new_supplier objects. Python converts your string objects into tuples if there are any trailing commas.

Upvotes: 1

Related Questions