[Django]-How to re-initialize a session variable in a Django SessionWizardView

2πŸ‘

βœ…

You should initialize your variable path_one_images only on the first wizard step:

....

step = int(self.steps.current)    
if step == 0:
    self.request.session['path_one_images'] = ['P1D1.jpg', 'P2D2.jpg', 'P3D3.jpg', 'P4D4.jpg', 'P5D5.jpg', 'P6D6.jpg', 'P7D7.jpg', 'P8D8.jpg', 'P9D9.jpg']    

PATH_ONE_IMAGES = self.request.session.get('path_one_images', [])        
images = self.request.session.get('images', [])
slider_DV_values = self.request.session.get('slider_DV_values', [])

if step in range (5, 19):   
    # You don't need to reinit here your session variable
    # self.request.session['path_one_images'] = PATH_ONE_IMAGES               

....

and maybe you need to adopt the same approach for images and slider_DV_values variables.

2πŸ‘

Actually when you visit with the same browser you are not initialising, you are actually using the same PATH_ONE_IMAGES, that you saved at the 9th step. This is happening because if this line of code –

PATH_ONE_IMAGES = self.request.session.get('path_one_images', ['P1D1.jpg', 'P2D2.jpg', 'P3D3.jpg', 'P4D4.jpg', 'P5D5.jpg', 'P6D6.jpg', 'P7D7.jpg', 'P8D8.jpg', 'P9D9.jpg']) 

Note that, get only return the second parameter if the provided key (first parameter) is not present in a dictionary, neither it checks what the value is nor does it initialises the dictionary with the provided default value (second parameter). So with this line code, the value of path_on_images inside the session is never updated, it will only check if that value exists or not – it won’t check for empty value, None or anything else.

I will describe the scenario, what is happening in your case –

  1. When the first time you open the browser there is nothing in the session. So the first time the above code will assign ['P1D1.jpg', 'P2D2.jpg', 'P3D3.jpg', 'P4D4.jpg', 'P5D5.jpg', 'P6D6.jpg', 'P7D7.jpg', 'P8D8.jpg', 'P9D9.jpg'] inside PATH_ONE_IMAGES.

  2. continues until PATH_ONE_IMAGES is empty …. no error..

  3. Now you refreshed the browser, but remember session does not get cleared for only refreshing the browser, therefore the PATH_ONE_IMAGE, that you saved in the session is not cleared and thus contains an empty list of item that was saved at last step.

So, somehow you have to clear the variable when it is the first step. You can take the code sample that @salvatore provided and add a check to initialise it only at step 0.

step = int(self.steps.current)    
if step == 0:
    self.request.session['path_one_images'] = ['P1D1.jpg', 'P2D2.jpg', 'P3D3.jpg', 'P4D4.jpg', 'P5D5.jpg', 'P6D6.jpg', 'P7D7.jpg', 'P8D8.jpg', 'P9D9.jpg']    

PATH_ONE_IMAGES = self.request.session.get('path_one_images', [])        
images = self.request.session.get('images', [])
slider_DV_values = self.request.session.get('slider_DV_values', [])`

Leave a comment