Django is a Python framework that makes it easier to create web sites using Python.
Django takes care of the difficult stuff so that you can concentrate on building your web applications.
Django emphasizes reusability of components, also referred to as DRY (Don't Repeat Yourself), and comes with ready-to-use features like login system, database connection and CRUD operations (Create Read Update Delete).
py -m venv env
env\Scripts\activate
py -m pip install Django
django-admin --version
py -m pip freeze > requirements.txt
pip install -r requirements.txt
django-admin startproject my_project
cd my_project
python manage.py runserver
py manage.py makemigrations
py manage.py migrate
py manage.py shell
python manage.py startapp app_name
from django.shortcuts import render
from django.http import HttpResponse
def members(request):
return HttpResponse("Hello world!")
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('members.urls')),
path('admin/', admin.site.urls),
]
py manage.py sqlmigrate app_name migrate_number
from django.db import modelsclass Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
py manage.py shell
from members.models import Member
Member.objects.all()
member = Member(firstname='Emil', lastname='Refsnes')
member.save()
Member.objects.all().values()
member1 = Member(firstname='Tobias', lastname='Refsnes')
member2 = Member(firstname='Linus', lastname='Refsnes')
member3 = Member(firstname='Lene', lastname='Refsnes')
member4 = Member(firstname='Stale', lastname='Refsnes')
member5 = Member(firstname='Jane', lastname='Doe')
members_list = [member1, member2, member3, member4, member5]
for x in members_list:
x.save()
from members.models import Member
x = Member.objects.all()[4]
x.firstname = "Stalikken"
x.save()
from members.models import Member
x = Member.objects.all()[4]
x.delete()
from django.db import modelsclass Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
phone = models.IntegerField(null=True)
joined_date = models.DateField(null=True)
py manage.py shell
from members.models import Member
x = Member.objects.all()[0]
x.phone = 5551234
x.joined_date = '2022-01-05'
x.save()
{% for x in mymembers %}
- {{ x.firstname }} {{ x.lastname }}
{% endfor %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<title>{% block title %}{% endblock %}</title>
{% block css %}{% endblock %}
</head>
<body>
{% block content %}{% endblock %}
{% block js %}{% endblock %}
</body>
</html>
py manage.py createsuperuser
from django.contrib import admin
admin.site.register(Member)
def __str__(self):
return f"{self.firstname} {self.lastname}"
class MemberAdmin(admin.ModelAdmin):
list_display = ("firstname", "lastname", "joined_date",)
admin.site.register(Member, MemberAdmin)
<h1>Hello {{ firstname }}, how are you?</h1>
context = {
'firstname': 'Linus',
}
{% with firstname="Tobias" %}
<h1>Hello {{ firstname }}, how are you?</h1>
from .models import Member
mymembers = Member.objects.all().values()
context = {
'mymembers': mymembers,
}
{% for x in mymembers %}
<li>{{ x.firstname }}</li>
{% endfor %}
Tag | Description |
---|---|
autoescape | Specifies if autoescape mode is on or off |
block | Specifies a block section |
comment | Specifies a comment section |
csrf_token | Protects forms from Cross Site Request Forgeries |
cycle | Specifies content to use in each cycle of a loop |
debug | Specifies debugging information |
extends | Specifies a parent template |
filter | Filters content before returning it |
firstof | Returns the first not empty variable |
for | Specifies a for loop |
if | Specifies a if statement |
ifchanged | Used in for loops. Outputs a block only if a value has changed since the last iteration |
include | Specifies included content/template |
load | Loads template tags from another library |
lorem | Outputs random text |
now | Outputs the current date/time |
regroup | Sorts an object by a group |
resetcycle | Used in cycles. Resets the cycle |
spaceless | Removes whitespace between HTML tags |
templatetag | Outputs a specified template tag |
url | Returns the absolute URL part of a URL |
verbatim | Specifies contents that should not be rendered by the template engine |
widthratio | Calculates a width value based on the ratio between a given value and a max value |
with | Specifies a variable to use in the block |
{% if greeting == 1 %}
{% endif %}
{% if greeting == 1 %}
{% elif greeting == 2 %}
{% endif %}
{% if greeting == 1 %}
{% elif greeting == 2 %}
{% else %}
{% endif %}
{% if greeting == 2 %}
{% endif %}
{% if greeting == 2 %}
{% endif %}
{% if greeting ! = 2 %}
{% endif %}
{% if greeting < 2 %}
{% endif %}
{% if greeting == 1 and day == "Friday" %}
{% endif %}
{% if greeting == 2 %}
{% endif %}
{% if greeting == 1 or greeting == 5 %}
{% endif %}
{% if 'Banana' in fruits %}
{% endif %}
{% if 'Banana' not in fruits %}
{% endif %}
{% if x is y %}
{% else %}
{% endif %}
{% for x in fruits %}{% endfor %}
{% for x in members reversed %}
{% endfor %}
{% for x in emptytestobject %}
{% empty %} {% endfor %}
{% for x in fruits %} {{ forloop.counter }} {% endfor %}
{% for x in fruits %} {{ forloop.counter0 }} {% endfor %}
{% for x in fruits %}
<li
{% if forloop.first %}
style='background-color:lightblue;'
{% endif %}
>{{ x }}</li>
{% endfor %}
{% for x in fruits %}
<li
{% if forloop.last %}
style='background-color:lightblue;'
{% endif %}
>{{ x }}</li>
{% endfor %}
{% for x in fruits %}
{{ forloop.revcounter }}
{% endfor %}
{% for x in fruits %}
{{ forloop.revcounter0 }}
{% endfor %}
{% comment %}
{% endcomment %}
{% comment "this was the original welcome message" %}
{% endcomment %}
<h1>Welcome{# Everyone#}</h1>
{% include 'footer.html' %}
{% include "mymenu.html" with me="TOBIAS" sponsor="W3SCHOOLS" %}
<div>HOME | {{ me }} | ABOUT | FORUM | {{ sponsor }}</div>
mydata = Member.objects.filter(firstname='Emil').values()
mydata = Member.objects.filter(lastname='Refsnes', id=2).values()
mydata = Member.objects.filter(firstname='Emil').values() | Member.objects.filter(firstname='Tobias').values()
from django.db.models import Qmydata = Member.objects.filter(Q(firstname='Emil') | Q(firstname='Tobias')).values()
.filter(firstname__startswith='L');
Keyword | Description |
---|---|
contains | Contains the phrase |
icontains | Same as contains, but case-insensitive |
date | Matches a date |
day | Matches a date (day of month, 1-31) (for dates) |
endswith | Ends with |
iendswith | Same as endswidth, but case-insensitive |
exact | An exact match |
iexact | Same as exact, but case-insensitive |
in | Matches one of the values |
isnull | Matches NULL values |
gt | Greater than |
gte | Greater than, or equal to |
hour | Matches an hour (for datetimes) |
lt | Less than |
lte | Less than, or equal to |
minute | Matches a minute (for datetimes) |
month | Matches a month (for dates) |
quarter | Matches a quarter of the year (1-4) (for dates) |
range | Match between |
regex | Matches a regular expression |
iregex | Same as regex, but case-insensitive |
second | Matches a second (for datetimes) |
startswith | Starts with |
istartswith | Same as startswith, but case-insensitive |
time | Matches a time (for datetimes) |
week | Matches a week number (1-53) (for dates) |
week_day | Matches a day of week (1-7) 1 is sunday |
iso_week_day | Matches a ISO 8601 day of week (1-7) 1 is monday |
year | Matches a year (for dates) |
iso_year | Matches an ISO 8601 year (for dates) |
mydata = Member.objects.all().order_by('firstname').values()
mydata = Member.objects.all().order_by('-firstname').values()
mydata = Member.objects.all().order_by('lastname', '-id').values()
{% load static %}
<link rel="stylesheet" href="{% static 'myfirst.css' %}">
pip install whitenoise
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
]
STATIC_ROOT = BASE_DIR / 'productionfiles'STATIC_URL = 'static/'
py manage.py collectstatic
#Add this in your settings.py file:
STATICFILES_DIRS = [
BASE_DIR / 'mystaticfiles'
]
{% load static %}
<link rel="stylesheet" href="{% static 'myglobal.css' %}">
py manage.py collectstatic
pip install psycopg2-binary
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'masteruser',
'PASSWORD': '12345678',
'HOST': 'w3-django-project.cdxmgq9zqqlr.us-east-1.rds.amazonaws.com',
'PORT': '5432'
}
}
.
mkdir .ebextensions
option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: my_tennis_club.wsgi:application
Tag | Description |
---|---|
autoescape | Specifies if autoescape mode is on or off |
block | Specifies a block section |
comment | Specifies a comment section |
csrf_token | Protects forms from Cross Site Request Forgeries |
cycle | Specifies content to use in each cycle of a loop |
debug | Specifies debugging information |
extends | Specifies a parent template |
filter | Filters content before returning it |
firstof | Returns the first not empty variable |
for | Specifies a for loop |
if | Specifies a if statement |
ifchanged | Used in for loops. Outputs a block only if a value has changed since the last iteration |
include | Specifies included content/template |
load | Loads template tags from another library |
lorem | Outputs random text |
now | Outputs the current date/time |
regroup | Sorts an object by a group |
resetcycle | Used in cycles. Resets the cycle |
spaceless | Removes whitespace between HTML tags |
templatetag | Outputs a specified template tag |
url | Returns the absolute URL part of a URL |
verbatim | Specifies contents that should not be rendered by the template engine |
widthratio | Calculates a width value based on the ratio between a given value and a max value |
with | Specifies a variable to use in the block |
Keyword | Description |
---|---|
add | Adds a specified value. |
addslashes | Adds a slash before any quote characters, to escape strings. |
capfirst | Returns the first letter in uppercase. |
center | Centers the value in the middle of a specified width. |
cut | Removes any specified character or phrases. |
date | Returns dates in the specified format. |
default | Returns a specified value if the value is False. |
default_if_none | Returns a specified value if the value is None. |
dictsort | Sorts a dictionary by the given value. |
dictsortreversed | Sorts a dictionary reversed, by the given value. |
divisibleby | Returns True if the value can be divided by the specified number, otherwise it returns False. |
escape | Escapes HTML code from a string. |
escapejs | Escapes JavaScript code from a string. |
filesizeformat | Returns a number into a file size format. |
first | Returns the first item of an object (for Strings, the first character is returned). |
floatformat | Rounds floating numbers to a specified number of decimals, default one decimal. |
force_escape | Escapes HTML code from a string. |
get_digit | Returns a specific digit of a number. |
iriencode | Convert an IRI into a URL friendly string. |
join | Returns the items of a list into a string. |
json_script | Returns an object into a JSON object surrounded by <script></script> tags. |
last | Returns the last item of an object (for Strings, the last character is returned). |
length | Returns the number of items in an object, or the number of characters in a string. |
length_is | Returns True if the length is the same as the specified number |
linebreaks | Returns the text with <br> instead of line breaks, and <p> instead of more than one line break. |
linebreaksbr | Returns the text with <br> instead of line breaks. |
linenumbers | Returns the text with line numbers for each line. |
ljust | Left aligns the value according to a specified width |
lower | Returns the text in lower case letters. |
make_list | Converts a value into a list object. |
phone2numeric | Converts phone numbers with letters into numeric phone numbers. |
pluralize | Adds a 's' at the end of a value if the specified numeric value is not 1. |
pprint | |
random | Returns a random item of an object |
rjust | Right aligns the value according to a specified width |
safe | Marks that this text is safe and should not be HTML escaped. |
safeseq | Marks each item of an object as safe and the item should not be HTML escaped. |
slice | Returns a specified slice of a text or object. |
slugify | Converts text into one long alphanumeric-lower-case word. |
stringformat | Converts the value into a specified format. |
striptags | Removes HTML tags from a text. |
time | Returns a time in the specified format. |
timesince | Returns the difference between two datetimes. |
timeuntil | Returns the difference between two datetimes. |
title | Upper cases the first character of each word in a text, all other characters are converted to lower case. |
truncatechars | Shortens a string into the specified number of characters. |
truncatechars_html | Shortens a string into the specified number of characters, not considering the length of any HTML tags. |
truncatewords | Shortens a string into the specified number of words. |
truncatewords_html | Shortens a string into the specified number of words, not considering any HTML tags. |
unordered_list | Returns the items of an object as an unordered HTML list. |
upper | Returns the text in upper case letters. |
urlencode | URL encodes a string. |
urlize | Returns any URLs in a string as HTML links. |
urlizetrunc | Returns any URLs in a string as HTML links, but shortens the links into the specified number of characters. |
wordcount | Returns the number of words in a text. |
wordwrap | Wrap words at a specified number of characters. |
yesno | Converts Booleans values into specified values. |
i18n | |
l10n | |
tz |
Keyword | Description |
---|---|
contains | Contains the phrase |
icontains | Same as contains, but case-insensitive |
date | Matches a date |
day | Matches a date (day of month, 1-31) (for dates) |
endswith | Ends with |
iendswith | Same as endswidth, but case-insensitive |
exact | An exact match |
iexact | Same as exact, but case-insensitive |
in | Matches one of the values |
isnull | Matches NULL values |
gt | Greater than |
gte | Greater than, or equal to |
hour | Matches an hour (for datetimes) |
lt | Less than |
lte | Less than, or equal to |
minute | Matches a minute (for datetimes) |
month | Matches a month (for dates) |
quarter | Matches a quarter of the year (1-4) (for dates) |
range | Match between |
regex | Matches a regular expression |
iregex | Same as regex, but case-insensitive |
second | Matches a second (for datetimes) |
startswith | Starts with |
istartswith | Same as startswith, but case-insensitive |
time | Matches a time (for datetimes) |
week | Matches a week number (1-53) (for dates) |
week_day | Matches a day of week (1-7) 1 is sunday |
iso_week_day | Matches a ISO 8601 day of week (1-7) 1 is monday |
year | Matches a year (for dates) |
iso_year | Matches an ISO 8601 year (for dates) |