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 myworld
myworld\Scripts\activate.bat
py -m pip install Django
django-admin --version
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