redirect to change form page from admin action intermediate page

181 views
Skip to first unread message

dc

unread,
Nov 4, 2015, 2:48:13 PM11/4/15
to Django users

I am trying to add admin action 'download_selected'. When the action is selected, it redirects to an intermediate page. When the user selects a file type and clicks on 'download', it downloads the file and stays on that page. How do I redirect it back to change form page it happens for 'delete_selected'? Thanks.

Here is my code.

admin.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

            self.message_user(request, "Successfully downloaded %d survey responses in %s format" % (count, 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"


download_type.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 %}

Reply all
Reply to author
Forward
0 new messages