store a list in request.session in one view and retrieve it in another view django

2.9k views Asked by At

I have a huge list that will be generated dynamically from a csv file in a django view, but i had a requirement to use that list in the next view, so i thought to give a try on django sessions

def import_products(request):
    if request.method == 'POST':
        if request.FILES:
           csv_file_data = ...........
           total_records = [row for row in csv_file_data]
           request.session['list_data'] = total_records
           # total_records is `list of lists` of length more than 150
           # do some processing with the list and render the page
    return render_to_response('product/import_products.html') 

def do_something_with_csv_data_from_above_view(request):
    data = request.session['list_data']
    # do some operations with list and render the page
    return render_to_response('website/product/success.html',

So as mentioned in the above, i need to use the total_records huge list in the do_something_with_csv_data_from_above_view view and delete the session by storing it in another variable

So actually how to implement/use exactly the sessions concept(i have read the django docs but could n't able to get the exact concept)

In my case,

  1. When a user tries to upload the csv file each time, i am reading the data and storing the data as list to session ==> Is this the right way to do so ? also i want to store the session variable in database concept
  2. Because the list was huge, i need to delete it for sure in the next view when i copied it in to another variable

Am i missing anything, can anyone please implement exact code for my above scenario ?

1

There are 1 answers

4
Sid On

You have two options:

  1. Client side RESTful - This is a RESTful solution but may require a bit more work. You can retrieve the data in the first request to the client and after selecting you can send the selected rows back to the server for processing, CSV etc.

  2. Caching: In the first request you can cache your data on the server using a django file system or memcached. In the second request use the cache key (which would be the user session key + some timestamp + whatever else) to fetch the data and store in the db.

If it's a lot of data option 2 may be better.