A cheat-sheet for creating web apps with the Django framework using the Python language. Most of the summaries and examples are based off the official documentation for Django v2.0.
- Still within the app directory, open (or create) `urls.py`
```python
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Now within the project directory, edit urls.py to include the following
from django.contrib import admin
from django.urls import include, path
- To include context to the template:
```python
def index(request):
context = {"context_variable": context_variable}
return render(request,'index.html', context)
Within the HTML file, you can reference static files by adding the following:
{% load static %}
<!DOCTYPE html>
- To make sure to include the following in your `settings,py`:
```python
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
To add an extends:
{% extends 'base.html'% }
{% block content %}
Hello, World!
{% endblock %}
- And then in `base.html` add:
```html
<body>
{% block content %}{% endblock %}
</body>
:ticket: Creating a model
Within the app's models.py file, an example of a simple model can be added with the following:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
*Note that you don't need to create a primary key, Django automatically adds an IntegerField.*
- To inact changes in your models, use the following commands in your shell:
*Note: including <app_name> is optional.*
- A one-to-many relationship can be made with a `ForeignKey`:
```python
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
In this example, to query for the set of albums of a musician:
>>> m = Musician.objects.get(pk=1)
>>> a = m.album_set.get()
A many-to-many relationship can be made with a ManyToManyField:
class Topping(models.Model):
# ...
pass
class Pizza(models.Model):
...
toppings = models.ManyToManyField(Topping)
*Note that the `ManyToManyField` is **only defined in one model**. It doesn't matter which model has the field, but if in doubt, it should be in the model that will be interacted with in a form.*
- Although Django provides a `OneToOneField` relation, a one-to-one relationship can also be defined by adding the kwarg of `unique = True` to a model's `ForeignKey`:
```python
ForeignKey(SomeModel, unique=True)
:scroll: Django Cheat Sheet
A cheat-sheet for creating web apps with the Django framework using the Python language. Most of the summaries and examples are based off the official documentation for Django v2.0.
Sections
:snake: Initializing pipenv (optional)
$ mkdir <folder>
and navigate to it with$ cd <folder>
$ pipenv install
$ pipenv shell
$ pipenv install django
$ pipenv install <package_name>
:blue_book: Creating a project
$ cd <folder>
$ django-admin startproject <project_name>
The project directory should look like this:
$ python manage.py runserver
within the project directorySECRET_KEY
to be more secure, you can set it to reference an environment variablesettings.py
file within the project directory change theSECRET_KEY
line to the following:export SECRET_KEY=<secret_key>
:page_with_curl: Creating an app
$ cd <outer_project_folder>
$ python manage.py startapp <app_name>
app
folder, create a file calledurls.py
The project directory should now look like this:
settings.py
file by adding its name to theINSTALLED_APPS
list::tv: Creating a view
views.py
and add the following:def index(request): return HttpResponse("Hello, World!")
urls.py
to include the followingurlpatterns = [ path('app/', include('app.urls')), path('admin/', admin.site.urls), ]
urls.py
urls.py
file within app directories are organized by theurls.py
found in the project folder.:art: Creating a template
views.py
within the app directory and include the following:def index(request): return render(request,'index.html')
<!DOCTYPE html>
extends
:{% block content %}
Hello, World!
{% endblock %}
:ticket: Creating a model
models.py
file, an example of a simple model can be added with the following:class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)
$ python manage.py makemigrations
$ python manage.py migrate
In this example, to query for the set of albums of a musician:
A many-to-many relationship can be made with a
ManyToManyField
:class Pizza(models.Model):
...
:postbox: Creating model objects and queries
models.py
file:class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField()
class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField()
class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) n_comments = models.IntegerField() n_pingbacks = models.IntegerField() rating = models.IntegerField()
$ python manage.py shell
:man: Using the Admin page
superuser
:admin.py
:admin.site.register(Author) admin.site.register(Book)