Ticket #2332: is_logged_in.diff

File is_logged_in.diff, 13.3 KB (added by Gary Wilson <gary.wilson@…>, 9 years ago)

is_logged_in implementation with doc changes and deprecation warnings in is_anonymous

  • django/views/generic/create_update.py

     
    2020            the form wrapper for the object
    2121    """
    2222    if extra_context is None: extra_context = {}
    23     if login_required and request.user.is_anonymous():
     23    if login_required and not request.user.is_logged_in():
    2424        return redirect_to_login(request.path)
    2525
    2626    manipulator = model.AddManipulator(follow=follow)
     
    3939            # No errors -- this means we can save the data!
    4040            new_object = manipulator.save(new_data)
    4141
    42             if not request.user.is_anonymous():
     42            if request.user.is_logged_in():
    4343                request.user.message_set.create(message="The %s was created successfully." % model._meta.verbose_name)
    4444
    4545            # Redirect to the new object: first by trying post_save_redirect,
     
    8686            the original object being edited
    8787    """
    8888    if extra_context is None: extra_context = {}
    89     if login_required and request.user.is_anonymous():
     89    if login_required and not request.user.is_logged_in():
    9090        return redirect_to_login(request.path)
    9191
    9292    # Look up the object to be edited
     
    113113        if not errors:
    114114            object = manipulator.save(new_data)
    115115
    116             if not request.user.is_anonymous():
     116            if request.user.is_logged_in():
    117117                request.user.message_set.create(message="The %s was updated successfully." % model._meta.verbose_name)
    118118
    119119            # Do a post-after-redirect so that reload works, etc.
     
    162162            the original object being deleted
    163163    """
    164164    if extra_context is None: extra_context = {}
    165     if login_required and request.user.is_anonymous():
     165    if login_required and not request.user.is_logged_in():
    166166        return redirect_to_login(request.path)
    167167
    168168    # Look up the object to be edited
     
    180180
    181181    if request.method == 'POST':
    182182        object.delete()
    183         if not request.user.is_anonymous():
     183        if request.user.is_logged_in():
    184184            request.user.message_set.create(message="The %s was deleted." % model._meta.verbose_name)
    185185        return HttpResponseRedirect(post_delete_redirect)
    186186    else:
  • django/contrib/auth/models.py

     
    124124
    125125    def is_anonymous(self):
    126126        "Always returns False. This is a way of comparing User objects to anonymous users."
     127        import warnings
     128        warnings.warn("is_anonymous is deprecated. Use is_logged_in instead.")
    127129        return False
     130   
     131    def is_logged_in(self):
     132        "Always return True.  This is a way of comparing User objects to anonymous users."
     133        return True
    128134
    129135    def get_full_name(self):
    130136        "Returns the first_name plus the last_name, with a space in between."
     
    292298        return []
    293299
    294300    def is_anonymous(self):
     301        import warnings
     302        warnings.warn("is_anonymous is deprecated. Use is_logged_in instead.")
    295303        return True
     304   
     305    def is_logged_in(self):
     306        return False
  • django/contrib/auth/decorators.py

     
    1717        return _checklogin
    1818    return _dec
    1919
    20 login_required = user_passes_test(lambda u: not u.is_anonymous())
     20login_required = user_passes_test(lambda u: u.is_logged_in())
    2121login_required.__doc__ = (
    2222    """
    2323    Decorator for views that checks that the user is logged in, redirecting
  • django/contrib/comments/templatetags/comments.py

     
    114114        comment_list = get_list_function(**kwargs).order_by(self.ordering + 'submit_date').select_related()
    115115
    116116        if not self.free:
    117             if context.has_key('user') and not context['user'].is_anonymous():
     117            if context.has_key('user') and context['user'].is_logged_in():
    118118                user_id = context['user'].id
    119119                context['user_can_moderate_comments'] = Comment.objects.user_is_moderator(context['user'])
    120120            else:
  • django/contrib/comments/views/karma.py

     
    1515    rating = {'up': 1, 'down': -1}.get(vote, False)
    1616    if not rating:
    1717        raise Http404, "Invalid vote"
    18     if request.user.is_anonymous():
     18    if not request.user.is_logged_in():
    1919        raise Http404, _("Anonymous users cannot vote")
    2020    try:
    2121        comment = Comment.objects.get(pk=comment_id)
  • django/contrib/comments/views/comments.py

     
    6363                validator_list=get_validator_list(8),
    6464            ),
    6565        ])
    66         if not user.is_anonymous():
     66        if user.is_logged_in():
    6767            self["username"].is_required = False
    6868            self["username"].validator_list = []
    6969            self["password"].is_required = False
  • django/contrib/comments/templates/comments/form.html

     
    22{% if display_form %}
    33<form {% if photos_optional or photos_required %}enctype="multipart/form-data" {% endif %}action="/comments/post/" method="post">
    44
    5 {% if user.is_anonymous %}
     5{% if user.is_logged_in %}
     6<p>{% trans "Username:" %} <strong>{{ user.username }}</strong> (<a href="/accounts/logout/">{% trans "Log out" %}</a>)</p>
     7{% else %}
    68<p><label for="id_username">{% trans "Username:" %}</label> <input type="text" name="username" id="id_username" /><br />{% trans "Password:" %} <input type="password" name="password" id="id_password" /> (<a href="/accounts/password_reset/">{% trans "Forgotten your password?" %}</a>)</p>
    7 {% else %}
    8 <p>{% trans "Username:" %} <strong>{{ user.username }}</strong> (<a href="/accounts/logout/">{% trans "Log out" %}</a>)</p>
    99{% endif %}
    1010
    1111{% if ratings_optional or ratings_required %}
  • django/contrib/flatpages/views.py

     
    2222    f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID)
    2323    # If registration is required for accessing this page, and the user isn't
    2424    # logged in, redirect to the login page.
    25     if f.registration_required and request.user.is_anonymous():
     25    if f.registration_required and not request.user.is_logged_in():
    2626        from django.contrib.auth.views import redirect_to_login
    2727        return redirect_to_login(request.path)
    2828    if f.template_name:
  • django/contrib/admin/views/decorators.py

     
    4646    member, displaying the login page if necessary.
    4747    """
    4848    def _checklogin(request, *args, **kwargs):
    49         if not request.user.is_anonymous() and request.user.is_staff:
     49        if request.user.is_logged_in() and request.user.is_staff:
    5050            # The user is valid. Continue to the admin page.
    5151            if request.POST.has_key('post_data'):
    5252                # User must have re-authenticated through a different window
  • django/contrib/admin/templates/admin/base.html

     
    2020        <div id="branding">
    2121        {% block branding %}{% endblock %}
    2222        </div>
    23         {% if not user.is_anonymous %}{% if user.is_staff %}
     23        {% if user.is_logged_in %}{% if user.is_staff %}
    2424        <div id="user-tools">{% trans 'Welcome,' %} <strong>{% if user.first_name %}{{ user.first_name|escape }}{% else %}{{ user.username }}{% endif %}</strong>. {% block userlinks %}<a href="doc/">{% trans 'Documentation' %}</a> / <a href="password_change/">{% trans 'Change password' %}</a> / <a href="logout/">{% trans 'Log out' %}</a>{% endblock %}</div>
    2525        {% endif %}{% endif %}
    2626        {% block nav-global %}{% endblock %}
  • docs/request_response.txt

     
    106106    A ``django.contrib.auth.models.User`` object representing the currently
    107107    logged-in user. If the user isn't currently logged in, ``user`` will be set
    108108    to an instance of ``django.contrib.auth.models.AnonymousUser``. You
    109     can tell them apart with ``is_anonymous()``, like so::
     109    can tell them apart with ``is_logged_in()``, like so::
    110110
    111         if request.user.is_anonymous():
     111        if request.user.is_logged_in():
     112            # Do something for logged-in users.
     113        else:
    112114            # Do something for anonymous users.
    113         else:
    114             # Do something for logged-in users.
    115115
    116116    ``user`` is only available if your Django installation has the
    117117    ``AuthenticationMiddleware`` activated. For more, see
  • docs/authentication.txt

     
    9494In addition to those automatic API methods, ``User`` objects have the following
    9595custom methods:
    9696
    97     * ``is_anonymous()`` -- Always returns ``False``. This is a way of
     97    * ``is_logged_in()`` -- Always returns ``True``. This is a way of
    9898      comparing ``User`` objects to anonymous users.
    9999
    100100    * ``get_full_name()`` -- Returns the ``first_name`` plus the ``last_name``,
     
    218218the ``django.contrib.auth.models.User`` interface, with these differences:
    219219
    220220    * ``id`` is always ``None``.
    221     * ``is_anonymous()`` returns ``True`` instead of ``False``.
     221    * ``is_logged_in()`` returns ``False`` instead of ``True``.
    222222    * ``has_perm()`` always returns ``False``.
    223223    * ``set_password()``, ``check_password()``, ``save()``, ``delete()``,
    224224      ``set_groups()`` and ``set_permissions()`` raise ``NotImplementedError``.
     
    254254``request.user`` in views. ``request.user`` will give you a ``User`` object
    255255representing the currently logged-in user. If a user isn't currently logged in,
    256256``request.user`` will be set to an instance of ``AnonymousUser`` (see the
    257 previous section). You can tell them apart with ``is_anonymous()``, like so::
     257previous section). You can tell them apart with ``is_logged_in()``, like so::
    258258
    259     if request.user.is_anonymous():
     259    if request.user.is_logged_in():
     260        # Do something for logged-in users.
     261    else:
    260262        # Do something for anonymous users.
    261     else:
    262         # Do something for logged-in users.
    263263
    264264.. _request objects: http://www.djangoproject.com/documentation/request_response/#httprequest-objects
    265265.. _session documentation: http://www.djangoproject.com/documentation/sessions/
     
    323323~~~~~~~~~~~
    324324
    325325The simple, raw way to limit access to pages is to check
    326 ``request.user.is_anonymous()`` and either redirect to a login page::
     326``request.user.is_logged_in()`` and either redirect to a login page::
    327327
    328328    from django.http import HttpResponseRedirect
    329329
    330330    def my_view(request):
    331         if request.user.is_anonymous():
     331        if not request.user.is_logged_in():
    332332            return HttpResponseRedirect('/login/?next=%s' % request.path)
    333333        # ...
    334334
    335335...or display an error message::
    336336
    337337    def my_view(request):
    338         if request.user.is_anonymous():
     338        if not request.user.is_logged_in():
    339339            return render_to_response('myapp/login_error.html')
    340340        # ...
    341341
     
    439439permission ``polls.can_vote``::
    440440
    441441    def my_view(request):
    442         if request.user.is_anonymous() or not request.user.has_perm('polls.can_vote'):
     442        if not request.user.is_logged_in() or not request.user.has_perm('polls.can_vote'):
    443443            return HttpResponse("You can't vote in this poll.")
    444444        # ...
    445445
     
    605605The currently logged-in user, either a ``User`` instance or an``AnonymousUser``
    606606instance, is stored in the template variable ``{{ user }}``::
    607607
    608     {% if user.is_anonymous %}
     608    {% if user.is_logged_in %}
     609        <p>Welcome, {{ user.username }}. Thanks for logging in.</p>   
     610    {% else %}
    609611        <p>Welcome, new user. Please log in.</p>
    610     {% else %}
    611         <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
    612612    {% endif %}
    613613
    614614Permissions
Back to Top