[Answered ]-Understanding django doc code- Sessions

1👍

The function request.session.get takes 2 parameters namely

  • the key (‘has_commented’)
  • the default (False)

The function will try return a value for the key, but if the key does not exist, or if the value is NULL then the default will be returned instead.

In other words, if the value for ‘has_commented’ is True the if statement will run. However if there is no ‘has_comment’ key in the session, request.session.get will return the default which is False and the if statement will not run.

The session key ‘has_commented’ originates in the line:

request.session[‘has_commented’] = True

1👍

When you call request.session.get('has_commented', False), you are asking “Has the session key 'has_commented' been set to true? If so, return the value. If not, return false.” Thus, if someone hasn’t yet commented, it will return False and continue to do the rest of the code.

The 'has_commented' key originates from a few lines below:

request.session['has_commented'] = True

This sets the 'has_commented' key to true once someone has commented.

Leave a comment