Reputation: 359
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.
Upvotes: 0
Views: 4835
Reputation: 1
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()
Upvotes: 0
Reputation: 359
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">
Upvotes: 1
Reputation: 511
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
)
Upvotes: 1