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

Ogr Django

This document provides a summary of key concepts for getting started with Django, including: 1) Instructions for setting up a Django project including creating a virtual environment, installing Django, initializing a project, and setting up the database. 2) How to create Django apps, models, URLs, views, templates, and add apps to the admin interface. 3) How to create custom Django management commands. 4) An overview of static files, templates, and passing data between views and templates.

Uploaded by

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

Ogr Django

This document provides a summary of key concepts for getting started with Django, including: 1) Instructions for setting up a Django project including creating a virtual environment, installing Django, initializing a project, and setting up the database. 2) How to create Django apps, models, URLs, views, templates, and add apps to the admin interface. 3) How to create custom Django management commands. 4) An overview of static files, templates, and passing data between views and templates.

Uploaded by

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

Django Cheat Sheet

by Olivier R. (OGR) via cheatography.com/143343/cs/30794/

Preparing enviro​nnement

mkdir projec​t_name && cd $_ Create project folder and navigate to it

python -m venv env_name Create venv for the project

source env_na​me​\bin​\ac​tivate Activate enviro​nnement (Replace "​bin​" by "​Scr​ipt​s" in Windows)

pip install django Install Django (and others depend​encies if needed)

pip freeze > requir​eme​nts.txt Create requir​ements file

pip install -r requir​eme​nts.txt Install all required files based on your pip freeze command

git init Version control initia​lis​ation, be sure to create approp​riate gitignore

Create project

django​-admin startp​roject mysite (or I like to call it confi This will create a mysite directory in your current
g) directory the manage.py file

python manage.py runserver You can check that everything went fine

Database Setup

Open up mysite​/se​tti​ngs.py It’s a normal Python module with module​-level variables repres​enting
Django settings.
ENGINE – 'djang​o.d​b.b​ack​end​s.s​qlite3', 'djang​o. If you wish to use another database, install the approp​riate database
d​b.b​ack​end​s.p​ost​gresql', 'djang​o.d​b.b​ack​end bindings and change the following keys in the DATABASES 'default'
​s.m​ysql', or 'djang​o.d​b.b​ack​end​s.o​racle' item to match your database connection settings

NAME – The name of your database. If you’re using SQLite, the The default value, BASE_DIR / 'db.sq​lite3', will store the file in
database will be a file on your computer; in that case, NAME should be your project directory.
the full absolute path, including filename, of that file.
If you are not using SQLite as your database, additional settings such For more details, see the reference docume​ntation for DATABASES.
as USER, PASSWORD, and HOST must be added.

Creating an app

python manage.py startapp app_name Create an app_name directory and all default file/f​older inside

