0% found this document useful (0 votes)
20 views

Beginners Python Cheat Sheet PCC Django BW

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Beginners Python Cheat Sheet PCC Django BW

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Beginner's Python

Working with models Building a simple home page


The data in a Django project is structured as a set of models. Users interact with a project through web pages, and a
Each model is represented by a class. project’s home page can start out as a simple page with no

Cheat Sheet - Django Defining a model


To define the models for your app, modify the models.py file that
was created in your app’s folder. The __str__() method tells
data. A page usually needs a URL, a view, and a template.
Mapping a project's URLs
The project’s main urls.py file tells Django where to find the urls.py
Django how to represent data objects based on this model. files associated with each app in the project.
What is Django? from django.db import models from django.contrib import admin
Django is a web framework that helps you build from django.urls import path, include
interactive websites using Python. With Django you class Topic(models.Model):
define the kind of data your site will work with, and the """A topic the user is learning about.""" urlpatterns = [
ways your users can work with that data. path('admin/', admin.site.urls),
text = models.CharField(max_length=200) path('', include('learning_logs.urls')),
Django works well for tiny projects, and just as well date_added = models.DateTimeField( ]
for sites with millions of users. auto_now_add=True)
Mapping an app's URLs
Installing Django def __str__(self): An app’s urls.py file tells Django which view to use for each URL
It’s best to install Django to a virtual environment, where return self.text in the app. You’ll need to make this file yourself, and save it in the
app’s folder.
your project can be isolated from your other Python projects.
Activating a model
Most commands assume you’re working in an active virtual from django.urls import path
To use a model the app must be added to the list INSTALLED_APPS,
environment.
which is stored in the project’s settings.py file.
from . import views
Create a virtual environment INSTALLED_APPS = [
$ python –m venv ll_env # My apps. app_name = 'learning_logs'
'learning_logs', urlpatterns = [
Activate the environment (macOS and Linux) # Home page.
$ source ll_env/bin/activate # Default Django apps. path('', views.index, name='index'),
'django.contrib.admin', ]
Activate the environment (Windows) ]
Writing a simple view
> ll_env\Scripts\activate Migrating the database A view takes information from a request and sends data to the
Install Django to the active environment The database needs to be modified to store the kind of data that the browser, often through a template. View functions are stored in an
model represents. You'll need to run these commands every time app’s views.py file. This simple view function doesn’t pull in any
(ll_env)$ pip install Django you create a new model, or modify an existing model. data, but it uses the template index.html to render the home page.
$ python manage.py makemigrations learning_logs from django.shortcuts import render
Creating a project $ python manage.py migrate
To start we’ll create a new project, create a database, and def index(request):
Creating a superuser """The home page for Learning Log."""
start a development server.
A superuser is a user account that has access to all aspects of the return render(request,
Create a new project project. 'learning_logs/index.html')
Make sure to include the dot at the end of this command. $ python manage.py createsuperuser
$ django-admin startproject ll_project .
Registering a model
Online resources
Create a database You can register your models with Django’s admin site, which makes The documentation for Django is available at
it easier to work with the data in your project. To do this, modify the docs.djangoproject.com/. The Django documentation is
$ python manage.py migrate app’s admin.py file. View the admin site at http://localhost:8000/ thorough and user-friendly, so check it out!
View the project admin/. You'll need to log in using a superuser account.
After issuing this command, you can view the project at http:// from django.contrib import admin
localhost:8000/.
from .models import Topic
Python Crash Course
$ python manage.py runserver A Hands-on, Project-Based
Create a new app admin.site.register(Topic) Introduction to Programming
A Django project is made up of one or more apps. ehmatthes.github.io/pcc_3e
$ python manage.py startapp learning_logs
Building a simple home page (cont.) Another model Building a page with data (cont.)
Writing a simple template A new model can use an existing model. The ForeignKey Using data in a template
A template sets up the structure for a page. It’s a mix of html and attribute establishes a connection between instances of the The data in the view function’s context dictionary is available within
template code, which is like Python but not as powerful. Most of the two related models. Make sure to migrate the database after the template. This data is accessed using template variables, which
logic for your project should be written in .py files, but some logic is adding a new model to your app. are indicated by doubled curly braces.
appropriate for templates. The vertical line after a template variable indicates a filter. In
Make a folder called templates/ inside the project folder. Inside Defining a model with a foreign key this case a filter called date formats date objects, and the filter
the templates/ folder make another folder with the same name as class Entry(models.Model): linebreaks renders paragraphs properly on a web page.
the app. This is where the template files should be saved. The home """Learning log entries for a topic."""
page template will be saved as learning_logs/templates/learning_ {% extends 'learning_logs/base.html' %}
topic = models.ForeignKey(Topic,
logs/index.html.
on_delete=models.CASCADE) {% block content %}
<p>Learning Log</p> text = models.TextField()
date_added = models.DateTimeField( <p>Topic: {{ topic }}</p>
<p>Learning Log helps you keep track of your auto_now_add=True)
learning, for any topic you're learning <p>Entries:</p>
about.</p> def __str__(self): <ul>
return f"{self.text[:50]}..." {% for entry in entries %}
Template Inheritance <li>
Many elements of a web page are repeated on every page Building a page with data <p>
Most pages in a project need to present data that’s specific {{ entry.date_added|date:'M d, Y H:i' }}
in the site, or every page in a section of the site. By writing
</p>
one parent template for the site, and one for each section, to the current user.
you can easily modify the look and feel of your entire site. URL parameters <p>
The parent template A URL often needs to accept a parameter telling it what data to {{ entry.text|linebreaks }}
The parent template defines the elements common to a set of access from the database. The URL pattern shown here looks for </p>
pages, and defines blocks that will be filled by individual pages. the ID of a specific topic and assigns it to the parameter topic_id. </li>
urlpatterns = [ {% empty %}
<p> <li>There are no entries yet.</li>
<a href="{% url 'learning_logs:index' %}"> --snip--
# Detail page for a single topic. {% endfor %}
Learning Log </ul>
</a> path('topics/<int:topic_id>/', views.topic,
</p> name='topic'),
] {% endblock content %}
{% block content %}{% endblock content %}
Using data in a view The Django shell
The child template The view uses a parameter from the URL to pull the correct data
You can explore the data in your project from the command
The child template uses the {% extends %} template tag to pull in from the database. In this example the view is sending a context
dictionary to the template, containing data that should be displayed line. This is helpful for developing queries and testing code
the structure of the parent template. It then defines the content for
on the page. You'll need to import any model you're using. snippets.
any blocks defined in the parent template.
{% extends 'learning_logs/base.html' %} def topic(request, topic_id): Start a shell session
"""Show a topic and all its entries.""" $ python manage.py shell
{% block content %} topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by( Access data from the project
<p> '-date_added')
>>> from learning_logs.models import Topic
Learning Log helps you keep track context = {
>>> Topic.objects.all()
of your learning, for any topic you're 'topic': topic,
[<Topic: Chess>, <Topic: Rock Climbing>]
learning about. 'entries': entries,
>>> topic = Topic.objects.get(id=1)
</p> }
>>> topic.text
return render(request,
'Chess'
{% endblock content %} 'learning_logs/topic.html', context)
>>> topic.entry_set.all()
<QuerySet [<Entry: In the opening phase...>]>
Template indentation Restarting the development server
Python code is usually indented by four spaces. In templates If you make a change to your project and the change doesn’t
you’ll often see two spaces used for indentation, because seem to have any effect, try restarting the server: Weekly posts about all things Python
elements tend to be nested more deeply in templates. $ python manage.py runserver mostlypython.substack.com
Beginner's Python
User accounts (cont.) User accounts (cont.)
Defining the URLs Showing the current login status
Users will need to be able to log in, log out, and register. Make a You can modify the base.html template to show whether the user

