0

I want to create the import the csv data into database. I add the import buttom on the my app. Override app/change_list. Button will be properly added. I want to add the action on click on that "import" button file will be uploaded on same template page. And the data will be saved. I refer the links

Importing data into django from CSV via admin interface

Extending Django Admin for data import

But i didn't understand the admin process. I want to open the file uploadd option on pop-up like the image_file upload.

Community
  • 1
  • 1
Meenakshi
  • 259
  • 5
  • 19

3 Answers3

1

I wrote and use the below code:

import csv
def importcsv(request):
     if request.method == "POST":
        form = DataInput(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('Url/')
     else:
        form = DataInput()
        context = {"form": form}
        return render_to_response("imported.html", context,context_instance=RequestContext(request))

And in created import.html file having form with

<form enctype="multipart/form-data" action="" method="post" id="importform">
NeuroWinter
  • 574
  • 1
  • 4
  • 20
Meenakshi
  • 259
  • 5
  • 19
1

There is a really good example of uploading CSV on the admin cookbook website:

https://books.agiliq.com/projects/django-admin-cookbook/en/latest/import.html

The code is as follows:

class CsvImportForm(forms.Form):
csv_file = forms.FileField()

@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...
change_list_template = "entities/heroes_changelist.html"

def get_urls(self):
    urls = super().get_urls()
    my_urls = [
        ...
        path('import-csv/', self.import_csv),
    ]
    return my_urls + urls

def import_csv(self, request):
    if request.method == "POST":
        csv_file = request.FILES["csv_file"]
        reader = csv.reader(csv_file)
        # Create Hero objects from passed in data
        # ...
        self.message_user(request, "Your csv file has been imported")
        return redirect("..")
    form = CsvImportForm()
    payload = {"form": form}
    return render(
        request, "admin/csv_form.html", payload
    )
NeuroWinter
  • 574
  • 1
  • 4
  • 20
  • Sorry to necro an old post, but how does it actually do the upload, do you create your own objects there, and call the save method? – CBredlow Nov 26 '18 at 22:51
  • Yeah, see where I commented `Create Hero objects from passed in data` That is where you would call `Hero(....).save()` – NeuroWinter Nov 27 '18 at 01:43
0

I know this is an old post but I had a similar issue and used the shell and a local CSV file with these lines of code:

from Contry.models import Countries
import pandas

for index, row in pandas.read_csv('./Country_data.csv').iterrows():
    x = Countries(name=f"{row['name']}", size=f"{row['area']}")
    x.save()
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
andy
  • 1