从 django 管理操作中间页面重定向到更改表单页面

ac1*_*c11 5 django django-admin django-admin-actions

我正在尝试构建一个管理操作“download_selected”,它将下载选定的模型。选择该操作后,我会重定向到中间页面,以便用户可以选择下载格式。当用户选择下载格式并单击“下载”时,就会下载文件。但停留在同一个中间页面上。如何将其重定向回更改表单管理页面?我想要的这个重定向类似于 django“下载所选文件”默认管理操作。谢谢。

这是我的代码。

管理员.py

class SelectDownloadFormatForm(forms.Form):
    DOWNLOAD_TYPE_CHOICES=[('csv','csv'),
                           ('json', 'json'),
                           ('xml','xml')]

    _selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
    download_type = forms.ChoiceField(label=_('Select a Download type'), choices=DOWNLOAD_TYPE_CHOICES, widget=forms.RadioSelect())


def download_selected(self, request, queryset):
    import csv
    from django.http import HttpResponse, HttpResponseRedirect
    import StringIO

    form = None

    if 'download' in request.POST:
        form = self.SelectDownloadFormatForm(request.POST)

        if form.is_valid():
            dtype = form.cleaned_data['download_type']
            print dtype
            response = HttpResponse(content_type='text/csv')
            response['Content-Disposition'] = 'attachment; filename="export.csv"'
            writer = csv.writer(response)
            writer.writerow(['id', 'name', 'qid' ,'label', 'name', 'field'])

            count = 0
            for s in queryset:
                questions_query = ParentModel.objects.filter(parent_form_id = s.id)
                for q in questions_query:
                    writer.writerow([s.id, s.name, q.id, q.label, q.name, q.field])
                    count += 1
          
            plural = ''
            if count != 1:
                plural = 's'

            self.message_user(request, "Successfully downloaded %d survey response%s in %s format" % (count, plural, dtype))               
            return response

    if not form:
        form = self.SelectDownloadFormatForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})

    return render(request,'admin/download_type.html', {'items': queryset,
                                                     'download_type_form': form,
                                                    })
download_selected.short_description = "Download selected forms"
Run Code Online (Sandbox Code Playgroud)

下载类型.html

{% extends "admin/base_site.html" %}
{% block content %}
<form action="" method="post">
  {% csrf_token %}  
  {{ download_type_form }}

  <p>Following survey will be downloaded with corresponding responses:</p>

  <ul>{{ items|unordered_list }}</ul>

  <input type="hidden" name="action" value="download_selected" />
  <input type="submit" name="download" value="Download" />
 </form>

{% endblock %}
Run Code Online (Sandbox Code Playgroud)

ac1*_*c11 2

我添加了一个额外的返回按钮

<a href="#" onclick="window.history.back(); return false;" class="button cancel-link">Go Back</a>
Run Code Online (Sandbox Code Playgroud)