我想创建将csv数据导入数据库。 我在我的应用程序上添加导入按钮。覆盖app / change_list。按钮将被正确添加。我想在点击时添加动作,“导入”按钮文件将被上传到同一模板页面上。并保存数据。 我参考链接
Importing data into django from CSV via admin interface
Extending Django Admin for data import
但我不理解管理员流程。我想在弹出窗口中打开文件uploadd选项,如image_file upload。
答案 0 :(得分:1)
我编写并使用以下代码:
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))
在创建的带有
表单的import.html文件中<form enctype="multipart/form-data" action="" method="post" id="importform">
答案 1 :(得分:1)
在admin cookbook网站上有一个很好的上传CSV的例子:
https://books.agiliq.com/projects/django-admin-cookbook/en/latest/import.html
代码如下:
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
)