Book Image

Mastering Django: Core

By : Nigel George
Book Image

Mastering Django: Core

By: Nigel George

Overview of this book

Mastering Django: Core is a completely revised and updated version of the original Django Book, written by Adrian Holovaty and Jacob Kaplan-Moss - the creators of Django. The main goal of this book is to make you a Django expert. By reading this book, you’ll learn the skills needed to develop powerful websites quickly, with code that is clean and easy to maintain. This book is also a programmer’s manual that provides complete coverage of the current Long Term Support (LTS) version of Django. For developers creating applications for commercial and business critical deployments, Mastering Django: Core provides a complete, up-to-date resource for Django 1.8LTS with a stable code-base, security fixes and support out to 2018.
Table of Contents (33 chapters)
Mastering Django: Core
Credits
About the Author
www.PacktPub.com
Preface
Free Chapter
1
Introduction to Django and Getting Started

Authentication in web requests


Django uses sessions and middleware to hook the authentication system into request objects. These provide a request.user attribute on every request which represents the current user. If the current user has not logged in, this attribute will be set to an instance of AnonymousUser, otherwise it will be an instance of User. You can tell them apart with is_authenticated(), like so:

if request.user.is_authenticated(): 
    # Do something for authenticated users. 
else: 
    # Do something for anonymous users. 

How to log a user in

To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user's ID in the session, using Django's session framework. Note that any data set during the anonymous session is retained in the session after a user logs in. This example shows how you might use both authenticate() and login():

from Django.contrib.auth import authenticate, login 
 
def my_view(request...