Django Beginner's Cheat Sheet
Django Beginner's Cheat Sheet
Django, Part 2
Testing for user.is_authenticated in a template allows you
from . import views to serve specific content to users depending on whether they have
logged in or not. The {{ [Link] }} property allows you to
app_name = 'accounts' greet users who have logged in. Users who haven’t logged in see
urlpatterns = [ links to register or log in.
Users and forms # Include default auth urls.
<p>
path('', include(
Most web applications need to let users make <a href="{% url 'learning_logs:index' %}">
'[Link]')),
accounts, so they can create and work with their own Learning Log
data. Some of this data may be private, and some may </a>
# Registration page.
be public. Django’s forms allow users to enter and path('register/', [Link],
{% if user.is_authenticated %}
modify their data. name='register'),
Hello, {{ [Link] }}.
]
<a href="{% url 'accounts:logout' %}">
User accounts The login template Log out
User accounts are handled by a dedicated app which we'll The login view is provided by default, but you need to provide your </a>
call accounts. Users need to be able to register, log in, and own login template. The template shown here displays a simple {% else %}
log out. Django automates much of this work for you. login form, and provides basic error messages. Make a templates/ <a href="{% url 'accounts:register' %}">
folder in the accounts/ folder, and then make a registration/ folder in Register
Making an accounts app the templates/ folder. Save this file as [Link]. The path should be </a> -
After making the app, be sure to add 'accounts' to INSTALLED_ accounts/templates/registration/[Link]. <a href="{% url 'accounts:login' %}">
APPS in the project’s [Link] file. The tag {% csrf_token %} helps prevent a common type of Log in
$ python [Link] startapp accounts attack with forms. The {{ form.as_div }} element displays the </a>
default login form in an appropriate format. {% endif %}
Including URLs for the accounts app {% extends "learning_logs/[Link]" %}
Add a line to the project’s [Link] file so the accounts app’s URLs </p>
are included in the project. {% block content %}
from [Link] import admin {% block content %}{% endblock content %}
from [Link] import path, include {% if [Link] %}
<p>
The logout form
Django handles logout functionality, but you need to give users
urlpatterns = [ Your username and password didn't match.
a simple form to submit that logs them out. Make sure to add the
path('admin/', [Link]), Please try again.
LOGOUT_REDIRECT_URL to [Link].
path('accounts/', include('[Link]')), </p>
path('', include('learning_logs.urls')), {% endif %} {% if user.is_authenticated %}
] <form action="{% url 'accounts:logout' %}"
<form action="{% url 'users:login' method='post'>
method="post" %}">
Using forms in Django {% csrf_token %}
There are a number of ways to create forms and work {% csrf token %} <button name='submit'>Log out</button>
with them. You can use Django’s defaults, or completely {{ form.as_div }}
customize your forms. For a simple way to let users enter <button name="submit">Log in</button> </form>
data based on your models, use a ModelForm. This creates {% endif %}
a form that allows users to enter data that will populate the </form>
fields on a model.
The register view on the back of this sheet shows a
simple approach to form processing. If the view doesn’t
{% endblock content %} Python Crash Course
receive data from a form, it responds with a blank form. If The logout redirect setting in [Link] A Hands-on, Project-Based
it receives POST data from a form, it validates the data and This setting tells Django where to send users after they log out. Introduction to Programming
then saves it to the database. LOGOUT_REDIRECT_URL = 'learning_logs:index' [Link]/pcc_3e
User accounts (cont.) User accounts (cont.) Connecting data to users (cont.)
The register view The register template Restricting access to logged-in users
The register view needs to display a blank registration form when The [Link] template shown here displays the registration form Some pages are only relevant to registered users. The views for
the page is first requested, and then process completed registration in a simple format. these pages can be protected by the @login_required decorator.
forms. Any view with this decorator will automatically redirect non-logged in
A successful registration logs the user in and redirects to the
{% extends 'learning_logs/[Link]' %} users to an appropriate page. Here’s an example [Link] file.
home page. An invalid form displays the registration page again,
with an appropriate error message. {% block content %} from [Link] import \
login_required
from [Link] import render, redirect <form action="{% url 'accounts:register' --snip--
from [Link] import login method='post' %}">
from [Link] import \ @login_required
UserCreationForm {% csrf_token %} def topic(request, topic_id):
{{ form.as_div }} """Show a topic and all its entries."""
def register(request):
"""Register a new user.""" <button name='submit'>Register</button>
Setting the redirect URL
The @login_required decorator sends unauthorized users to the
if [Link] != 'POST': login page. Add the following line to your project’s [Link] file so
</form>
# Display blank registration form. Django will know how to find your login page.
form = UserCreationForm() {% endblock content %} LOGIN_URL = 'accounts:login'
[Link] lets you push your project to a live server, In a view, the request object has a user attribute. You can use this new_topic = [Link](commit=False)
making it available to anyone with an internet connection. attribute to query for the user’s data. The filter() method shown new_topic.owner = [Link]
[Link] offers a free service level, which lets you learn here pulls the data that belongs to the current user. new_topic.save()
the deployment process without any commitment. topics = [Link](
You’ll need to install a set of [Link] command line owner=[Link]) Weekly posts about all things Python
tools, and use Git to track the state of your project. See
[Link] for more information. [Link]