Ogr Django
Ogr Django
Preparing environnement
pip install -r requirements.txt Install all required files based on your pip freeze command
Create project
django-admin startproject 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/settings.py It’s a normal Python module with module-level variables representing
Django settings.
ENGINE – 'django.db.backends.sqlite3', 'django. If you wish to use another database, install the appropriate database
db.backends.postgresql', 'django.db.backend bindings and change the following keys in the DATABASES 'default'
s.mysql', or 'django.db.backends.oracle' 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.sqlite3', 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 documentation 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/folder inside
INSTALLED_APPS = [ Apps are "plugable", that will "plug in" the app into the project
'app_name',
...
urlpatterns = [ Into urls.py from project folder, inculde app urls to project
path('app_name/', include('app_name.urls')),
path('admin/', admin.site.urls),
]
Creating models
def __str__(self): It’s important to add __str__() methods to your models, because objects’ represent‐
return self.title ations are used throughout Django’s automatically-generated admin.
Database editing
python manage.py makemigrations (app_nam By running makemigrations, you’re telling Django that you’ve made some changes
e) to your models
python manage.py sqlmigrate #identifier 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 shell Hop into the interactive Python shell and play around with the free API Django
gives you
Administration
python manage.py createsuperuser Create a user who can login to the admin site
Management
Management (cont)
from django.core.management.base import BaseCommand Edit your new python file, start
#import anything else you need to work with (models?) with import
from django.http import HttpResponse Open the file app_name/views.py and put the following
def index(request): Python code in it.
return HttpResponse("Hello, world. You're at the index This is the simplest view possible.
.")
from django.urls import path In the app_name/urls.py file include the following code.
from . import views
app_name = "app_name"
urlpatterns = [
path('', views.index, name='index'),
]
{% url 'app_name:view_name' question_id %} We can pass attribute from template this way
<title>Page Title</title> you can put this on top of your html template to define page title
Raising 404
Forms
from .models import YourModel import models you need to work with
Forms (cont)
form = ExempleForm(data=request.POST) The form object contain's the informations submitted by the
user
is form.isvalid() Form validation. Always use redirect function
form.save()
return redirect("app_name:view_name", argument
=ardument)
{{ form.as_p }} The most simple way to render the form, but usualy it's ugly
{{ field|placeholder:field.label }} The | is a filter, and here for placeholder, it's a custom one. See next
{{ form.username|placeholder:"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
from django import template To be a valid tag library, the module must contain a
module-level variable named register
register = template.Library() that is a template.Library instance
Create a "users" app Don't forget to add app to settings.py and include th
from users.
app_name = "users" Inside app_name/urls.py (create it if inexistent),
urlpatterns[ this code includes some default authentification UR
# include default auth urls. Django has defined.
path("", include("django.contribe.auth.urls"))
]
{{ form.as_p }} a>
{% url "users:logout" %} Link to logout page, and log out the user
save template as users/templates/registration/logge
out.html
path("register/", views.register, name="register"), Inside app_name/urls.py, add path to register
from django.shortcuts import render, redirect We write our own register() view inside users/views
from django.contrib.auth import login For that we use UserCreationForm, a django buildin
from django.contrib.forms 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 form.is_valid():
new_user = form.save()
login(request, new_user)
return redirect("app_name:index")
... Add this field to your models to connect data to certain users
from django.contrib.auth.models import User
... When migrating, you will be prompt to select a default value
owner = models.ForeignKey(User, on_delete=models.C‐
ASCADE)
user_data = ExempleModel.objects.filter(owner=req Use this kind of code in your views to filter data of a specific
uest.user) 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 exemple_data.owner != request.user:
raise Http404
Paginator
page_obj = paginator.get_page(page_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
Paginator (cont)
<div class="pagination"> An
<span class="step-links"> exemple
{% if page_obj.has_previous %} of what
<a href="?page=1">« first</a> to put on
<a href="?page={{ page_obj.previous_page_number }}">previous</a> the
{% endif %} bottom
of your
<span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages
page
}}. </span>
to
{% if page_obj.has_next %}
navigate
<a href="?page={{ page_obj.next_page_number }}">next</a>
through
<a href="?page={{ page_obj.paginator.num_pages }}">last »</a>
Page
{% endif %}
Objects
</span>
</div>
Deploy to Heroku
# Heroku settings. At the very end of settings.py, make an Heroku ettings section
import django_heroku import django_heroku and tell django to apply django heroku settings
django_heroku.settings(locals(), staticfil The staticfiles to false is not a viable option in production, check
es=False) whitenoise for that IMO
if os.environ.get('DEBUG') == "TRUE":
DEBUG = True
elif os.environ.get('DEBUG') == "FALSE":
DEBUG = False