ToB企服应用市场:ToB评测及商务社交产业平台
标题:
Django Admin管理后台导入CSV
[打印本页]
作者:
我爱普洱茶
时间:
2024-9-10 02:01
标题:
Django Admin管理后台导入CSV
修改管理模子,代码如下:
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
)
复制代码
创建模板文件templates/entities/heroes_changelist.html
{% extends 'admin/change_list.html' %}
{% block object-tools %}
<a href="import-csv/">Import CSV</a>
<br />
{{ block.super }}
{% endblock %}
复制代码
创建模板文件templates/admin/csv_form.html
{% extends 'admin/base.html' %}
{% block content %}
<div>
<form action="." method="POST" enctype="multipart/form-data">
{{ form.as_p }}
{% csrf_token %}
<button type="submit">Upload CSV</button>
</form>
</div>
<br />
{% endblock %}
复制代码
显示效果如下:
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4