INSTAL​LED​_APPS = [ Apps are "​plu​gab​le", that will "plug in" the app into the project
'app_name',
...

By Olivier R. (OGR) Published 6th February, 2022. Sponsored by Readable.com


cheatography.com/ogr/ Last updated 12th February, 2022. Measure your website readability!
Page 1 of 8. https://readable.com
Django Cheat Sheet
by Olivier R. (OGR) via cheatography.com/143343/cs/30794/

Creating an app (cont)

urlpat​terns = [ Into urls.py from project folder, inculde app urls to project
path('app_name/', include('app_name.urls')),
path('admin/', admin.s​it​e.u​rls),
]

Creating models

Class ModelN​ame​(mo​del​s.M​odel) Create your class in the app_na​me/​mod​els.py file

title = models.Ch​arF​iel​d(m​ax_​len​gt Create your fields


h​=100)

def __str__(self): It’s important to add __str__() methods to your models, because objects’ repres​ent​‐
return self.title ations are used throughout Django’s automa​tic​all​y-g​ene​rated admin.

Database editing

python manage.py makemi​gra​tions (app_nam By running makemi​gra​tions, you’re telling Django that you’ve made some changes
e) to your models

python manage.py sqlmigrate #ident​ifier See what SQL that migration would run.

python manage.py check This checks for any problems in your project without making migrations

python manage.py migrate Create those model tables in your database

python manage.py shell Hop into the intera​ctive Python shell and play around with the free API Django
gives you

Admini​str​ation

python manage.py create​sup​eruser Create a user who can login to the admin site

admin.s​it​e.r​egi​ste​r(M​ode​lName) Into app_na​me/​adm​in.py, add the model to admini​str​ation site

http:/​/12​7.0.0.1​:8​000​/admin/ Open a web browser and go to “/admin/” on your local domain

Management

mkdir app_na​me/​man​agement app_na​me/​man​age​men​t/c​ommands && Create required folders


cd $_

touch your_c​omm​and​_na​me.py Create a python file with your command name

By Olivier R. (OGR) Published 6th February, 2022. Sponsored by Readable.com


cheatography.com/ogr/ Last updated 12th February, 2022. Measure your website readability!
Page 2 of 8. https://readable.com
Django Cheat Sheet
by Olivier R. (OGR) via cheatography.com/143343/cs/30794/

Management (cont)

from django.co​re.m​an​age​men​t.base import BaseCommand Edit your new python file, start
#import anything else you need to work with (models?) with import

class Command(BaseCommand): Create the Command class that


help = "This message will be shon with the --help option after your command" will handle your command

def handle​(self, args, *kwargs):


# Work the command is supposed to do

python manage.py my_cus​tom​_co​mmand And this is how you execute your


custom command

Django lets you create your customs CLI commands

Write your first view

from django.http import HttpResponse Open the file app_na​me/​vie​ws.py and put the following
def index(request): Python code in it.
return HttpRe​spo​nse​("Hello, world. You're at the index This is the simplest view possible.
."​)

from django.urls import path In the app_na​me/​urls.py file include the following code.
from . import views

app_name = "app_name"
urlpatterns = [
path('', views.i​ndex, name='index'),
]

View with argument

def detail​(re​quest, question_id): Exemple of view with an arugment


return HttpRe​spo​nse​(f"Y​ou're looking at question {quest​ion​_id
​}")

urlpat​terns = [ See how we pass argument in path


path('<int:question_id>/', views.d​etail, name='detail'),
...

{% url 'app_n​ame​:vi​ew_​name' questi​on_id %} We can pass attribute from template this way

By Olivier R. (OGR) Published 6th February, 2022. Sponsored by Readable.com


cheatography.com/ogr/ Last updated 12th February, 2022. Measure your website readability!
Page 3 of 8. https://readable.com
Django Cheat Sheet
by Olivier R. (OGR) via cheatography.com/143343/cs/30794/

View with Template

app_na​me/​tem​pla​tes​/ap​p_n​ame​/in​dex.html This is the folder path to follow for template

context = {'key': value} Pass values from view to template

return render​(re​quest, 'app_n​ame​/in​dex.html', conte Exemple of use of render shortcut


xt)

{% Code %} Edit template with those. Full list here


{{ Variavle from view's context dict }}
<a href="{% url 'detail' questi​on.id %}">​</a>

<ti​tle​>Page Title<​/ti​tle> you can put this on top of your html template to define page title

Add some static files

'djang​o.c​ont​rib.st​ati​cfiles' Be sure to have this in your


INSTAL​LED​_APPS
STATIC_URL = 'static/' The given exemples are for this
config
mkdir app_na​me/​static app_na​me/​sta​tic​/ap​p_name Create static folder associated
with your app
{% load static %} Put this on top of your template

<link rel="st​yle​she​et" type="t​ext​/cs​s" href="{% static 'app_n​ame​/st​yle. Exemple of use of static.


css' %}">

Raising 404

raise Http40​4("Q​uestion does not exist") in a try / except statement

question = get_ob​jec​t_o​r_4​04(​Que​stion, pk=que​sti​on_id) A shortcut

Forms

app_na​me/​for​ms.py Create your form classes here

from django import forms Import django's forms module

from .models import YourModel import models you need to work with

class ExempleForm(forms.Form): For very simple forms, we can use simple


exemple_field = forms.C​ha​rFi​eld​(la​bel​='E​xemple label', max_le​n Form class
gt​h=100)

class ExempleForm(forms.ModelForm): A ModelForm maps a model class’s fields


class meta: to HTML form <in​put> elements via a
model = model_name Form. Widget is optional. Use it to
fields = ["fields"] override default widget
labels = {"te​xt": "label_text"}
widget = {"te​xt": forms.w​id​get​_name}

TextInput, EmailI​nput, Passwo​rdI​nput, DateInput, Textarea Most common widget list

if reques​t.m​ethod != "POST": Create a blank form if no data submitted


form = Exempl​eForm()

By Olivier R. (OGR) Published 6th February, 2022. Sponsored by Readable.com


cheatography.com/ogr/ Last updated 12th February, 2022. Measure your website readability!
Page 4 of 8. https://readable.com
Django Cheat Sheet
by Olivier R. (OGR) via cheatography.com/143343/cs/30794/

Forms (cont)

form = Exempl​eFo​rm(​dat​a=r​equ​est.POST) The form object contain's the inform​ations submitted by the
user
is form.isvalid() Form valida​tion. Always use redirect function
form.save()
return redire​ct(​"​app​_na​me:​vie​w_n​ame​", argume​nt
=​ard​ument)

{% csrf_token %} Template tag to prevent "​cro​ss-site request forger​y" attack

Render Form In Template

{{ form.as_p }} The most simple way to render the form, but usualy it's ugly

{{ field|​pla​ceh​old​er:​fie​ld.l​abel }} The | is a filter, and here for placeh​older, it's a custom one. See next
{{ form.u​ser​nam​e|p​lac​eho​lde​r:"Your name section to see how to create it
here"}}

{% for field in form %} You can extract each fields with a for loop.
{{form.username}} Or by explicitly specifying the field

Custom template tags and filters

app_na​me​\tem​pla​tet​ags​\__​ini​t__.py Create this folder and this file. Leave it blank

app_na​me​\tem​pla​tet​ags​\fi​lte​r_n​ame.py Create a python file with the name of the filter

{% load filter​_name %} Add this on top of your template

from django import template To be a valid tag library, the module must contain a
module​-level variable named register
register = templa​te.L​ib​rary() that is a templa​te.L​ibrary instance

@regis​ter.fi​lte​r(n​ame​='cut') Here is an exemple of filter defini​tion.


def cut(value, arg): See the decorator? It registers your filter with your
"​"​"​Removes all values of arg from the given string​"​" Library instance.
​" You need to restart server for this to take effects
return value.r​ep​lac​e(arg, '')

https:​//t​ech.se​rha​tte​ker.co​m/p​ost​/20​21-​06/​pla​ceh​old​er-​tem​pla​tetags/ Here is a link of how to make a placeh​older custom


template tag

By Olivier R. (OGR) Published 6th February, 2022. Sponsored by Readable.com


cheatography.com/ogr/ Last updated 12th February, 2022. Measure your website readability!
Page 5 of 8. https://readable.com
Django Cheat Sheet
by Olivier R. (OGR) via cheatography.com/143343/cs/30794/

Setting Up User Accounts

Create a "​use​rs" app Don't forget to add app to settin​gs.py and include th
from users.
app_name = "users" Inside app_na​me/​urls.py (create it if inexistent),
urlpatterns[ this code includes some default authen​tif​ication UR
# include default auth urls. Django has defined.
path("", include("django.contribe.auth.urls"))
]

{% if form.error %} Basic login.html template


<p>Your username and password didn't match</p> Save it at save template as
{% endif %} users/templates/registration/login.html
<form method​="po​st" action​="{% url 'users​:login' %}"> We can access to it by using
{% csrf_token %} <a href="{% url 'users​:login' %}">Log

{{ form.as_p }} a>

<button name="s​ubm​it">Log in</button>


<input type="h​idd​en" name="n​ext​" value=​" {% url 'app_n​ame​:index'
%}" />
</form>

{% if user.i​s_a​uth​ent​icated %} Check if user is logged in

{% url "​use​rs:​log​out​" %} Link to logout page, and log out the user
save template as users/​tem​pla​tes​/re​gis​tra​tio​n/l​ogg​e
out.html
path("r​egi​ste​r/", views.r​eg​ister, name="r​egi​ste​r"), Inside app_na​me/​url​s.py, add path to register

from django.sh​ortcuts import render, redirect We write our own register() view inside users/views
from django.co​ntr​ib.auth import login For that we use UserCr​eat​ion​Form, a django buildin
from django.co​ntr​ib.f​orms import UserCreationForm model.
If method is not post, we render a blank form
def register(request): Else, is the form pass the validity check, an user is

if reques​t.m​ethod != "POST": We just have to create a regist​rat​ion.html template


folder as the login and logged_out
form = UserCreationForm()
else:
form = UserCreationForm(data=request.POST)

if form.is_valid():
new_user = form.save()
login(request, new_user)
return redirect("app_name:index")

context = {"fo​rm": form}


return render​(re​quest, "​reg​ist​rat​ion​/re​gis​ter.ht​ml", context)

By Olivier R. (OGR) Published 6th February, 2022. Sponsored by Readable.com


cheatography.com/ogr/ Last updated 12th February, 2022. Measure your website readability!
Page 6 of 8. https://readable.com
Django Cheat Sheet
by Olivier R. (OGR) via cheatography.com/143343/cs/30794/

Allow Users to Own Their Data

... Restrict access with @login​_re​quired decorator


from django.co​ntr​ib.a​ut​h.d​eco​rators import login_requ
ired If user is not logged in, they will be redirect to the login page
... To make this work, you need to modify settin​gs.py so Django
knows where to find the login page

@login_required Add the following at the very end


# My settings
def my_view(request)
LOGIN_URL = "​use​rs:​log​in"
...

... Add this field to your models to connect data to certain users
from django.co​ntr​ib.a​ut​h.m​odels import User
... When migrating, you will be prompt to select a default value
owner = models.Fo​rei​gnK​ey(​User, on_del​ete​=mo​del​s.C​‐
ASCADE)

user_data = Exempl​eMo​del.ob​jec​ts.f​il​ter​(ow​ner​=re​q Use this kind of code in your views to filter data of a specific
ue​st.u​ser) user
request.user only exist when user is logged in
... Make sure the data belongs to the current user
from django.http import Http404
... If not the case, we raise a 404

...
if exempl​e_d​ata.owner != request.user:
raise Http404

new_data = form.save(commit=false) Don't forget to associate user to your data in corres​ponding


new_data.owner = request.user views
new_data.save()
The "​com​mit​=fa​lse​" attribute let us do that

Paginator

from django.co​re.p​ag​inator import Paginator In app_na​me/​vie​ws.py, import Paginator

exempl​e_list = Exempl​e.o​bje​cts.all() In your class view, Get a list of data

paginator = Pagina​tor​(ex​emp​le_​list, 5) # Show 5 items per pag Set approp​riate pagination


e.

page_n​umber = reques​t.G​ET.g​et​('p​age') Get actual page number

page_obj = pagina​tor.ge​t_p​age​(pa​ge_​number) Create your Page Object, and put it in the context

{% for item in page_obj %} The Page Object acts now like your list of data

By Olivier R. (OGR) Published 6th February, 2022. Sponsored by Readable.com


cheatography.com/ogr/ Last updated 12th February, 2022. Measure your website readability!
Page 7 of 8. https://readable.com
Django Cheat Sheet
by Olivier R. (OGR) via cheatography.com/143343/cs/30794/

Paginator (cont)

<div class="pagination"> An
<span class="step-links"> exemple
{% if page_o​bj.h​as​_pr​evious %} of what
<a href="?​pag​e=1​"​>&​laquo; first</a> to put on
<a href="?page={{ page_o​bj.p​re​vio​us_​pag​e_n​umber }}">previous</a> the

{% endif %} bottom
of your
<span class=​"​cur​ren​t"> Page {{ page_o​bj.n​umber }} of {{ page_o​bj.p​ag​ina​tor.nu​m_pages
page
}}. </span>
to
{% if page_o​bj.h​as​_next %}
navigate
<a href="?page={{ page_o​bj.n​ex​t_p​age​_number }}">​nex​t</​a>
through
<a href="?page={{ page_o​bj.p​ag​ina​tor.nu​m_pages }}">last &r​aqu​o;<​/a>
Page
{% endif %}
Objects
</s​pan>
</d​iv>

Deploy to Heroku

https:​//h​ero​ku.com Make a Heroku account


https:​//d​evc​ent​er.h​er​oku.com:artic​les​/he​rok​u-cli/ Install Heroku CLI
pip install psycog2 install these packages
pip install django​-heroku
pip install gunicorn

pip freeze > requir​​em​e​n​ts.txt updtate requir​eme​nts.txt

# Heroku settings. At the very end of settin​gs.py, make an Heroku ettings section
import django​_heroku import django​_heroku and tell django to apply django heroku settings
django​_he​rok​u.s​ett​ing​s(l​oca​ls(), static​fil The static​files to false is not a viable option in produc​tion, check
​es=​False) whitenoise for that IMO
if os.env​iro​n.g​et(​'DE​BUG') == "​TRU​E":
DEBUG = True
elif os.env​iro​n.g​et(​'DE​BUG') == "​FAL​SE":
DEBUG = False

By Olivier R. (OGR) Published 6th February, 2022. Sponsored by Readable.com


cheatography.com/ogr/ Last updated 12th February, 2022. Measure your website readability!
Page 8 of 8. https://readable.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy