我想在django管理界面上创建一个动作,允许选择和打开文件,然后进行处理(将此处理的最终结果保存下来)。我不知道如何在管理操作中执行此操作,因此我通过在与操作关联的模型上添加可选文件字段来解决此问题,但这看起来很笨拙和浪费。
如何在点击管理操作后提示用户选择文件?
感谢。
答案 0 :(得分:0)
首先创建表单
class SelectFileForm(forms.Form):
_selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
file = forms.FileField()
将此代码添加到您的admin.py:
def select_file_action(modeladmin, request, queryset):
form = None
if 'apply' in request.POST:
form = ChooseFileForm(request.POST)
if form.is_valid():
file = form.cleaned_data['file']
count = 0
for item in queryset:
#do something with file
item.file = file
item.save()
count += 1
modeladmin.message_user(request, "File successfully selected")
return HttpResponseRedirect(request.get_full_path())
if not form:
form = SelectFileForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
return render(request, 'select_file.html', {'items': queryset,'form': form, 'title':'File'})
select_file_action.short_description = "Choose file"
注册您的行动
actions = [select_file_action,]
和select_file模板:
{% extends "admin/base_site.html" %}
{% block content %}
<form action="" method="post">{% csrf_token %}
{{ form }}
<ul>{{ items|unordered_list }}</ul>
<input type="hidden" name="action" value="select_file_action" />
<input type="submit" name="apply" value="Save" />
</form>
{% endblock %}