Apoorv Kansal
Apoorv Kansal

Reputation: 3280

Deleting Session Variables Django

So I have a session variable that has a rough structure like this:

request.session['selected_courses'] = {
    '2': {'num_spots_available': 3, 
           attendees = [ {'first_name': 'Jon', 'last_name': 'Kan'}, ... ]}
    ...
}

Each key under 'selected_courses' is a course id.

I need to remove an attendee i.e {'first_name': 'Jon', 'last_name': 'Kan'} from a selected course. When I try to do this, the session does not actually delete the attendee. As I try to delete another attendee, the previous attendee pops right back into the session even though my code deleted it before! However, after rerunning this code, it finally deletes the attendee from session.

My code in views.py (i pull data out of POST because I am doing an AJAX request and know the data is not inputted by the user):

course_id = str(request.POST['course_id'])
first_name = str(request.POST['first_name'])
last_name = str(request.POST['last_name'])
request.session['selected_courses'][str(course_id)]['attendees'] = [a for a in request.session['selected_courses'][str(course_id)]['attendees']
        if a['first_name'] != first_name or a['last_name'] != last_name]

request.session.modified =True

So I have tried the request.session.modified attribute (as shown above) along with the SESSION_SAVE_EVERY_REQUEST = True and neither worked. (Please note: I am still quite new to Django).

Upvotes: 0

Views: 657

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599530

This code is much too complex, and has at least one serious bug. remove does not return the modified list, but None, so if you do attendees = attendees.remove(...) then the attendees will now be None.

A very much simpler way to write this code will be with loops:

for course in request.session['selected_courses']:
    if course['course_id'] == course_id:
        course['attendees'] = [
            a for a in course['attendees']
            if a['first_name'] != first_name and a['last_name'] != last_name
        ]
        break

Note, this is not any less efficient, since your calls to map and remove are really loops themselves.

Alternatively, you might consider a different data structure; if you regularly need to search selected_courses for a particular course ID, it would be better to store it as a dict keyed by that ID, rather than a list of dicts containing the ID as a value.

request.session['selected_courses'] = {
   '2': [ {'first_name': 'Jon', 'last_name': 'Kan'}, ... ]
}

Upvotes: 2

Related Questions