我有一个具有以下格式的模板:
<form enctype="multipart/form-data" action="{% url 'ngnmgmt_import_metro_area' %}" method="post" class="tds_form" id="import_metro_area_form">
{% csrf_token %}
<h3>Metro Area File Upload</h3>
<div class="form-group">
<!-- Would like to somehow re-attach my file here if it exists -->
<label for="metro_area_file_upload">Select a Metro Area file to import.</label>
<input id="metro_area_file_upload" name="metro_area_file" type="file">
<!-- Alternatively, I would be happy to put the file in a hidden input or
pass the file some other way, and hide the above input -->
</div>
<div class="row">
<button class="btn btn-primary" type="submit">Check for Existing Items</button>
{% if view_changes %}
<button class="btn btn-success" type="submit" name="load_changes" value="True">Import Metro Area</button>
{% endif %}
</div>
</form>
和类似以下内容的视图:
class ImportMetroArea(LoginRequiredMixin, PermissionRequiredMixin, TemplateView):
template_name = 'ngnmgmt/import_metro_area.html'
login_url = '/login/'
permission_required = 'commons.change_metroarea'
def __init__(self, **kwargs):
super(ImportMetroArea, self).__init__(**kwargs)
self.load_changes = False
self.view_changes = False
def get_context_data(self, **kwargs):
context = {
# I would like to pass the file back
# through the context, and somehow re-attach it
# to my form file input
"file": self.file,
"load_changes": self.load_changes,
"view_changes": self.view_changes,
# Other irrelevant context data...
}
return context
def get(self, request, *args, **kwargs):
context = self.get_context_data()
return render(request, self.template_name, context=context)
def post(self, request, *args, **kwargs):
self.load_changes = request.POST.get("load_changes")
self.file = request.FILES.get("metro_area_file")
if not self.load_changes:
self.view_changes = True
if not self.file:
context = {
"errors": ['Please upload a file.', ]
}
return render(request, self.template_name, context=context)
// Do stuff that happens whether we are loading changes or not
if self.load_changes:
// Actually load the changes
context = self.get_context_data()
return render(request, self.template_name, context=context)
基本上,这是一个两步过程,在第一个POST中,我们确定要更改的内容,在第二个POST请求中,我们实际加载更改。
当前,在第二步中,用户必须将相同文件重新附加到文件上传表单。我希望将此文件保留下来并在第二步中重新附加。