twoscoops / two-scoops-of-django-1.8

Tracking thoughts and feature requests for Two Scoops of Django 1.8 in the issue tracker. And the book's code examples are here.
400 stars 81 forks source link

Chapter 9.1 / example 9.1 - return request #154

Closed briceparent closed 7 years ago

briceparent commented 7 years ago

In this chapter, you use return request and then explain this use by :

You’ll note that we return back a HttpRequest object rather than an arbitrary value or even a None object. We do this because as Python is a dynamically typed language, we can attach additional attributes to the HttpRequest

If you don't return it, and call it with check_sprinkles(request) instead of request = check_sprinkles(request), you'll have the same effect, as this object is mutable (correct me if I'm wrong), so there should be no reason to make a new assignment and this would lead to thinking that we are able to call the function without modifying the object just by removing the assignment.

Is there a reason to make the assignment like you did ?

pydanny commented 7 years ago

Yes, that's explained in the example that follows:

from django.core.exceptions import PermissionDenied

def check_sprinkles(request):
    if request.user.can_sprinkle or request.user.is_staff:
        # By adding this value here it means our display templates
        #   can be more generic. We don't need to have
        #   {% if request.user.can_sprinkle or request.user.is_staff %}
        #   instead just using
        #   {% if request.can_sprinkle %}
        request.can_sprinkle = True
        return request

    # Return a HTTP 403 back to the user
    raise PermissionDenied