Home > Blockchain >  Export data as excel from class based view
Export data as excel from class based view

Time:10-11

I have class based view and when request is post, self.readdb() will give dictionary result to self.db_result variable which will be populated as html table. This is working fine.

I need to export this table as excel.

My view.py

  class Download(View):
    def __init__(self, logger=None, **kwargs):
        self.logger = logging.getLogger(__name__)
        self.db_result = []

  def post(self, request):
    if request.method == 'POST':
        form = DownloadForm(request.POST, request.FILES)
        if form.is_valid():  
            self.db_result = self.readdb() 
            if self.db_result != False:
                return render(request,'download.html',{'present': self.db_result[0]})
        <table >
            <caption>Present in DB</caption>
            <tbody>
                {% for key, value in present.items %}
                    <tr>
                        <td> {{ key }} </td> <td> {{ value }} </td>
                    </tr>
                {% endfor %}
            </tbody>
            <a href="{% url 'export_excel' %}">Download excel file</a>
        </table>
    {% endif %}

I tried following which is generating excel file when click but it doesn't have any data. print(self.db_result) in get function is printing []. Looks like result from "post" is not available in "get".

    def get(self, request):
       if request.method == 'GET':    
            if request.path_info == '/export/excel':
                print(self.db_result)
                response = self.export_users_xls()
                return response

    def export_users_xls(self):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachement; filename="report.csv"'
        print(self.db_result)
        writer = csv.writer(response)
        writer.writerow(['Command', 'XML data'])

        return response

How can I access self.db_result from "post" function in "get" so that I can generate excel file. If I'm doing wrong, please guide me to correct steps. I'm not using Models. self.db_result from post has the required result which should be populated as excel.

CodePudding user response:

You can't as such. The GET action and the POST actions are separate types of request - one loads a page and possibly sends name/value pairs from a form via the URL, and the other posts the pairs behind the scenes. A variable created in one function isn't immediately available in another, because they are run as different requests/page loads.

If you need to refer to a previous variable you can store it as a session variable for later (see docs for more)

eg in your post()

    if form.is_valid():  
        self.db_result = self.readdb() 
        request.session['db_result'] = self.db_result

and then later, in your get()

   #use session.get() to return None if variable has not been set.
   self.db_result = request.session.get('db_result')
   
  • Related