cj ogbuehi
cj ogbuehi

Reputation: 187

Understanding django doc code- Sessions

Hello Im a django/python newbie and need some help understanding the code below.

def post_comment(request, new_comment):
    if request.session.get('has_commented', False):
        return HttpResponse("You've already commented.")
    c = comments.Comment(comment=new_comment)
    c.save()
    request.session['has_commented'] = True
    return HttpResponse('Thanks for your comment!')

Where I am confused is at if request.session.get('has_commented',False) If a user has commented the'has_commented' key is set to true, so wouldnt you check to see if 'has_commented' is set to true to make sure a user doesnt post another comment instead of checking if 'has_commented' is false. Is my logic incorrect? Also where is the session key 'has_commented' originating from?

Upvotes: 1

Views: 97

Answers (2)

avenger
avenger

Reputation: 120

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

Upvotes: 1

Xymostech
Xymostech

Reputation: 9850

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.

Upvotes: 1

Related Questions