Beginners Python Cheat Sheet PCC Django BW
Beginners Python Cheat Sheet PCC Django BW
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 {{ user.username }} 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' %}">
'django.contrib.auth.urls')),
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/', views.register,
{% if user.is_authenticated %}
modify their data. name='register'),
Hello, {{ user.username }}.
]
<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 login.html. The path should be </a> -
After making the app, be sure to add 'accounts' to INSTALLED_ accounts/templates/registration/login.html. <a href="{% url 'accounts:login' %}">
APPS in the project’s settings.py file. The tag {% csrf_token %} helps prevent a common type of Log in
$ python manage.py 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/base.html" %}
Add a line to the project’s urls.py file so the accounts app’s URLs </p>
are included in the project. {% block content %}
from django.contrib import admin {% block content %}{% endblock content %}
from django.urls import path, include {% if form.errors %}
<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/', admin.site.urls), Please try again.
LOGOUT_REDIRECT_URL to settings.py.
path('accounts/', include('accounts.urls')), </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 settings.py 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' ehmatthes.github.io/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 register.html 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/base.html' %} users to an appropriate page. Here’s an example views.py file.
home page. An invalid form displays the registration page again,
with an appropriate error message. {% block content %} from django.contrib.auth.decorators import \
login_required
from django.shortcuts import render, redirect <form action="{% url 'accounts:register' --snip--
from django.contrib.auth import login method='post' %}">
from django.contrib.auth.forms 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 request.method != 'POST': login page. Add the following line to your project’s settings.py file so
</form>
# Display blank registration form. Django will know how to find your login page.
form = UserCreationForm() {% endblock content %} LOGIN_URL = 'accounts:login'
Platform.sh 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 = form.save(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 = request.user
Platform.sh 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 = Topic.objects.filter(
You’ll need to install a set of Platform.sh command line owner=request.user) Weekly posts about all things Python
tools, and use Git to track the state of your project. See
https://platform.sh/marketplace/django for more information. mostlypython.substack.com