Cheat Sheet - new urls.py file in the users app folder.


from django.urls import path, include
is currently logged in, and to provide a link to the login and logout
pages. Django makes a user object available to every template,
and this template takes advantage of this object.

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'

else: Preventing inadvertent access


# Process completed form. Connecting data to users Some pages serve data based on a parameter in the URL. You can
form = UserCreationForm( Users will create some data that belongs to them. Any model check that the current user owns the requested data, and return a
data=request.POST) that should be connected directly to a user needs a field 404 error if they don’t. Here’s an example view.
connecting instances of the model to a specific user. from django.http import Http404
if form.is_valid(): --snip--
new_user = form.save()
Making a topic belong to a user
Only the highest-level data in a hierarchy needs to be directly
connected to a user. To do this import the User model, and add it as @login_required
# Log in, redirect to home page. def topic(request, topic_id):
a foreign key on the data model.
login(request, new_user) After modifying the model you’ll need to migrate the database. """Show a topic and all its entries."""
return redirect( You’ll need to choose a user ID to connect each existing instance to. topic = Topics.objects.get(id=topic_id)
'learning_logs:index') if topic.owner != request.user:
from django.db import models
raise Http404
# Display a blank or invalid form. from django.contrib.auth.models import User
--snip--
context = {'form': form}
class Topic(models.Model):
return render(request, """A topic the user is learning about.""" Using a form to edit data
'registration/register.html', context) If you provide some initial data, Django generates a form
text = models.CharField(max_length=200) with the user’s existing data. Users can then modify and
date_added = models.DateTimeField( save their data.
Styling your project auto_now_add=True)
The django-bootstrap5 app allows you to use the Creating a form with initial data
Bootstrap library to make your project look visually owner = models.ForeignKey(User, The instance parameter allows you to specify initial data for a form.
appealing. The app provides tags that you can use in your on_delete=models.CASCADE) form = EntryForm(instance=entry)
templates to style individual elements on a page. Learn
more at django-bootstrap5.readthedocs.io/. def __str__(self): Modifying data before saving
return self.text The argument commit=False allows you to make changes before
Deploying your project Querying data for the current user
writing data to the database.

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

You might also like