Guide to Django - Building Advanced Websites With Python
Guide to Django - Building Advanced Websites With Python
Guide to Django:
Building Advanced
Websites with Python
• Caching
• Logging
• Sending emails
• Pagination
• Messages framework
• Serialization
• Sessions
• Sitemaps
• Data validation
Preliminary stage
Basics of Django
Open: cmd
OK Cancellation Overview...
C:\Users\User>
[ :. Administrator: C:\Windows\system32\cmd.exe
C:\Users\Useopython -V
Python 3.10.6
C:\Users\User>
Ready!
Please note the fact that you are in a global
environment, and all packages currently installed are
also visible in the global space.
Let's move on to the next point, namely to creating our
virtual environment.
First, we need to create a folder where the virtual
environment will be located.
My project will be located at the following path:
C: - > Python -> Django -> travels
You might have a different path. Accordingly, the path
can vary widely.
In the console, if you are on a different drive, switch to
the appropriate drive immediately. For example, if
you've created the project on drive D, switch to that
drive using the command D:
I will navigate directly to the required folder and
provide the following command:
cd C:/Python/Django/travels
Sure, while being in this folder, let's create our virtual
environment using the following command:
Python -m venv venv
Name Change date Type Size
C:\>cd D:/Python/Django/travels
The device is not ready.
C:\>cd C:/Python/Django/travels
pip 22.2.1
setuptools 63.2.0
(venv) C:\Python\Django\travels>________________________________________________________________
If you had modules installed in the global environment,
you won't see them here. Additionally, you should
perform the update again, as we did earlier.
Admintop: C:\Windows\system32\cmd.exe
C:\>cd C:/Python/Django/travels
C:\Python\Django\travels>.\venv\Scripts\activate
pip 22.2.1
setuptools 63.2.0
(venv) C:\Python\Django\travelsydeactivate
C:\Python\Django\travels>_________________________________________________________________________
C:\Python\Django\travels ▼
■ Intel
> taKMSAutoS
> >7 NewBot
> ► parser_avito
> M Program Files
> ta Program Files (x86)
v M Python
v M Django
v ► travels
> M idea
> M venv
> M Python-3.S.3
> M Python371
> M Users
> M Webhook
> Windows
> MRwneoRnorwHr
? OK Cancel
And click "OK".
After this action, the project will be loaded.
File Edit View Navigate Code Refactor Run Tools VCS Window Help
travels M venv
P Version Control := TODO O Problems H Terminal $ Python Packages *•* Python Console
ID Indexing completed in 52 sec. Shared indexes were applied to 29% of files (1,271 of 4,289). (18 minutes ago)
Windows PowerShell
(C) 2016 Microsoft Corporation. All rights reserved.
PS C:\Python\Django\travels>
M travels
Project
H Project ▼ -3 H "r Cl —
v travels C:\Python\Django\travels
V
v M venv
M Include
* M Lib
> Bi Scripts
Lo.gitignore
t3 pyvenv.cfg
* Hill External Libraries
Terminal: Local X + v
Windows PowerShell
(C) 2016 Microsoft Corporation. All rights reserved.
Cvenv) PS C:\Python\Django\travels> Q
If you enter the command pip list, you will see that the
Django package has been added to our list.
fl manage, py 1 KB
Thu 08.09.22 11:54 JetBrains PyCharm ...
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
September 08, 2022 - 12:13:30
Django version 4.1.1, using settings 'travels.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
M
The install worked successfully! Congratulations!
You are seeing this page because DEBUG=True is in your
settings file and you have not configured any URLs.
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate1 to apply them.
September 08, 2022 - 12:32:07
Django version 4.1.1, using settings 'travels.settings'
Starting development server at http:7/127.0.0.1:4000/
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'traveler'
]
Here's an improved version:
If you open the "apps.py" file:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'traveler.apps.TravelerCon fig'
Presentation Views
(Creation of the main page
handler)
In Django, views can be implemented either as
functions or as classes. Let's start by using a function,
as it's the simplest implementation to understand. We
define all views in the views.py file.
Let's define the first view function for the main page.
def index(request):
return HttpResponse("Application page traveler.")
The function name "index" is chosen arbitrarily, but
typically, for the main page, it's customary to use this
name.
Next, (request) essentially refers to an HttpRequest
object that contains information about the request,
session, cookies, etc. So, using the request variable, we
have access to all the information within the current
request context.
As an output, this function should create an instance of
the HttpResponse class.
The content of the main page will be the string
("Application page content.").
However, in order to use this, you need to import the
HttpResponse class.
def index(request):
return HttpResponse("Application page traveler.")
urlpatterns = [
pathCadmin/', admin.site.urls),
]
urlpatterns = [
pathCadmin/', admin.site.urls),
path('traveler/', index),
]
urlpatterns = [
pathCadmin/', admin.site.urls),
path('traveler/', index),
]
H Project ▼ © J. -r Ct — ft settings.py x ft views.py < I ft urls.py ft apps.py
settings.py
ft urls.py
ft wsgi.py
tj db.sqlite3
ft manage.py
> to venv
> Hill External Libraries
You have 18 unapplied migrationCs). Your project may not work properly until you apply the migrations for appts): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
September 12, 2022 - 12:45:23
Django version 4.1.1, using settings 'travels.settings'
Starting development server at http://127.B.B.l:8BBB/
Quit the server with CTRL-BREAK.
Using the URLconf defined in travels.urls, Django tried these URL patterns, in this order:
1. admin/
2. traveler/
You're seeing this error because you have debug = True in your Django settings file. Change that to False, and Django will display a standard 404 page
urlpatterns = [
path('admin/', admin.site.urls),
pathC', index),
]
urlpatterns = [
path('admin/', admin.site.urls),
path('traveler/', include('traveler.urls')),
]
wsgi.py
db.sqlite3
urlpatterns = [
pathC', index)
]
http://127.0.0.1:8000/traveler
The prefix traveler will be attached to the domain
because we specified it in the urls.py file of the overall
project configuration.
To do this, we use the path('travels/',
include(traveler.urls)) line, which is located in the
travels directory.
This file should be created in the traveler application
directory.
Copy and paste the route
http://127.0.0.1:8000/traveler
into the browser. You will see the familiar page
<- -> C O 127.0.0.1:8000/traveler/
urlpatterns = [
path('admin/', admin.site.urls),
pathC', include('traveler.urls')),
]
v Bi travels
ft _init_.py
ft asgi.py
ft settings.py
ft urls.py
ft wsgi.py
def categories(request):
return HttpResponse("Articles by categories.'")
tj [■} Project ▼ © I <1 " settings.py views.py tests.py x travels\urls.py :< traveler\urls.py
a- v ft travels sources root Ct\Python\Django\travels 1 1 import ...
v M travels ■ X
v Bi traveler 1 4 ddef
index(request):
> Eft migrations 1 5 A return HttpResponse( ‘Traveler app page.11)
fl, _init_.py
admin.py
7 A def categories(request):
S apps.py
a A return HttpResponse("Articles by Cateoorv.1')
models py
tests.py 9
$ urls.py
views, py
v Bi travels
ft irit py
fi. asgi.py
[£■ settings.py
ft Nrlspy
giwsgi.py
Articles by category
def index(request):
return HttpResponse('"Application page traveler.")
Articles by category
2
zh
If you enter
http://127.0.0.1:8000/cats/
without a number, you will see a 404 page
<- -> O <X> 127.0.0.1:8000/cats/ <
Using the URLconf defined in travels.uris, Django tried these URL patterns, in this order:
1. admin/
2.
3. cats/<int:order_id>/
You’re seeing this error because you have debug = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
urlpatterns = [
path(", index),
pathCcats/<slug:order_id>/', categories),
]
Let's go to the browser and see how it works
<- -» 0 © 127.0.0.1:8000/cats/l/
Articles by category
1
«- -> 0 © 127.0.0.1:8000/cats/i a/
Articles by category
ia
Using the URLconf defined in travels.urls, Django tried these URL patterns, in this order:
1. admin/
2.
3. cats/<slug:order_id>/
You're seeing this error because you have debug = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
urlpatterns = [
path(", index),
path('cats/<int:order_id>/', categories),
re_path(r'~archive/(?P<year>[0-9]{4})/',
archive),
]
Fl Project O -£■ C® — settings.py views,py tests,py i5> travels\urls,py [£> traveler\urls.py models.py [£> apps.py
def index(request):
return HttpResponseC'The page of the application
traveler.")
Archive by years
2022
O 127.0.0.1:8000/cats/1/
Articles by category
We will receive
[18/Sep/2022 16:52:23] "GET/ HTTP/1.1" 200 47
[18/Sep/2022 16:53:58] "GET/cats/2/ HTTP/1.1" 200 56
[18/Sep/2022 16:54:02] "GET/cats/1/ HTTP/1.1" 200 56
Terminal: Local
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
September 18, 2022 - 16:45:52
Django version 4.1.1, using settings 'travels.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[18/Sep/2022 16:48:43] "GET /?name=Akademgorodok&order_id=smartphon HTTP/1.1" 200 47
[18/Sep/2022 16:52:23] "GET / HTTP/1.1" 200 47
[18/Sep/2022 16:53:58] "GET /cats/2/ HTTP/1.1" 200 56
[18/Sep/2022 16:54:02] "GET /cats/1/ HTTP/1.1" 200 56
Using the URLconf defined in travels.uris, Django tried these URL patterns, in this order:
1. admin/
3. cats/<int:order_id>/
4. Aarchive/(?P<year>[0-9]{4})/
You’re seeing this error because you have debug = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
def index(request):
return HttpResponse("Application page traveler.")
def index(request):
return HttpResponse("Application page traveler.")
r^. models.py
def categoriesCrequest, order_id):
tests.py
F return HttpResponse (f "<hl>Articles by category </hlxp> {or de r_id}</p>")
A urls.py
db.sqliteB
ft manage,py 17
> to venv
(D 127.0.0.1:8000
urlpatterns = [
path('', index, name='home'),
path('cats/<int:order_id>/', categories),
re_path(r'~archive/(?P<year>[0-9]{4})/', archive),
]
travels sources root C:\Python\Django\travels import ...
v travels
ra traveler urtpatterns = [
> ra migrations path(''( index, name=1 home'),
f5._init_.py
path('cats/<int:order_id>/', categories),
admir.py
re_path(r1Aarchive/(?P<year>[0-9]{4})/ ', archive),
fiapps.py
9 ]
E^ models, py
S tests, py
44 urls.py
E^views.py
ra travels
6_init_.py
ftasgi.py
ijsettings.py
Suri spy
wsgi.py
db.sqliteS
manage.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
Connecting to other databases is done within the same
dictionary. The key is to have the appropriate driver for
interaction with them.
Let's add the first model to our program, which will
describe the "traveler" table for storing information.
I've chosen the following database model structure.
Yours may be different. Since our website is related to
tourism, it's practical to name our models based on the
context. Let's name the first model "dir_travel," which
corresponds to the chosen location that is likely to
interest website users.
dir travel
id: Integer, primary key
title: Varchar
content: Text
photo: Image
timecreate: DateTime
time update: DateTime
is_puplished: Boolean
class Dir_travel(models.Model):
title = models.CharField(max_length=255)
content = models.TextField(blank=True)
photo =
models.ImageField(upload_to="photos/%Y/%m/%d/")
timecreate =
models.DateTimeField(auto_now_add=True)
timeupdate =
models.DateTimeField(auto_now=True)
is_puplished = models.BooleanField(default=True)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
In debug mode, we add to the routes
urlpatterns = [
pathCadmin/', admin.site.urls),
path(", include('traveler.urls')),
]
urlpatterns = [
path('admin/', admin.site.urls),
path(", include('traveler.urls')),
]
if settings.DEBUG:
urlpatterns + = static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
manage.py
Now we can create a database table based on the
created model. For this purpose, there is a mechanism
called "migrations" for databases.
Migrations are Python modules that contain sets of
ORM-level commands. When you execute a migration
file, it automatically creates new tables or modifies
existing ones in the database, as well as their
relationships.
admin.py
&apps.py
_K(
Templates
We will discuss where to store templates and how to
connect them in this section. You can find more detailed
information about templates by visiting the official
Django website
https://django.fun/ru/docs/django/4.0/topics/temp
lates/
Let's assume that as our main page, we want to use a
template that is stored in a file index.html
To begin, let's import the built-in Django template
engine. Next, go to our project and open the views.py
file. This is the file where we will place all our
templates.
n traveler
-from django.shortcuts import render, redirect
v U migrations
& 0001Jnitial.py
i§._init_.py
def index(request):
f5> urls.py
t5> wsgi.py
def index(request):
return render(request, 'traveler/index.html')
© Main page x i
Main page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> About the website</title>
</head>
<body>
<h1> About the website</h1>
</body>
</html>
index.html </body>
rt._init_.py 10 </html>
admin.py
def about(request):
return render(request, 'traveler/about.html')
travels sources root, C:\Python\Django\travels ^from django.http import HttpResponse
v travels Afrom django.shortcuts import render, redirect
- El traveler
v El migrations
c>def index(request):
0001JnitiaLpy
return render(request, 'traveter/index.html' )
fi._init_.py
v M templates
v M traveler
Hdef about(request):
urlpatterns = [
path(", index, name='home'),
path('about/', about, name='about'),]
H Project ▼ Q £ T $ settings.py X views.py < urls.py index.html
def index(request):
return render(request, 'traveler/index.html', {'title':'
Main Page '})
def about(request):
return render(request, 'traveler/about.html', {'title':
''About the Website'})
def index(request):
return render(request, 'traveler/index.html', {'title': Main
page})
nponui±ieM
def index(request):
return render(request, 'traveler/index.html', {'menu':
menu, 'title': Main page})
<!DOCTYPE html>
<html lang='"en'">
<head>
<meta charset='"UTF-8'">
<title>{{ title }}</title>
</head>
<body>
{% for m in menu %}
<li>{{m}}</li>
{% endfor %}
</body>
</html>
Main page x
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{% block mainmenu %}
<ul>
{% for m in menu %}
<li>{{m}}</li>
{% endfor %}
</ul>
{% endblock mainmenu %}
{% block content %}
{% endblock %}
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{% for m in menu %}
<li>{{m}}</li>
{% endfor %}
</body>
</html>
{% extends 'traveler/base.html' %}
{% block content %}
<h1>{{title}}</h1>
<p>The content of the page</p>
{% endblock %}
<h1>{{title}}</h1>
<p>The content of the page</p>
def index(request):
posts = Dir_travel.objects.all()
return render(request, 'traveler/index.html', { 'posts':
posts, 'menu': menu, 'title': Main page '})
H Project ▼ O i. -J- settings.py views.py base.html [£> urls.py index.html x models.py about.html
{% extends 'traveler/base.html' %}
{% block content %}
<h1>{{title}}</h1>
<ul>
{% for p in posts %}
<li>
<h2>
{{p.title}}
</h2>
<h2>
{{p.content}}
</h2>
<hr>
</li>
{% endfor %}
</ul>
{% endblock %}
AAMnHMCTpupoeaHne Django
Wmh nojib3CBare;iA:
Flaponb:
Bomtm
Add Edit
Obligatory field.
□ Is puplished
Main page
• Poland
Poland,[b] officially the Republic of Poland,[c] is a country in Central Europe. It is divided into 16 administrative provinces called voivodeships, covering an area of 312,696 kni2 (120,733 sq mi).
Poland has a population of over 38 million and is the fifth-most populous member state of the European Union.[12] Warsaw is the nation's capital and largest metropolis. Other major cities
include Krakow, Wroclaw, Lodz, Poznan, Gdansk, and Szczecin. Poland has a temperate transitional climate. Its territory extends from the Baltic Sea in the north to the Sudeten and Carpathian
Mountains in the south. The country is bordered by Lithuania and Russia to the northeast,[d] Belarus and Ukraine to the east, Slovakia and the Czech Republic to the south, and Germany to the
west. Poland also shares maritime boundaries with Denmark and Sweden.
Main page
• Poland
Poland,[b] officially the Republic of Poland,[c] is a countiy in Central Europe. It is divided into 16 administrative provinces called voivodeships, covering an area of 312,696 km2 (120,733 sq mi).
Poland has a population of over 38 million and is the fifth-most populous member state of the European Union.[12] Warsaw is the nation's capital and largest metropolis. Other major cities
include Krakow, Wroclaw, Lodz, Poznan, Gdansk, and Szczecin. Poland has a temperate transitional climate. Its territory extends from the Baltic Sea in the north to the Sudeten and Carpathian
Mountains in the south. The countiy is bordered by Lithuania and Russia to the northeast,[d] Belarus and Ukraine to the east, Slovakia and the Czech Republic to the south, and Germany to the
west. Poland also shares maritime boundaries with Denmark and Sweden.
Ukraine
Ukraine (Ukrainian: ykpama, romanized: Ukraina, pronounced [ukrn jinn] (listen)) is a countiy in Eastern Europe. It is the second-largest European countiy after Russia, which it borders to the
east and northeast.[a][ll] Ukraine covers approximately 600,000 square kilometres (230,000 sq mi).[b] Prior to the ongoing Russo-Ukrainian War, it was the eighth-most populous countiy in
Europe, with a population of around 41 million people.[c][6] It is also bordered by Belarus to the north; by Poland, Slovakia, and Hungaiy to the west; and by Romania and Moldova[d] to the
southwest; with a coastline along the Black Sea and the Sea ofAzov to the south and southeast.[e] Kyiv is the nation's capital and largest city. The countiy's national language is Ukrainian, an g x
most people are also fluent in Russian.[14] '*
Germany
Germany (German: Deutschland, pronounced [ davtjlant] (listen)), officially the Federal Republic of Germany,[f] is a countiy in Central Europe. It is the second most populous countiy in Europe
after Russia, and the most populous member state of the European Union. Germany is situated between the Baltic and North seas to the north, and the Alps to the south; it covers an area of
357,022 square kilometres (137,847 sq mi), with a population of almost 84 million within its 16 constituent states. Germany borders Denmark to the north, Poland and the Czech Republic to the
east, Austria and Switzerland to the south, and France, Luxembourg, Belgium, and the Netherlands to the west. The nation's capital and largest city by population is Berlin and its financial centre
is Frankfurt; the largest urban area is the Ruhr.
views,py
v Ea travels 4 Rclass Dir_travel(models.Model):
(Ji_irit_,py title = models.CharField(max_length=255)
ft asgi.py content = models.TextField(blank-True)
settings,py photo - models. ImageField(l^pload_to=' lphotos/%Y/%m/%d/,l)
S urls.py time_create = models.DateTimeField(auto_now_add-True)
wsgi.py time_update = models.DateTimeField(auto_now=True)
H db.sqliteS
is_puplished = models. BooleanField (clef ault=True)
manage,py
> M venv
L2 ©T 3 def (self):
' Hill External Libraries
v *3* < Python 3.10 (travels) (2) > C:\Python\Django\travek
return self.title
class Meta:
verbose_name = "All Countries"
verbose_name_plural = "All Countries"
ordering = ['time_create', 'title']
Let's go to the admin panel and refresh the page
class TravelerConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'traveler'
verbose_name = "TRAVELER"
'traveler.apps.TravelerCon fig'
Next, let's add more fields in the list of articles, not just
the title (such as publication time, publication flag,
etc.). Open the admin.py file and add the following:
class Dir_travelAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'timecreate', 'photo')
list_display_links = ('id', 'title')
search fields = ('title', 'content')
admin.site.register(Dir_travel)
list_display" contains a list of all the fields we want to
see in our admin panel.
"list_display_links" contains the fields on which we
can click to go to the corresponding article for editing.
"search_fields" specifies the fields by which we can
search for specific information.
admin.site.register(Dir_travel, Dir_travelAdmin)
class Dir_travel(models.Model):
title = models.CharField(max_length=255,
verbose_name = "Heading")
content = models.TextField(blank=True, verbose_name
= "Article text")
photo =
models.ImageField(upload_to="photos/%Y/%m/%d/",
verbosename = "Photo")
time_create =
models.DateTimeField(auto_now_add=True,
verbose_name = "Time of creation ")
time_update = models.DateTimeField(auto_now=True,
verbose_name = "Change time")
is_puplished = models.BooleanField(default=True)
Q YouTube
66 OYouTube
blockquote.png btn_yt.png logo.png main.ico share_yt.png smallmenu.png
■ travels sources root C:\Python\Djai
v ■ travels
> ■ media
v El traveler
v El migrations
r^.0001 Jnitial.py
&_init_.py
v ■ static
v M traveler
v ■ css
aa styles.css
v ■ images
blockquote.png
U btn_ytpng
logo.png
main ,ico
share_yt.png
smallmenu.png
■ js
Main page
□ Moldova
Moldova (Romanian: Republics Moldova), is a landlocked country in Eastern Europe.[17] It is bordered by Romania to the west and Ukraine to the north, easl
Russian puppet state of Transnistria lies across the Dniester on the country's eastern border with Ukraine. Moldova's capital and largest city is Chisinau.
Germany
Germany (German: Deutschland, pronounced [ doYtjlant] (listen)), officially the Federal Republic of Germany,[f] is a country in Central Europe. It is the secon
after Russia, and the most populous member state of the European Union. Germany is situated between the Baltic and North seas to the north, and the Alps
357,022 square kilometres (137,847 sq mi), with a population of almost 84 million within its 16 constituent states. Germany borders Denmark to the north, Pol
east, Austria and Switzerland to the south, and France, Luxembourg, Belgium, and the Netherlands to the west. The nation's capital and largest city by popul
Frankfurt; the largest urban area is the Ruhr.
Ukraine
Ukraine (Ukrainian: YKpaiHa, romanized: UkraTna, pronounced [ukre jine] (listen)) is a country in Eastern Europe. It is the second-largest European country al
and northeast.[a][11] Ukraine covers approximately 600,000 square kilometres (230,000 sq mi).[b] Prior to the ongoing Russo-Ukrainian War, it was the eighth
with a population of around 41 million people.[c][6] It is also bordered by Belarus to the north; by Poland, Slovakia, and Hungary to the west; and by Romani,
with a coastline along the Black Sea and the Sea of Azov to the south and southeast.[e] Kyiv is the nation's capital and largest city. The country’s national lai
are also fluent in Russian.[14]
Poland
Poland,[b] officially the Republic of Poland,[c] is a country in Central Europe. It is divided into 16 administrative provinces called voivodeships, covering an ;
Poland has a population of over 38 million and is the fifth-most populous member state of the European Union.[12] Warsaw is the nation's capital and largesl
Krakow, Wroclaw, Lodz, Poznan, Gdansk, and Szczecin. Poland has a temperate transitional climate. Its territory extends from the Baltic Sea in the north to tl
in the south. The country is bordered by Lithuania and Russia to the northeast,[d] Belarus and Ukraine to the east, Slovakia and the Czech Republic to the s<
also shares maritime boundaries with Denmark and Sweden.
If you look at the code of the loaded page, you will find
that the CSS stylesheet file is included
1
2 <!DOCTYPE html>
3 <html lang="en">
4 <head>
5 <meta charset=,rUT = -8">
6 <title>r/iaBH.nfl crpaHHi4&</title>
7 <link type="text/css" href="/static/traveler/css/5tyles.css" re1="stylesheet" />
8 </head>
9 <body>
Clicking on href="/static/traveler/css/styles.css",
the next thing you will see is the code for our stylesheet
htnulj body {
font-family: 'Arial';
margin: 0;
padding: 0;
height: 130%;
width: 100%;
color: #444;
? '
a {
color: #0059b2;
text-decoration: none;
?
a:hover {
color: #CCfN)00;
text-decaration: underline;
:•
img {max-width: 600px; height: auto;}
ing.img-art ide-left {
max-width: 3f»0px;
oeight: auto;
float: left;
padding: 0 lOpx l®px 0;
:• '
ing.img-art ide-left-thumb {
max-width: 15E>px;
height: auto;
? ’
Base.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
<link type="text/css" href="{% static 'traveler/css/styles.css' %}"
rel="stylesheet" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" href="{% static 'traveler/images/main.ico' %}"
type="image/x-icon"/>
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
</head>
<body>
<table class="table-page" border=0 cellpadding="0" cellspacing="0">
<tr><td valign=top>
{% block mainmenu %}
<div class="header">
<ul id="mainmenu" class="mainmenu">
<li class="logo"><a href="#"><div class="logo"></div></a></li>
{% for m in menu %}
{% if not forloop.last %}
<li><a href="#">{{m.title}}</a></li>
{% else %}
<li class="last"><a href="#">{{m.title}}</a></li>
{% endif %}
{% endfor %}
</ul>
<div class="clear"></div>
</div>
{% endblock mainmenu %}
to static
7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
v to traveler 8 <link rel="shortcut icon" href="{% static 'traveler/images/main.ico' %}" type=l,image/x-icon,7>
> to CSS 9 <meta name="viewport" content=”width=device-width, initial-scale=1.0">
> to images 10 t </head>
tojs 11 f <body>
v to templates 12 f3<table class="table-page" border=0 cellpadding=l,0" cellspacing=l,0l,>
'■s to traveler
13 S3<trxtd valign=top>
about.html
14 {% block mainmenu %}
fa base.html
15
index.html
ft_init_.py
16 f <div class="header">
ft admin.py 17 <ul id="mainmenu" class=l,mainmenul,>
ft apps.py 18 <li class=l,logo"xa href="#"xdiv class="logo"x/divx/ax/li>
ft models.py 19 {% for m in menu %}
fttests.py 20 {% if not forloop.last %}
ft urls.py 21 <lixa href ="#">■{{m.title}]-</ax/li>
ft views.py
22 {% else %}
v to travels
23 <li class="last"xa href="#">{{m.title}-}-</ax/li>
ft _init_.py
24 {% endif %}
ft asgi.py
25 {% endfor %}
ft settings.py
26 t t/uli
ft urls.py
ftwsgi.py | 27 <div class="clear"x/div>
|| dbsqlite3 28 E-1 </div>
ft manage.py 29 {% endblock mainmenu %}
|3 db.sqliteJ </div>
ft manage.py 59 <! - - End of content block ->
Connecting the file styles.css
<link type="text/css" href="{% static
'traveler/css/styles.css' %}" rel = "stylesheet" />
Additionally, we connect an icon
<link rel = "shortcut icon" href="{% static
'traveler/images/main.ico' %}" type="image/x-icon"/>
<div class="header">
<ul id = "mainmenu" class="mainmenu">
<li class="logo"><a href="#"><div
class="logo"></div></a></li>
{% for m in menu %}
{% if not forloop.last %}
<li><a href="#">{{m.title}}</a></li>
{% else %}
<li class="last"><a href="#">{{m.title}}</a>
</li>
{% endif %}
{% endfor %}
</ul>
<div class="clear"></div>
</div>
{% endblock mainmenu %}
{% for m in menu %}
{% if not forloop.last %}
<li><a href="#">{{m.title}}</a></li>
{% else %}
<li class="last"><a href="#">{{m.title}}</a>
</li>
{% endif %}
{% endfor %}
{% extends 'traveler/base.html' %}
{% block content %}
<ul class="list-articles">
{% for p in posts %}
<li><h2>{{p.title}}</h2>
<p>{{p-content}}</p>
<div class="clear"></div>
<p class="link-read-post"><a href="#">Read the
post</a></p>
</li>
{% endfor %}
</ul>
{% endblock %}
We're not changing the about.html template for now.
Now let's see how the main page will look. Refresh the
page in your browser.
Ukraine Moldova
Moldova (Romanian: Republica Moldova), is a landlocked country in Eastern Europe.[17] It is bordered by Romania to the west and Ukraine to the north, east, and south.[18] The unrecognised Russian puppet state of Transnistria lies across
the Dniester on the country's eastern border with Ukraine. Moldova's capital and largest city1 is Chisinau.
Moldova
Germany
Germany
Germany (German: Deutschland, pronounced [ doYtflant] (listen)), officially the Federal Republic of Germany,[f] is a country in Central Europe. It is the second most populous country in Europe after Russia, and the most populous member
state of the European Union. Germany is situated between the Baltic and North seas to the north, and the Alps to the south; it covers an area of 357,022 square kilometres (137,847 sq mi), with a population of almost 84 million within its 16
Our channel constituent states. Germany borders Denmark to the north, Poland and the Czech Republic to the east, Austria and Switzerland to the south, and France, Luxembourg, Belgium, and the Netherlands to the west. The nation's capital and largest
city’ by population is Berlin and its financial centre is Frankfurt; the largest urban area is the Ruhr.
O YouTube
Ukraine
Ukraine (Ukrainian: ykpaiHa, romanized: Ukraina, pronounced [ukra jine] (listen)) is a country’ in Eastern Europe. It is the second-largest European country’ after Russia, which it borders to the east and northeast.[a][ll] Ukraine covers
approximately 600,000 square kilometres (230,000 sq mi).[b] Prior to the ongoing Russo-Ukrainian War, it was the eighth-most populous country in Europe, with a population of around 41 million people.[c][6] It is also bordered by Belarus
to the north; by Poland, Slovakia, and Hungary to the west; and by Romania and Moldovafd] to the southwest; with a coastline along the Black Sea and the Sea ofAzov to the south and southeast.[e] Kyiv is the nation's capital and largest
city’. The country’,s national language is Ukrainian, and most people are also fluent in Russian.[14]
Poland
Poland,[b] officially the Republic of Poland,[c] is a country’ in Central Europe. It is divided into 16 administrative provinces called voivodeships, covering an area of 312,696 km2 (120,733 sqmi). Poland has a population of over 38 million
and is the fifth-most populous member state of the European Union.[12] Warsaw is the nation's capital and largest metropolis. Other major cities include Krakow, Wroclaw, Lodz, Poznan, Gdansk, and Szczecin. Poland has a temperate
transitional climate. Its territory’ extends from the Baltic Sea in the north to the Sudeten and Carpathian Mountains in the south. The country is bordered by Lithuania and Russiato the northeast,[d] Belarus and Ukraine to the east, Slovakia
and the Czech Republic to the south, and Germany to the west. Poland also shares maritime boundaries with Denmark and Sweden.
Moldova (Romanian: Republica Moldova), is a landlocked country in Eastern Europe. [17] It is bordered by Romania to the west
and Ukraine to the north, east, and south. [ 18] The unrecognised Russian puppet state of Transnistria lies across the Dniester on
the country's eastern border with Ukraine. Moldova's capital and largest city is Chisinau.
Read post
Germany
Germany (German: Deutschland, pronounced [ dovtjlant] (listen)), officially the Federal Republic of Germany,[f] is a country in
Central Europe. It is the second most populous country in Europe after Russia, and the most populous member state of the
European Union. Germany is situated between the Baltic and North seas to the north, and the Alps to the south; it covers an area
of 357.022 square kilometres (137,847 sq mi), with a population of almost 84 million within its 16 constituent states. Germany
borders Denmark to the north, Poland and the Czech Republic to the east, Austria and Switzerland to the south, and France,
Luxembourg, Belgium, and the Netherlands to the west. The nation's capital and largest city by population is Berlin and its
financial centre is Frankfurt; the largest urban area is the Ruhr.
Read post
For example:
{{ value|truncatewords:2 }}
And now let's see how this filter will affect the content
display. Let's refresh our page
As we can see, only a portion of the post is displayed.
We can briefly review the post, and if we need to delve
into the information, we click the 'Read the post'
button. For now, it doesn't lead to anything, as the
button is inactive.
Filters can be composite, meaning they can be applied
simultaneously to the same content. For example, let's
transform the string into all uppercase letters. In this
case, it doesn't make sense and is only required for
demonstration
ttjs 12 </ul>
v Bi templates
ta traveler
endblock %}
abouthtml
m base.html
_______________ irtrl w h<-ml____________________
Ukraine Moldova
Poland MOLDOVA (ROMANIAN: REPUBLICA MOLDOVA), IS A LANDLOCKED COUNTRY IN EASTERN ...
Moldova
Germany
Germany
Spain
GERMANY (GERMAN: DEUTSCHLAND, PRONOUNCED ['DOyTELANT] (LISTEN)), OFFICIALLY THE FEDERAL REPUBLIC
Our chaninel
O YouTube Ukraine
UKRAINE (UKRAINIAN: UKRAINE, ROMANIZED: UKRAINA, PRONOUNCED [UKRVJINV] (LISTEN)) IS A ...
Moldova
Title:
Articta tad: <h3>Moldova (Romanian: Republica Moldova)</h3>, is a landlocked country in Eastern Europe.[17] It is
bordered by Romania to the west and Ukraine to the north, east, and south. [18] The unrecognised Russian
puppet state of Transnistria lies across the Dniester on the country's eastern border with Ukraine.
Moldova's capital and largest city is Chisinau.
Q Is puplished
About tb-e .site Add Article Feedback
All countries
Ukraine Moldova
Poland <H3>MO LDOVA (ROMANIAN: REPUBLICA MOLDOVA)</H3>, IS A LANDLOCKED COUNTRY IN EASTERN ...
Moldova
Germany
Germany
Spain
GERMANY (GERMAN: DEUTSCHLAND, PRONOUNCED [ DOyTZLANT] (LISTEN)), OFFICIALLY THE FEDERAL REPUBLIC ..
Our channel
74
75 <lixh2>Germany</h2>
76 <p>GERMANY (GERMAN: DEUTSCHLAND, PRONOUNCED ['DDYTILANT] (LISTEN)), OFFICIALLY THE FEDERAL REPUBLIC ...</p>
77 <div class="clear,’x/div>
79 <p class=,,link-read-post"><a href="#">read post</a></p>
79 </li>
AU countries
Ukraine Moldova
Poland MOLDOVA (ROMANIAN: REPUBLICA MOLDOVA)
Germany
Spain
Germany
GERMANY (GERMAN: DEUTSCHLAND. PRONOUNCED [ DOyTILANT] (LIST
Our channel REPUBLIC ...
</head>
B<body>
Retable class="table-page" border=0 cellpadding="G" cellspacing="Q">
Hctrxtd vallgn=top>
{% block mainmenu %}
<div class="header">
<ul id="mainmenu" class="mainmenu">
18 * <li class="logo"xa href="/"xdiv class="logo" ></divx/ax/li>
_______ {% for m in menu %}___________________________________________________
And this will work. If you start our server and click on
the logo (currently represented by an empty square,
which we'll fix later), you'll be taken to the same main
page.
Creating links in this way is not the best solution
because the URL of the main page doesn't necessarily
have to match the name of the main page. If it
changes, you'd have to make changes in all the
templates. It's more practical to use route names.
If you open the urls.py file, you'll see the names of our
routes
urlpatterns = [
path('', index, name='home'),
path('about/', about, name='about'),
]
Cewnac Hac uHTepecyem uma home.
Let's change the previous line to:
<li class="logo"><a href="{% url 'home' %}"><div
class="logo" ></div></a></li>
n<trxtd valign=top>
{% block mainmenu %}
<div class="header">
<ul id="mainmenu" class="mainnenu">
18 <11 class="logo"xa href="{% url 'home' %}-"xdiv class = "logo" x/divx/ax/li>
{% for m in nenu %}
20__________ <% If not forloon.last ________________________________________________________
menu = ["About", " Add article " f "Feedback" f "To come in"]
on
menu = [{'title': 'About the site', 'url_name': 'about'},
{'title': 'Add an article', 'url_name': 'add_page'},
{'title': 'Contact us', 'url_name': 'contact'},
{'title': 'Login', 'url_name': 'login'}
]
menu = [{'title': "About", 'url_name': 'about'},
{'title': "Add article", 'url_name': 'add_page'},
{'title': "Feedback", 'url.name': 'contact'},
{'title': "Tocomein", 'url_name': 'login'}
]
def contact(request):
return HttpResponse("Feedback")
def login(request):
return HttpResponse("Authorization")
to traveler
radef index(request) :
v to migrations
posts = Dir_tra vet. objects. alL()
&0001.jnitial.py
ft_init_.py return render (request, 'traveler/index.html', {'posts': posts, 'menu': menu, 'title': ' Mainpage'})
def index(request):
posts = Dir_travel.objects.all()
return render(request, 'traveler/index.html',
{'posts': posts, 'menu': menu, 'title': ' Home page})
Intuitively, we might want to shorten the bottom line of
the index function ourselves. This is a commendable
desire since shorter lines are more readable and
generally easier to understand. Let's create a special
dictionary within this function where we list all the
parameters we'll be passing.
def index(request):
posts = Dir_travel.objects.all()
context = {
'posts': posts,
'menu': menu,
'title': 'Home page'
}
return render(request, 'traveler/index.html',
context=context)
{% block mainmenu %}
<div class="header">
<ul id = "mainmenu" class="mainmenu">
<li class="logo"><a href="{% url 'home' %}">
<div class="logo" ></div></a></li>
{% for m in menu %}
{% if not forloop.last %}
<li><a href="{% url m.url_name %}">{{m.title}}
</a></li>
{% else %}
<li class="last"><a href="{% url m.url_name %}">
{{m.title}}</a></li>
{% endif %}
{% endfor %}
</ul>
<div class="clear"></div>
</div>
{% endblock mainmenu %}
</head>
0<body>
<table class="table-page" border=0 cellpaddlng="0" cellspacing="G">
Actrxtd valign=top>
{% block mainmenu %}
<div class="header">
cut id="mainmenu" class="mainmenu">
• <11 class="logo"xa href="{% url 'home' %}"xdiv class="logo" x/divx/ax/li>
19 {% for m in menu %}
{% if not forloop.last %}
<lixa href="{% url m.url_name %}',>{{m.title}}</ax/li>
22 {% else %}
<li class="last"xa href="{% url m.url_name %}">{-{m.title}}</ax/li>
endif
{% endfor
26 </ul>
<div class="clear"x/div>
</div>
endblock mainmenu %}
All countries
Moldova
Germany
Spain
Our channel
O YouTube
Adding an article
urlpatterns = [
path('', index, name='home'),
path('about/', about, name='about'),
path('addpage/', addpage, name='add_page'),
path('contact/', addpage, name='contact'),
path('login/', login, name='login'),
path('post/<int:post_the>/', show_post,
name='post'),
]
v to templates
def togin(request):
v to traveler
return Http Re spun se(" Authorization ")
go abouthtml
go base.html
def show_post(request, post_the):
m index,html
S_init_.py = return HttpRe span se(f' Display article with id = {post_the}")
class Dir_travel(models.Model):
title = models.CharField(max_length=255, verbose_name
= " Heading ")
content = models.TextField(blank=True, verbose_name =
" Article text ")
photo =
models.ImageField(upload_to="photos/%Y/%m/%d/",
verbose_name = " Photo ")
time_create =
models.DateTimeField(auto_now_add=True, verbose_name
= " Time of creation ")
time_update = models.DateTimeField(auto_now=True,
verbose_name = " Change time ")
is_puplished = models.BooleanField(default=True)
def get_absolute_url(self):
return reverse('post', kwargs={'post_the':
self.pk})
def get_absolute_url(self):
return reverse('post', kwargs={'post_the':
self.pk})
{% extends 'traveler/base.html' %}
{% block content %}
H<ul class="list-articles">
{% for p in posts %}
<lixh2>{{p. title}-}</h2>
{% autoescape off %}
<p>{{p•content|truncatewords:10|upper}}</p>
{% endautoescape %}
<div class="clear"x/div>
11 <p class="link-read-post"xa href="{% p. get_absolute_url %}">Readpost </ax/p>
</li>
{% endfor %}
</ul>
{% endbtock %}•
A
Let's go back to the browser, refresh the page.
«- -> C © 127.0.0.1:8000
TemplateSyntaxError at I
Invalid block tag on line 11 'p.get_absolute_url'; expected 'empty' or 'endfor'. Did you forget to register or load this tag?
Request Method: GET
Request URL: http://127.001:8000/
Django Version: 4.1.1
Exception Type: TemplateSyntaxError
Exception Value: Invalid block tag on line 11: 'p.get_absolute_url', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
Exception Location: C:\Python\Django\travels\venv\lib\site-packages\django\template\base.py, line 558, in invalid_block_tag
Raised during: traveier.views. index
Python Executable: C:\PythDn\Django\travels\venv\Scripts\python exe
Python Version: 3.10.7
Python Path: [ ,C:\\PythorA\DjangcA\travels ’x\tr'avels,J
'C:\\Python\\python310.zip',
■C:\\Python\\DLLs',
■CiWPythonWlib'j
'C:\\Python',
'C: WPython V\Django\.\travels\\venv',
'C:\\Python\\Django\\travels\\venv\Mib\\site-packages']
Server time: Mon, 31 Oct 2022 11:37:26 +0000
Invalid block tag on line 11: 'p.get_absolute_url', expected 'empty' or'endfor'. Did you forget to register or load this tag?
1 {% extends ’traveler/base.html’ %}
2
3 {% block content
4 <ul class-"list-articles’^
5 {% for p in posts %}
6 <lixh2>{{p. title}}</h2>
{% autoescape off %}
8 <p>{{p.content|truncatewords:10|upper}}</p>
9 {% endautoescape %}
10 <div class="clear'’x/div>
11 <p class="link-read-post"xa href="{% p.get_absolute_url %}">Read post</ax/p>
12 </li>
13 endfor %}
14 </ul>
15
16 {% endblock 56}
17
class Category(models.Model):
name = models.CharField(max_length=100,
db_index=True)
21
class Meta:
verbose_name = " all countries "
27 class Category(models.Model):
name = models.CharField(max_length=10O, db_ index=True)
3G of def (self):
I
return self.name
cat = models.ForeignKey('Category',
on_delete=models.PROTECT)
'Category' - We define the association with the
category through a string.
on_delete=models.Protect - We prohibit deleting
categories from the Dir_travel model if there are
references. We create/modify this table in our database.
□class Oir_travel(models.Model):
title = models.ChanField(max_leng1 =255, verbose_name = "header")
content = models.TextField(blank=True, verbose_name = " Article text")
photo = models. ImageField(upload_1 ="photos/%Y/%m/%d/", verbose_name = "Photo")
time_create = models. DateTimeField (auto_now_add=True, verbose_name = "Time of creation")
time_update = models.DateTimeField(ajto_no.'.=Tnue, venbose_name = "Changetime 11)
is_puplished = models. BooleanField(defaiilt=True)
cat = models.ForeignKey(1 Category’, on_delet =models.PROTECT)
15 Of def (self):
16 return self.title
17
def get_absolute_url(self):
return reverse(1 post1 , kwai gs={'post_the 1: self.pk})
21
23 class Meta:
verbose_name = " All countries"
25 verbose_name_plural = "All countries"
26 ordering = [1-time_create', ’title1]
Terminal: Local
Category.objects.create(name=' Asia')
Category.objects.create(name=' Africa')
Category.objects.create(name=' North America’)
Category.objects.create(name=' South America')
Continents
Evpona Moldova
Asia MOLDOVA (ROMANIAN: REPUBLICA MOLDOVA)
Africa
North America
South America
Our channel
Q YouTube
{% for c in cats %}
{% if c.pk == cat_celected %}
<li class="selected">{{c.name}}</li>
{% else %}
<li><a href="{{ c.get_absolute_url }}">
{{c.name}}</a></li>
{% endif %}
{% endfor %}
<li class="share">
<p> Our channel </p>
<a class="share-yt" href="#"></a>
</li>
</ul>
</td>
<!--KoHe^ Sidebar -->
Q Project © hi styles,css < 1^ base.html p^views.py < urls.py x indexhtml x j£, models,py x
about.html
di class="share"?
base.html
im indexhtml
<p?Haiu K3Haji</p>
_init_.py <a class="share-yt" href="#"x/a>
admin.py
S appspy i </ul>
models,py i </td>
S tests,py
<!--Koh6M Sidebar -->
£ urls.py
i<td valign="top1' class="content"?
Let's go through this code.
Line:
<li class="selected"> Continents </li>
will be displayed always. And if
{% if cat_selected == 0 %}
we display this line not as a link but as text. If
cat_selected is not equal to "0", then we display it as
a link to the main page
<li><a href="{% url 'home' %}"> Continents </a>>
</li>.
All subsequent categories will be formed using a loop
{% for c in cats %}
{% if c.pk == cat_celected %}
<li class="selected">{{c.name}}</li>
{% else %}
<li><a href="{{ c.get_absolute_url }}">
{{c.name}}</a></li>
{% endif %}
{% endfor %}
We will pass the collection "cats" (this collection will
consist of objects of the Category class) and iterate
through it. If in this loop the primary key "c.pk" is equal
to "cat_selected"
{% if c.pk == cat_celected %}
then we output the current category not as a link but as
text
<li class="selected">{{c.name}}</li>
Otherwise, it will be displayed as a regular link.
<li><a href="{{ c.get_absolute_url }}">{{c.name}}
</a></li>
In other words, we display it by name, and we will form
the link using the method
get_absolute_url
To use this method, you need to add it to our Category
model.
class Category(models.Model):
name = models.CharField(max_length=100,
db_index=True)
def get_absolute_url(self):
return reverse('category', kwargs={'cat_the':
self.pk})
urlpatterns = [
path('', index, name='home'),
path('about/', about, name='about'),
path('addpage/', addpage, name='add_page'),
path('contact/', addpage, name='contact'),
path('login/', login, name='login'),
path('post/<int:post_the>/', show_post, name='post'),
path('category/<int:cat_the>/', show_category,
name='category'),
]
Let's define the function show_category in the
views.py file, and for now, it will look like a placeholder
function.
def index(request):
posts = Dir_travel.objects.all()
cats = Category.objects.all()
context = {
'posts': posts,
'cats': cats,
'menu': menu,
'title': 'Home page’,
'cat_selected': 0,
def index(request):
posts = Dir_travel.objects.al1()
cats = Category. objects. attO
context = {
1 posts': posts,
'cats': cats,
'menu': menu,
'title': ' Main page >
'cat_selected ' : 0,
}
return render(request, 'traveler/index.html', context=context)
Evpona
Moldova
Asia
MOLDOVA (ROMANIAN: REPUBLICA MOLDOVA)
Africa
, IS A LANDLOCKED COUNTRY IN EASTERN ...
South America
Germany
Our channel GERMANY (GERMAN: DEUTSCHLAND, PRONOUNCED [DOyTLLANT] (LISTEN)), OFFICIALLY THE FEDERAL REPUBLIC ...
fl YouTube
Ukraine
UKRAINE (UKRAINIAN: YKPAIHA. ROMANIZED: UKRAINA, PRONOUNCED [UKRV JINV] (LISTEN)) IS A ...
Read post
Poland
Category display =2
urlpatterns = [
path('', index, name='home'),
path('about/', about, name='about'),
path('addpage/', addpage, name='add_page'),
path('contact/', addpage, name='contact'),
path('login/', login, name='login'),
path('post/<int:post_the>/', show_post, name='post'),
path('category/<int:cat_id>/', show_category,
name='category'),
]
if len(posts) == 0:
raise Http404()
context = {
'posts': posts,
'cats': cats,
'menu': menu,
'title': ' Display by Categories ',
'cat_selected': cat_id,
}
return render(request, 'traveler/index.html',
context=context)
if len(posts) == 0:
raise Http4G4C)
context = {
' posts': posts,
'cats': cats,
'menu' : menu,
52 'title': ' Display by category ',
'cat_selected': cat_id,
North America
Germany
South America GERMANY (GERMAN: DEUTSCHLAND, PRONOUNCED ['DDyTSLANT] (LISTEN)), OFFICIALLY THE FEDERAL REPUBLIC ...
Our channel
O YouTube Ukraine
UKRAINE (UKRAINIAN: YKPAIHA, ROMANIZED: UKRAINA, PRONOUNCED [UKRV'JINV] (LISTEN)) IS A ...
Let's add the category name and the post creation time
to this list. To do this, open the index.html file, find
where the list is being generated, and modify the lines.
{% extends 'traveler/base.html' %}
{% block content %}
<ul class="list-articles">
{% for p in posts %}
<li><div class="article-panel">
<p class="first"> Continent: {{p.cat}}</p>
<p class="last">flama:
{{p.time_update|date:"d-m-Y H:i:s"}}</p>
</div>
<h2>{{p.title}}</h2>
{% autoescape off %}
<p>{{p.content|truncatewords:10|upper}}</p>
{% endautoescape %}
<div class="clear"></div>
<p class="link-read-post"><a href="{{
p.get_absolute_url }}"> Read the post </a></p>
</li>
{% endfor %}
</ul>
{% endblock %}
extends 'traveler/base.html
{% block content %}
<ul class="list-articles">
{% for p in posts %}
<lixdiv class="article-panel">
<p class="first">Continent: {{p.cat}}</p>
<p class="last">date : {{p.time_update|date: "d-m-Y H:i:s"}}</p>
</div>
<h2>{-[p .title}}</h2>
{% autoescape off %}
< p>{{p.content|truncatewords:10|upper}}</p>
endautoescape %}
<div class="clear"x/div>
< p class="link-read-post"xa href="{{ p. get_absolute_url }}">ReadDost</ax/p>
</li>
■ {% endfor %}
</ul>
{% endblock %}
Moldova
MOLDOVA (ROMANIAN: REPUBLICA MOLDOVA)
, IS A LANDLOCKED COUNTRY IN EASTERN ...
Read post
Germany
GERMANY (GERMAN: DEUTSCHLAND, PRONOUNCED [ DDyTLLANT] (LISTEN)), OFFICIALLY THE FEDERAL REPUBLIC ...
Read post
Admin panel. Registering the
Category model
How to do it?
It's simple! Open the admin.py file that we've worked
with before and add 'is_published'.
class Dir_travelAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'time_create', 'photo',
'is_puplished')
list_display_links = ('id', 'title')
search_fields = ('title', 'content')
I
Bclass Dir_travelAdmin(admin.ModelAdmin):
7 Of list_display = ('id1, 'title', 'time_create', 'photo', 'is_puplished')
8 of list_display_links = ('id', 'title')
9 Of h search_fields = ('title', 'content')
10
class Dir_travel(models.Model):
title = models.CharField(max_length=255, verbose_name
= 11 Title ")
content = models.TextField(blank=True, verbose_name =
" Article text")
photo =
models.ImageField(upload_to=''photos/%Y/%m/%d/'',
verbose_name = " Photo ")
time_create =
models.DateTimeField(auto_now_add=True, verbose_name
= " Creation time ")
time_update = models.DateTimeField(auto_now=True,
verbose_name = " Modification time ")
is_puplished = models.BooleanField(default=True,
verbose_name = " Publication ")
cat = models.ForeignKeyCCategory',
on_delete=models.PROTECT, null=True)
1 class Dir_travel(models.Model):
title = models.CharField(max_length=255, verbose_name = "header")
content = models.TextField(blank=True, verbose.name = "Articletext")
photo = models.ImageField(upload_to="photos/%Y/%m/%d/" , verbose_name = "Photo")
time_create = models.DateTimeField(auto_now_add=True, verbose_name = "Time of creation")
time.update - models.DateTimeField(auto_now=True, verbose_name = "Changetime")
is_puplished = models.BooleanField(default=True, verbose_name = "Publication")
cat = models.ForeignKeyCCategory1, on_delete=models.PROTECT, null=True)
admin.site.register(Category, CategoryAdmin)
a>iin.site.register(0ir_travel, Dir_travelAdmin)
20 admin.site.register(Category, CategoryAdmin)
Find
v Run
□ ■ NAME
Categorys + Add
□ 6 South America
□ 4 Asia
□ 3 Africa
□ 2 Asia
« □ 1 Europe
6 categorys
class Meta:
verbose_name = " Continent "
verbose_name_plural = " Continents "
ordering = ['id']
Aclass Category (models. Model) :
29 name = models.CharField(max_length=100, db_index=True)
30
3i i def __str__(self):
return self.name
40 verbose_name_plural = "Continents"
41 ordering = [1 id']
42
class Category(models.Model):
name = models.CharField(max_length=100,
db_index=True, verbose_name = " Continent ")
def_ str__(self):
return self.name
def get_absolute_url(self):
return reverse('category', kwargs={'cat_id': self.pk})
Let's move to the admin panel and update
Groups + Add
Users Add
TRIPS
□ ID CONTINENT
□ 3 Africa
O 4 Asia
O 5 North America
« □ 6 South America
After all these steps, we can say that the admin panel is
set up and fully functional at this stage. Next, using it,
we'll add a few more entries. Let's add 2-3 more
countries and link them to relevant categories. I've
taken the text from Wikipedia, and we'll use random
photos from the internet as well.
<li><div class="article-panel">
<p class='"first'"> Continent: {{p.cat}}</p>
<p class='"last'"> date: {{p.time_updateldate:'"d-m-Y
H:i:s'"}}</p>
</div>
{% if p.photo %}
<p><img class="img-article-left thumb" src="
{{p.photo.url}}"></p>
{% endif %}
<h2>{{p.title}}</h2>
{% block content %}
<ul class="list-articles">
■{% for p in posts %}
<lixdlv class="article-panel">
<p class="first">Continent: {{p . cat}}</p>
<p class="last">datea:{{p.time_update|date:"d-m-Y H:i:s"}}</p>
</div>
■{% if p.photo %}
<pximg class="img-article-left thumb" src="{{p.photo.url}}"x/p>
{% endif %}
< h2>{{p.title}}</h2>
■ (% autoescape off %}
< p>{{p.content|truncatewords:10|upper}}</p>
■ {% endautoescape %}
7 AH countries
class Dir_travelAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'time_create', 'photo',
'is_puplished')
list_display_links = ('id', 'title')
search_fields = ('title', 'content')
list_editable = ('is_published',)
ERRORS:
cclass 1 traveler.admin.Dir_travelAdmin’>: (admin.E121) The value of 'list_editable[0]' refers to 'is_published', which is not a field of 1 traveler.Dir_travel'.
Should be
class Dir_travelAdmin(admin.ModelAdmin):
list_display = ('id1, 'title', 'time_create', 'photo',
'is_published')
list_display_links = ('id', 'title')
search_fields = ('title', 'content')
list_editable = ('is_published',)
Rclass Dir_travelAdmin(admin.ModelAdmin):
list_display = ('id1, 'title', 'time_create', 'photo', 'is_published1)
! Of list_display_links = ('id', 'title')
Of search_fields = ('title', 'content')
) Of list_editable = ('is_published ',)
Let's add more fields that we can use to filter our list of
articles. We'll do this by adding another line to the
same class.
class Dir_travelAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'time_create', 'photo',
'is_published')
list_display_links = ('id', 'title')
search_fields = ('title', 'content')
list_editable = ('is_published',)
listfilter = ('is_published', 'timecreate')
□class Dir_travelAdmin(admin.ModelAdmin) :
7 ©T list_display = ('id', 'title', 'time_create', ' photo', is_published')
list_display_links = ('id', 'title')
9 ©T search_fields = ('title', 'content')
10 ©T list_editable = ('is_published',)
11 ©T list_fliter = ('is_published', 'time_create')
Q | |[ Find |
1 Publication
7 All countries
v M LdlipljlL-
v ta traveler
about.html
base.html
index.html
v El templatetags
£_init_.py
travel er_tags.py
ft Jnit_.py
Register = template.Library()
def get_categories():
return Category.objects.all()
Register = template.Library()
def get_categoriesQ :
return Category.objects.allO
Register = template.Library()
@register.simple_tag()
def get_categories():
return Category.objects.all()
Register = template.Library()
^register.simple_tag()
def get_categories():
return Category.objects.altO
9
This simple process turns our function into a tag that
can be used in the templates of our application. Next,
let's open the base template, base.html, and load our
tag at the very beginning of the file.
{% load static %}
{% load traveler_tags %}
toad static %}
{% toad traveter_tags %}
<!DOCTYPE htmt>
And let's see how this simple tag works. Let's navigate
to the terminal and start our test server.
We have an error
register = template.Library()
(^register. simple_tag ()
def get_categories():
return Category.objects.allO
9
{% for c in categories %}
{% if c.pk == cat_selected %}
<li class='"selected'">{{c.name}}</li>
{% else %}
<li><a href="{{ c.get_absolute_url }}'">
{{c.name}}</a></li>
{% endif %}
{% endfor %}
{% for c in categories %}
-{% if c.pk == cat_selected %}
<li class="selected">{{c.name}}</li>
{% else %}
<lixa href="-{-{ c.get_absolute_url }}">-{{c.name}}</ax/li>
endif %}
{% endfor %}
def index(request):
posts = Dir_travel.objects.all()
context = {
'posts': posts,
'menu': menu,
'title': 'The main page',
'cat_selected': 0,
}
return render(request, 'traveler/index.html',
context=context)
if len(posts) == 0:
raise Http404()
context = {
'posts': posts,
'menu': menu,
'title': 1 Display by categories ',
'catselected': cat_id,
}
return render(request, 'traveler/index.html',
context=context)
@register.simple_tag(name='getcats')
def get_categories():
return Category.objects.all()
from django import template
from traveler.models import *
register = template.LibraryO
@register.inclusion_tag('traveler/list_categories.htmr
)
def show_categories():
cats = Category.objects.all()
return {"cats": cats}
1 □from django import template
2 tifrom traveler. models import *
3
4 register = template.Library ()
5
6 (^register. simple_tag (name= ' get cats ' )
7 Hdef get_categories():
8 return Category.objects.all()
9
10 ^register.inclusion_tag(1traveler/list_categories.html')
11 Hdef show_categories():
12 cats = Category.objects.all()
13 return {’cats": cats}
14
itJ base.html
17^ index.html
list_categories.html
El tern platetags
{% for c in categories %}
{% if c.pk = = cat_selected %}
<li class="selected">{{c.name}}</li>
{% else %}
<li><a href="{{ c.get_absolute_url }}">
{{c.name}}</a></li>
{% endif %}
{% endfor %}
{% for c in cats %}
{% if c.pk == cat_seiected %}
<li eta ss=" selected" >{-{c .name}}</ti>
{% else %}
<lixa href="-[{ c.get_absolute_url }}">-{-[c. name}}</ax/li>
{% endif %}
7 {% endfor %}-
{% for c in categories %}
{% if c.pk = = cat_selected %}
<li class="selected">{{c.name}}</li>
{% else %}
<li><a href="{{ c.get_absolute_url }}">
{{c.name}}</a></li>
{% endif %}
{% endfor %}
Let's write...
{% show_categories %}
{% show_categories %}
<li class="share">
<p> Our channel </p>
@register.simple_tag(name='getcats')
def get_categories(filter=None):
if not filter:
return Category.objects.all()
else:
return Category.objects. filter(pk=filter)
To simply see how it works and view the entire full list.
About the site
Continents
Europe
Asia
Africa
Asia
<ul id='"leftchapters'">
{% if cat_selected == 0 %}
<li class='"selected'"> Continents </li>
{% else %}
<li><a href='"{% url 'home' %}'"> Continents </a>
</li>
{% endif %}
<ul id="teftchapters">
38 {% if cat_selected == 0 %}
<li class=" selected"> Continents </li>
else %}
<lixa href="{% url 'home' %}" Continents </ax/li>
{% endif %}
Continents
Africa
context = {
'post': post,
'menu': menu,
'title': post.title,
'catselected': 1,
}
return render(request, 'traveler/post.html',
context=context)
Hdef show_post(request, post_the):
post = get_object_or_404(Dir_travel, pk=post_the)
context = {
'post1 : post,
40 * 'menu': menu,
'title': post.title,
'cat_selected': 1,
}
return renderfrequest, 'traveler/post.html', context=context)
context = {
'post': post,
'menu': menu,
'title': post.title,
'cat_selected': post.cat_id,
}
v templates
v M traveler
iff about.html
base.html
iff index.html
।list_categories.html
> El templatetags
{% extend 'traveler/base.html' %}
{% block content %}
<h1>{{post.title}}</h1>
{% if post.photo %}
<p><img class="img-article-left" src="
{{post.photo.url}}"></p>
{% endif %}
{{post.contentllinebreaks}}
{% endblock %}
{% extend 'traveler/base.html' %}
{% block content %}
<hl>{{post.title}}</hl>
{% if post.photo %}
<p><img class="img-article-left" src="{{post. photo. url}}"x/p>
{% endif %}
{{post.content|linebreaks}}
{% endblock %}
class Dir_travel(models.Model):
title = models.CharField(max_length=255, verbose_name
= "Header")
slug = models.SlugField(max_length=255,
unique=True, db_index=True, verbose_name="URL")
content = models.TextField(blank=True, verbose_name =
" Article text")
photo =
models.ImageField(upload_to="photos/%Y/%m/%d/",
verbose_name = "Photo")
time_create =
models.DateTimeField(auto_now_add=True, verbose_name
= " Time of creation ")
time_update = models.DateTimeField(auto_now=True,
verbose_name = " Time of modification ")
is_published = models.BooleanField(default=True,
verbose_name = " Publication ")
cat = models.ForeignKeyCCategory',
on_delete=models.PROTECT, null=True, verbose_name = "
Category")
4
E
Hclass Dir_travel(models.Model):
title = models.CharField(max_length=255, verbose_name - "header")
slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL")
content = models.TextField(blank=True, verbose_name = "Articletext ")
photo = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name = "Photo")
time_create = models.DateTimeField(auto_now_add=True, verbose_name - "Time of creation ")
time_update - models.DateTimeField(auto_now=True, verbose_name - "Chanoetime ")
is_published = models.BooleanField(default=True, verbose_name = "Publication")
cat = models.ForeignKeyCCategory', on_delete=models.PROTECT, null=True, verbose_name = "Cateqorv")
Q002_cate g o ry_a Ite r_d i r_tra ve l_o pti o n s_a n d_m o re. py
D0D3_a Iterjcate g o ry_o pti o n s_a Iterjcate g o ry_n a m e_a n d_r
0004_alter_dir_travel_cat.py
D005_rena m eJ s_p u p I i shed_d i r_tra vel J s_p u b I i sh ed. py
&_init_.py
> ta static
v B templates
v M traveler
about.html
We'll remove the checkmarks to physically delete from
the hard drive
03 De ete X
Delete 5 files?
? OK Cancel
class Category(models.Model):
name = models.CharField(max_length=100,
db_index=True, verbose_name = " Continent")
slug = models.SlugField(max_length=255,
unique=True, db_index=True, verbose_name="URL")
def_ str__(self):
return self.name
Hclass Category(models.Model):
name = models.CharField(max_leng1 =166, db_index=True, verbose_name = ''Continent'1)
slug = models.SlugFleld(max_leng1 =255, uniqi =True, db_index=lrue, verbose_namB="LRL")
33 0) def (self):
• return self.name
35
def get_absolute_url(self):
return reverse(’category', kwargs={'cat_id': self.pk})
Password:
Password (again):
The entered password is too short. It must contain at least 8 characters.
We'll start the test web server and check. Enter the
command
'Python manage.py runserver'.
Then input your login and password
Django administration
0 Continents
class CategoryAdmin(admin.ModelAdmin):
list_display = (id1, 'name')
list_display_links = ('id', 'name')
searchfields = ('name',)
prepopulatedfields = {"slug": ("name",)}
Continent:
evropa-2
□ ID CONTINENT
O 1
O 2
□ 3
□ 4 South America
O 5 North America
5 Continents
class Dir_travelAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'time_create', 'photo',
'is_published')
list_display_links = ('id', 'title')
searchfields = ('title', 'content')
list_editable = ('is_published',)
listfilter = ('is_published', 'time_create')
prepopulatedfields = {"slug": ("title",)}
Rclass Dir_travelAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'time_create’, 'photo', 'is_published')
8 Of list_display_links = ('id', 'title')
9 Of search_fields = ('title', 'content')
0 Of list_editable = ('is_published',)
1 Of list_filter = ('is_published', 'time_create')
2 Of A prepopulated_fields = {"slug": ("title",)}
Instead of 'name,' we write 'title.'
Let's fill the database together with uploading photos
for different countries.
Find
Q
Action:
—_______ v Run Selected 0 items out of 13
■
German rule began in mainland Tanzania the late 19th century when Germany formed German East Africa. followed by British rule after World War I. The mainland was governed as Tanganyika, with the Zanzil
South America Archipelago remaining a separate colonial jurisdiction. Following their respective independence in 1961 and 1963, the two entities merged in 1964 to form the United Republic of Tanzania. [12] Tanganyikajoined the British Cot
in 1961 and Tanzania remains a member of the Commonwealth as a unified republic.[13]
Tanzania's population is composed of about 120 ethnic,[14] linguistic, and religious groups. The sovereign state of Tanzania is a presidential constitutional republic and since 1996 its official capital city has been Dodoma where
president's office, the National Assembly, and all government ministries are located.[15] Dar es Salaam, the former capital, retains most government offices and is the country's largest city, principal port, and leading commercial
[ 16][17] Tanzania is a de facto one-party state with the democratic socialist Chama Cha Mapinduzi party in power.
Our channel
Tanzania is mountainous and densely forested in the north-east, where Mount Kilimanjaro is located. Three ofAfrica's Great Lakes are partly within Tanzania. To the north and west lie Lake Victoria, Africa's largest lake, and La
Tanganyika, the continent's deepest lake, known for its unique species of fish. To the south lies Lake Malawi. The eastern shore is hot and humid, with the Zanzibar Archipelago just offshore. The Menai Bay ConservationArea i
OYouTube largest marine protected area. The Kalambo Falls, located on the Kalambo River at the Zambian border, is the second-highest uninterrupted waterfall inAfiica.[18]
Christianity is the largest religion in Tanzania, but there are also substantial Muslim and animist minorities. [19] Over 100 different languages are spoken in Tanzania, making it the most linguistically diverse country in East Afrit
country does not have a de jure official language,[21][22] although the national language is Swahili.[23] Swahili is used in parliamentary debate, in the lower courts, and as a medium of instruction in primary school. English is t
foreign trade, in diplomacy, in higher courts, and as a medium of instruction in secondary and higher education; [20] although the Tanzanian government is planning to discontinue English as the primary language of instruction,:
available as an optional course.[24] Approximately 10% of Tanzanians speak Swahili as a first language, and up to 90% speak it as a second language.[20]
urlpatterns = [
path(', index, name='home'),
path( about/, about, name='about'),
path(addpage/, addpage, name='add_page'),
path( contact/, addpage, name='contact'),
path( 1 login/, login, name='login'),
path( 1 post/<slug:post_slug>/, show_post, name='post'),
path( 1 category/<int:cat_id>/, show_category,
name=' category'),
(Jurlpatterns = [
path('', index, name='home'),
path('about/', about, name= 'about'),
path('addpage/', addpage, name='add_page'),
path(' contact/', addpage, name= 'contact'),
pathf'login/', login, name='login'),
path('post/<slug:post_slug>/', show_post, name='post'),
path('category/<int:cat_id>/', show_category, name=1 category'),
$|]
context = {
'post': post,
'menu': menu,
'title': post.title,
'cat_selected': post.cat_id,
}
return render(request, 'traveler/post.html',
context=context)
35 Adef show_post(request, post_the):
36 post = get_object_or_AGA(Dir_travel, pk=post_the)
37
38 context = {
39 'post': post,
AO 'menu': menu,
Al 'title1: post.title,
A2 'cat_selected': post.cat_id,
A3 }
AA * return render(request, 1traveler/post.html', context=context)
def get_absolute_url(self):
return reverse('post', kwargs={'post_slug':
self. slug})
18
19 def get_absolute_url(self):
20 return reverse('post’, kwargs={1post_slug': self.slug})
21
Adding an article
def addpage(request):
return HttpResponse("Adding an article ")
def addpage(request) :
return HttpResponsef’1 Adding an article ")
def addpage(request):
return render(request, 'traveler/addpage.html',
{'menu': menu, 'title': 1 Adding an article '})
v M templates
v M traveler
itJ abouthtml
addpage.html
q base.html
iff index.html
■^i list_categories.html
itJ post.html
{% extends 'traveler/base.html' %}
{% block content %}
<h1>{{title}}</h1>
<p> Page content </p>
{% endblock %}
extends 'traveter/base.htmt’ %}
{% block content %}
<hl>{{titte}}</hl>
<P> The content of the article </p>
endblock %}
Continents
Page content
admin.py
ft apps py
forms.py
[$, models.py
tests, py
& urls.py
views, py
> EB travels
db.sqlite3
manage, py
class AddPostForm(forms.Form):
title = forms.CharField(max_length=255)
slug = forms.SlugField(max_length=255)
content =
forms.CharField(widget=forms.Textarea(attrs=
{'cols': 60, 'rows': 10}))
is_published = forms.BooleanField()
cat =
forms.ModelChoiceField(queryset=Category.objects.a
ll())
def addpage(request):
form = AddPostForm()
return render(request, 'traveler/addpage.html', {'form':
form, 'menu': menu, 'title': 'flofiaB^eHue cmambu'})
idef addpage(request):
form = AddPostForm()
I return render (request, 1 traveler/addpage. html1 , {'form': form, 'menu': menu, 'title': 'Addina an article '})
{% extends 'traveler/base.html' %}
{% block content %}
<h1>{{title}}</h1>
{% extends 'traveler/base.html’ %}
{% block content %}
<hl>{-{title}}</hl>
{% endblock %}
Is published: □
Cat: |------
Add
def addpage(request):
if request.method == 'POST':
form = AddPostForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
else:
form = AddPostForm()
return ...
27 Rdef addpage(request):
28 R if request.method == 'POST':
form = AddPostForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
else:
33 form = AddPostFormO
34 A return render(request, 'traveler/addpage.html', {'form': form, 'menu': menu, 'title': Adding an article •})
{'title': 'Er^net', 'slug': 'Egypt', 'content': 'Egypt', ' is_publlshed ’ : True, 'cat': cCategory: Africa >}
[13/0ec/2022 11:15:23] "POST /addpage/ HTTP/1.1" 200 3564
Adding an article
Title: I Tunis |
• The value must contain only Latin letters, numbers, underscores or hyphens.
Slug: jhjhjjjjpopn ~|
class AddPostForm(forms.Form):
title = forms.CharField(max_length=255, label=" Title ")
slug = forms.SlugField(max_length=255, label="URL")
content = forms.CharField(widget=forms.Textarea(attrs=
{'cols': 60, 'rows': 10}), label=" Content")
is_published = forms.BooleanField(label=" Publication
")
cat =
forms.ModelChoiceField(queryset=Category.objects.all(),
label=" Categories ")
Hfrom djangc import forms
4 'iclass AddPostForm(forms.Form):
cat =
forms.ModelChoiceField(queryset=Category.objects.all(),
label=" Categories ", empty_label=" Category not
selected ")
This parameter allows writing this message instead of
dashes in the field.
class AddPostFormCforms.Form):
title = forms.CharField(max_length=255, label="header")
slug = forms.SlugField(max_length=255, label="URL")
content = forms. CharField (widget=forms. Textarea (attrs={' cols 1 : 60, 'rows': 10}), la bel=" Content")
is_publlshed = forms.BocleanField (label-"Publication" f required=False, initial=True)
cat = forms.ModelChoiceFieldCqueryset=Category.objects.all(), la bel=" Categories" , empty_label= "Category not selected")
<P>
<label class="form-label" for="{{
form.title.idforlabel }}">{{ form.title.label}}:
</label>
{{ form.title }}
</p>
<div class="form-error">{{ form.title.errors }}
</div>
<P>
<label class="form-label" for="{{
form.slug.id_for_label }}">{{ form.slug.label}}:
</label>
{{ form.slug }}
</p>
<div class="form-error">{{ form.slug.errors }}
</div>
<P>
<label class="form-label" for="{{
form.content.id_for_label }}">{{ form.content.label
}}: </label>
{{ form.content}}
</p>
<div class="form-error">{{ form.content.errors }}
</div>
<P>
<label class="form-label" for="{{
form.is_published.id_for_label }}">{{
form.is_published.label}}: </label>
{{ form.is_published }}
</p>
<div class="form-error">{{
form.is_published.errors }}</div>
<P>
<label class="form-label" for="{{
form.cat.id_for_label }}">{{ form.cat.label}}:
</label>
{{ form.cat}}
</p>
<div class="form-error">{{ form.cat.errors }}
</div>
<P> Reader
<label class='Tform-label" for="{{ form.title.icLfor_label }}">{{ form, title .label }}: </label>
{{ form.title }} Q]
</p>
<div class=,Tform-error">{{ form.title.errors }}</div>
<p>
<label class=irform-label" for="{-{ form.slug.id_for_label }}'’>-{{ form, slug .label }}■: </label>
- {{ form.slug }}
</p>
<div class="form-error,r>{-{ form, slug .errors }}</div>
<p>
<label class-"fcrm-label" for-"{{ form.content.id_for_label }}">-{{ form.content.label </label>
- {{ form.content }}
</p>
<div class=,rform-error,r>{-{ form.content.errors }}</div>
URL: | |
Content:
Publication: □
Add
{% for f in form %}
{% endfor %}
{% for f in form %}
{% endfon %}
Adding an article
Title: |
URL: Q
Content:
Publication: □
Add
All fields now have the same formatting styles under
class="form-label" and class="form_error," but
they can be customized if desired. Each field can have
its own style assigned to it. Let's navigate to the
forms.py file and within the AddPostForm class,
specify a special parameter called widget
class AddPostForm(forms.Form):
title = forms.CharField(max_length=255, label=" Title ",
widget=forms.TextInput(attrs={'class': 'form
input'}))
slug = forms.SlugField(max_length=255, label="URL")
content = forms.CharField(widget=forms.Textarea(attrs=
{'cols': 60, 'rows': 10}), label="KoHTeHT")
is_published = forms.BooleanField(label=" Publication ",
required=False, initial=True)
cat =
forms.ModelChoiceField(queryset=Category.objects.all(),
label=" Categories ", empty_label=" Not selected category
")
TextInput(attrs={'class': 'form-input'}))
In this case, the line attrs={'class': 'form-input'}))
will mean that for the title...
Title:
URL: |
Content:
Publication: □
Add
Next, let's proceed with adding the data from the form
into the database.
Open views.py and add a few lines of code to the
addpage module
def addpage(request):
if request.method == 'POST1:
form = AddPostForm(request.POST)
if form.is_valid():
#print(form.cleaned_data)
try:
Dir_travel.objects.create(**form.cleaned_da
ta)
return redirect('home')
except:
form.add_error(None, 'Post addition error')
else:
form = AddPostForm()
return render(request, 'traveler/addpage.html', {'form':
form, 'menu': menu, 'title':
‘Adding an article'})
Hdef addpage(request):
E if request.method == 'POST':
form = AddPostForm(request.POST)
if form.is_valid():
#print(form.cleaned_data)
try:
Dir_travel.objects.create(**form.cleaned_data)
return redirect(1 home 1)
except:
form.add_error(None, 'Erroradding post' )
else:
form = AddPostFormO
A return render(request, 'traveler/addpage.html', {'form': form, 'menu': menu, 'title': 'Adding an article'})
{% csrf_token %}
<div class="form-error">{{ form.non_field_errors
}}</div>
{% for f in form %}
{% csrf_token %}
<div class="form-error">{{ form.non_field_errors }}</div>
{% for f in form %}
Add
Adding an article
Title:
Article text
Publication:
Category:
Add
class AddPostForm(forms.ModelForm):
class Meta:
model = Dir_travel
fields = ['title', 'slug', 'content', 'is_published', 'cat']
widgets = {
'title': forms.TextInput(attrs={'class': 'form
input'}),
'content': forms.Textarea(attrs={'cols': 60,
'rows': 10}),
}
□ class AddPostForm(forms.ModelForm) :
class Meta:
model = Dir_travel
fields = ['title1, 'slug', 'content', 'is_published', 'cat']
widgets = -{
'title': forms. Textinput (attrs=-{' class': 'form-input'}),
'content': forms.Textarea(attrs={'cols': 6G, 'rows': 10}),
}
class AddPostForm(forms.ModelForm):
def_ init_ (self, *args, **kwargs):
super()._ init_ (*args, **kwargs)
self.fields['cat'].empty_label = 'Category not
selected'
class Meta:
model = Dir_travel
fields = ['title', 'slug', 'content', 'is_published', 'cat']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-input'}),
'content': forms.Textarea(attrs={'cols': 60, 'rows':
10}),
}
class AddPostForm(forms.ModelForm):
def _init_ (self, *args, **kwargs):
super().__ init__ (*args, **kwargs)
self .fields ['cat'] .empty_label = ' Category not selected '
class Meta:
model = Dir_travel
fields = ['title1, 'slug', 'content', 'is_published', 'cat']
widgets = ■(
'title': forms.TextInput(attrs=-{' class': 'form-input'}),
'content': forms.Textarea(attrs={'cols': 6G, 'rows': 10}),
}
def addpage(request):
if request.method == 'POST1:
form = AddPostForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = AddPostForm()
return render(request, 'traveler/addpage.html', {'form':
form, 'menu': menu, 'title': ‘Adding an article'})
27 i def addpage(request):
28 i-i if request.method == 'POST':
form - AddPostFormCrequest.POST)
if form.is_validC):
#print(form.cleaned_data)
32 form.saveC)
return redirect('home')
else:
form = AddPostFormO
37 El return renderfrequest, ' traveler/addpage . html', {'form': form, 'menu': menu, 'title': ' Addino an article 1})
Continent: Europe
Spain
GHGCDHVSDH SHCDJ SDCJBSJHDBC
Spain
ghgcdhvsdh shedj sdej b sj hd be
class AddPostForm(forms.ModelForm):
def_ init_ (self, *args, **kwargs):
super()._ init_ (*args, **kwargs)
self.fields['cat'].empty_label = 'Category not selected'
class Meta:
model = Dir_travel
fields = ['title', 'slug', 'content', 'photo', 'is_published',
'cat']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-input'}),
'content': forms.Textarea(attrs={'cols': 60, 'rows':
10}),
}
fictass AddPostForm(forms.ModelForm):
def _init_ (self, *args, **kwargs):
super(). _init (*args, **kwargs)
self .fields [ 'cat' ] .empty_label = ' Category not selected '
class Meta:
model = Dir_travet
fields = ['title', 'slug', 'content', 'photo', 'is_published', 'cat']
widgets = {
13 T 'title': forms.Textlnput(attrs={'class': 'form-input'}),
'content': forms.Textarea(attrs=-{'cots1: 60, 'rows': ID}),
def addpage(request):
if request.method == 'POST1:
form = AddPostForm(request.POST, request.FILES)
if form.is_valid():
#print(form.cleaned_data)
form.save()
return redirect('home')
else:
form = AddPostForm()
return render(request, 'traveler/addpage.html', {'form':
form, 'menu': menu, 'title': ‘Adding an article'})
jidef addpage(request):
ji if request.method == 'POST':
form - AddPostForm(request.POST, request.FILES)
if form.is_valid():
#print(form.cleaned_data)
form.save()
• return redirect('home')
else:
form = AddPostFormO
•1 return render(request, 'traveler/addpage.html', {'form': form, 'menu': menu, 'title': 'Adding an article '})
Ad d a rtic le Feed ba ck
Netherlands
The Netherlands (Dutch: Nederland [ ne:dar
Caribbean. It is the largest of four constituen
Germany to the east, and Belgium to the sou
Belgium in the North Sea.[18] The country’s
Saxon and Limburgish are recognised region
English and Papiamento are official in the C;
Netherlands literally means "lower countries" in reference to its low elevation and 1
level. [24] Most of the areas below sea level, known as polders, are the result of lane
unique era of political, economic, and cultural greatness, ranked among the most pc
trading companies, the Dutch East India Company and the Dutch West Lidia Comp;
With a population of 17.7 million people, all living within a total area of 41,850 km
country in the world and the second-most densely populated country in the Europe?
largest exporter of food and agricultural products by value, owing to its fertile soil.
def clean_title(self):
So, let's write down
def clean_title(self):
title = self.cleaned_data['title']
if len(title) > 200:
raise ValidationError(‘The length exceeds 200
characters')
return title
def clean_title(self):
title = self.cleaned_data['title']
19 t if len(title) > 200:
raise ValidationError('Lengthexceeds200characters ')
return title
Adding an article
Title: | dfg fdddddddddddddddddddg dfgddddddd» |
Article text:
Publication: □
Category: | Ash
Add
Next, let's create a class that will handle the main page
and name it
Dir_travelHome.
class Dir_travelHome(ListView):
model = Dir_travel
Rclass Dir_travetHome(ListView):
model = Dir_travet
class Dir_travelHome(ListView):
model = Dir_travel
templatename = 'traveler/index.html'
3class Dir_travelHome(ListView):
model - Dir_travel
17 ©t 0 template_name = ’travelen/index.html’
Continents
Europe
Asia
{% for p in objectjist %}
5 for p in object_list
<lixdiv class="article-panel">
class Dir_travelHome(ListView):
model = Dir_travel
template_name = 'traveler/index.html'
context_object_name = 'posts'
Rclass Dir_travelHome(ListView):
17 Of model = Dir_travel
18 Of template_name = ’traveler/index.html ’
19 Of 0 context_object_name = 'posts’
class Dir_travelHome(ListView):
model = Dir_travel
template_name = 'traveler/index.html'
context_object_name = 'posts'
extra_context = {'title': 'Home Page'}
class Dir_travetHome(ListView):
model = Din_travel
template_name = ’tpavelen/index.html
context_object_name = 'posts’
extra_context = {’title’: 'Main page’}
- Main page
class Dir_travelHome(ListView):
model = Dir_travel
template_name = 'traveler/index.html'
context_object_name = 'posts'
extra_context = {'title': 'Home Page'}
nclass Dir_travelHome(ListView):
17 Of model = Dir_travel
18 Of template_name = 'traveler/index.html'
19 Of context_object_name = 'posts'
20 Of extra_context = -{'title': 'Main page1}
nclass Dir.travelHome(ListView):
17 Gf model = Dir_travel
18 Gt template_name = 'traveler/index.html'
19 Gt context_object_name = ’posts'
Europe
Asia
Africa
South America
def get_queryset(self):
return
Dir_travel.objects. filter(is_published=True)
class Dir_travelCategory(ListView):
model = Dir_travel
templatename = 'traveler/index.html'
context_object_name = 'posts'
def get_queryset(self):
return
Dir_travel.objects. filter(cat_ slug=self.kwargs[cat_sl
ug], is_published=True)
;lclass Dir_travelCategory(ListView):
54 ©1 model = Dir_travel
55 ©t template_name = 'tnaveler/lndex.html’
56 ©t context_object_name = 'posts'
57
58 ©T def get_queryset(self):
59 return Dir_travel.objects,filter(cat__slug=self.kwargsf'cat_slug'], is_published=True)
urlpatterns = [
path(", Dir_travelHome.as_view(), name^home'),
path( about/, about, name='about'),
path( addpage/, addpage, name='add_page'),
path( 1 contact/, addpage, name= 1 contact'),
path('login/, login, name='login'),
path( 1 post/<slug:post_slug>/, show_post, name=post'),
path('category/<int:catjd>/, show_category,
name='category'),
]
return
Dir_travel.objects.filter(cat__slug=self.kwargs['ca
t_slug'], is_published=True)
def get_absolute_url(self):
return reverse('category', kwargs={'cat_slug':
self.slug})
context = super().get_context_data(**kwargs) -
We form the data context that is already created by the
base ListView class.
context['title'] = 'Category - ' +
str(context['posts'][0].cat)
In this line, posts represent the collection of read
records, where we take the first record [0] and access
the 'cat' attribute, which returns the category's name.
We convert all of this into a string using str and add it
to the string 'Category - '.
context['cat_selected'] = context['posts']
[0].cat_id - We do the same, but this time we fetch the
identifier of the selected category, cat_id.
And we return return context.
Let's check how this will work.
It seems everything is working as intended. If you
navigate to the 'Europe' category, you'll notice that
everything works just as planned.
t Category Europe
Continents
Asia
Italy
Africa ITALY (ITALIAN: IT;
South America
However, there is one nuance. Let's type in the
browser's address bar a non-existing slug, for example
http://127.0.0.1:8000/category/aziya5/
y Hac B03HUKHem oi±iu6ka
-> C © 127.0.0.1:8000/category/aziya5/
IndexError at /category/aziya5/
list index out of range
Request Method: GET
Request URL: http://127.0.0.1:8000/category/aziya5/
Django Version: 4.1.1
Exception Type: IndexError
Exception Value: list index out of range
Written
Exception Value: list index out of range
We'll refresh the page and see that when the page
doesn't exist, a 404 error occurs.
Using the URLconf defined in Travels.mis, Django tried these URL patterns, in this order:
class ShowPost(DetailView):
model = Dir_travel
template name =' traveler/post.html'
Rclass ShowPost(DetailView):
Of model = Dir_travel
Of A template_name = 'traveler/post.html'
path('post/<slug:post_slug>/', ShowPost.as_view(),
name='post'),
class ShowPost(DetailView):
model = Dir_travel
template_name = 'traveler/post.html'
slug_url_kwarg = 'postslug'
Rclass ShowPost(DetailView):
model = Dir_travel
66 ©T template_name = ’traveler/post.html’
67 ©T A slug_url^kwarg = ’post_slug’
Continents
Europe
Germany
Asia Germany (German: Deutschland, j
populous country in Europe after I
Africa and the Alps to the south; it covers
borders Demnark to the north, Pol;
to the west. The nation's capital an
South America
Various Germanic tribes have inha
North America 962, the Kingdom of Germany for.
Reformation. Following the Napol
class AddPage(CreateView):
form_class = AddPostForm
templatename = 'traveler/addpage.html'
urtpatterns = [
path('', Dir_traveLHome.as_view(), name=1 home'),
pathC1 about/r, about, name-'about1),
pathC'addpage/1, AddPage.as_view(), name='add_page'),
□class AddPage(CreateView):
37 0| form_class = AddPostForm
38 O| template_name = 'traveler/addpage.html'
39
def get_context_data(self, *, oblect_list=None, **kwargs):
context = super().get_context_data(**kwargs)
context ['title ' ] = 1 Adding an article '
context['menu'] = menu
return context
class Meta:
verbose_name = ’'All countries 11
verbose_name_plural = 11 All countries 11
ordering ~ [1 -time_create ', 'title']
Line '27'
ordering = ['-time_create', 'title']
If not all entries are needed but only some, this can be
done using slice syntax. Let's select the first 3 entries.
Dir_travel.objects.all()[:3]
??? Dir_travel.objects.all()[:3]
<QuerySet [<Dir_travel: Tunisia?, <Dir_travel: Tanzania?, <Dir_travel: Netherlands?]?
»> Dlr.travel.objects.all()[2:5]
<QuerySet [<Dir_travel: Netherlands?, <Dir_travel: Tanzania?, <Dir_travel: Zimbabwe?]?
LIMIT 3 OFFSET 2’ ,
»> Dir.travel.objects.order.byi'pk')
<QuerySet [<Dir_travel: Ukraine?, <Dir_travel: Poland?, <Dir_travel: Germany?, <Dir_travel: Italy?, <Dir_travel: Brazil?, <Dir_travel: Peru?, <Oir_travel: Mexico?, <Dir_travel: United
States?, <Dir_travel: Canada?, <Dir_travel: China?, <Dir_travel: Cambodia?, <Dir_travel: Zimbabwe?, <Dir_travel: Tanzania?, <Dir_travel: Netherlands?, <Dir_travel: Tanzania?, <Dir_trav
el: Tunisia?]?
Keyboardinterrupt
»> from traveler.models import*
And after that, let's repeat entering the command
Dir_travel.objects. filter(pk_ lte=2)
>» Dir_travet.objects.fitter(pk_ tte=2)
<QuerySet [<Dir_travet: Potand>, <Dir_travet: Ukraine>]>
»> n
»> c.Dir_travel_set
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Category' object has no attribute 'Dir_travel_set'
>» c.dir_travel_set
<django.db.models.fields,related.descriptors.create.reverse_many_to_one_manaqer .<locals>.RelatedManager object at 0x00000169F39C5270>
»> c.dir_travel_set.all()
<QuerySet [<Dir_travet: Netherlands:*, <Dir_travet: Italy>, <Dir_travel: Germany:*, <Dir_travel: Poland:*, <Dir_travel: Ukraine>]>
Field filters.
< Attribute name >_ gte - Greater than or equal to
comparison (>=);
< Attribute name >_ Ite - Less than or equal to
comparison (<=);
Those are called lookups:_ gte and_ Ite, which allow
us to select records based on conditions of >= or < =
respectively.
»> Dir.travel.objects.all()
<QuerySet [<Cir_tnavel: Tunisia?, <Cir_tnavel: Tanzania?, <Cir_tnavel: Netherlands?, <Bir_travel:
Tanzania?, <Dir_travel: Zimbabwe?, <Dir_travel: Cambodia?, <Cir_travel: China?, <Dir_travel: Canad
a?, <Dir_travel: United States?, <Cir_tnavel: Mexico?, <Dir_travel: Peru?, <Cir_travel: Brazil?, <
□ir_travel: Italy?, <Dir_travel: Germany?, <Dir_travel: Poland?, <Dir_travel: Ukraine?]?
Dir_travel.objects.order_by('pk').first()
or
Dir_travel.objects.order_by('-pk'). first()
>» Dir_travel.objects .order_by(’-pk’).first()
<Dir_travel: Tunisia?
>»
or
Dir_travel.objects.order_by('-pk').last()
??? Dir_travel.objects.order_by('-pk’).last()
<Dir_travel: Ukraine?
??? n
??? Dir_travel.objects.latest('time_update’)
<Dir_travel: Tunisia?
???
>» w.get_previous_by_time_update ()
<Dir_travel: Brazil?
??? n
>>> new.dir_travel_set.existsf)
False
>» n
»> cl = Category.objects.get(pk=l)
>» cl
^Category :Europe >
>» cl.dir_travet_set. existsQ
True
>» n
To find out the number of entries for a specific
category, we use the second method by analogy.
c1.dir_travel_set.count()
»> Dir_travel,objects.aggregate(Min(’cat_id’))
{’cat_id_ min': 1}
»> n
»> Dir_travel.objects.fitterfpk__gt=4).aggregate(res=Avg('cat_id'))
{'res1: 3.25}
»> w = Dir_travel.objects.get(pk=l)
»> w
<Dir_travel: Ukraine?
»> w.title
'Ukraine'
>» w.slug
'Ukraine’
>>> n
cQuepySet [{’title1: ’Tunisia1, 'cat_ name': 'Africa'} t {'title': 'Tanzania', 'cat__ name’: 'Africa'}, {’tit
le' : 'Netherlands', 'cat_ name': 'Eurooe'} , {'title': 'Tanzania', 'cat__ name': 'Africa'}, {'title': 'Zinbab
we', 'cat__name': 'Africa'}, {'title': 'Cambodia', 'cat__ name’: 'Asia'} , {'title': 'China', 'cat__ name’:
'Asia'}, {'title': 'Canada', 'cat__name’: ' North America '} , {'title': 'United States', 'cat__name': ’
'NorthAmerica {'title': 'Mexico', 'cat_ name': 'SouthAmerica '}, {'title': 'Peru', 'cat__ name': '
{'title': 'Brazil', 'cat name’: ' South America '}, {'title': 'Italy', 'cat name': 'Eurooe'}, {'tit
le' : 'Germany', 'cat_ name’: 'Eurooe'}, {'title': 'Poland', 'cat__ name’: 'Eurooe'}, {'title': 'Ukraine', 'c
at__name ' : ’ Eurooe ' }]>
Tunisia Africa
Tanzania Africa
Netherlands Eurooe
Tanzania Africa
Zimbabwe Africa
Cambodia Asia
China Asia
Canada North America
United States North America
Mexico South America
Pe ru South America
Brazil South America
Italy Eurooe
Germany Eurooe
Poland Eurooe
Ukraine Eurooe
class Dir_travelHome(ListView):
is ©r model = Dir_travel
19 ©r template_name = 'traveler/index.html'
20 ©t context_object_name = 'posts'
context!'cat_selected'] = 0
return context
30 ©T H def get_queryset(self):
return Dir_travel.objects.filter (is_published=True)
Hdef about(request):
return renderfrequest, 'traveler/about.html', {'menu': menu, 'title': 'About sile'})
admin.py
ftappspy
i^forms.py
models.py
r< tests.py
ft urls.py
util spy
views, py
v El travels
@Oegister.inclusion_tag(' traveler/list_categories.html')
15 def show_categories(sort=None, cat_selected=0):
if not sort:
cats = Category.objects.attO
else:
cats = Category.objects.order_by(sort)
return {"cats": cats, "cat_selected": cat_selected}
44 {% show_categories cat_selected=cat_selected %}
<li class="share">
<p>Haui KaHan</p>
<a class="share-yt" href="#"x/a>
</li>
Let's do the following: Remove the line
{% show categories cat_selected=cat_selected %}
And instead, we'll specify the output of categories using
the category cats
{% for c in cats %}
{% if c.pk = = cat_selected %}
<li class="selected">{{c.name}}</li>
{% else %}
<li> <a href="{{ c.get_absolute_url }}">
{{c.name}}</a></li>
{% endif %}
{% endfor %}
class DataMixin:
def get_user_context(self, **kwargs):
context = kwargs
cats = Category.objects.all()
context['menu'] = menu
context['cats'] = cats
if 'cat_selected' not in context:
context['cat_selected'] = 0
return context
Next, we set
context['cat_selected'] = 0
and check if 'cat_selected' not in
context. If we somehow define the **kwargs key within the
parameters of the function def get_user_context(self,
**kwargs),
then in the context if 'cat_selected' not in context, this key
will be present, and in this case, we won't override it. If this
key is absent, then by default, we create
context['cat_selected'] = 0.
Finally, we return the context using return context.
def get_queryset(self):
return
Dir_travel.objects.filter(cat_slug=self.kwargs['cat_slug'],
is_published=True)
def get_queryset(self):
return Bir_travel.objects.filter(cat__ slut - self. kwargs[ ’ cat_slug 1 ], is_put>lished=Tnue)
Article tex:
Photo:
Publication:
Add
Using the URLconf defined in Travels.mis, Django tried these URL patterns, in this order:
And then, if the user is not authorized, they will see the
page
O 127.0.0.1:8000/add page/
403 Forbidden
If the user logs in
Adding an article
Title:
Article text:
Photo:
Publication:
Category:
Add
@login_required
def about(request):
return render(request, 'traveler/about.html', {'menu':
menu, 'title': 1 About page'})
@login_required
Hdef about(request):
32 A return render(request, 'traveler/about.html', {'menu': menu, 'title': 'Aboutttie site>
class DataMixin:
def get_user_context(self, **kwargs):
context = kwargs
cats = Category.objects.all()
user_menu = menu.copy()
if not self.request.user.is_authenticated:
user_menu.pop(1)
context['menu'] = user_menu
context['cats'] = cats
if 'cat_selected' not in context:
context['cat_selected'] = 0
©1 HcLass DataMixin:
def get_user_context (self, **kwargs):
context = kwargs
cats = Category.objects.all()
user_menu = menu.copyO
if not self.request.user.is_authenticated :
16 user_menu.pop(1)
context['menu’] = user_menu
context[‘cats’] = cats
if 'cat_selected’ not in context:
context[’cat_selected'] = 0
4- -> O Q 127.0.0.1:8000/category/antarcti
©1 class DataMixin:
def get_user_context(self, **kwargs):
r
context = kwargs
cats = Category.objects.all()
cats = Category.objects.annotate(Count('dir_travel'))
{% for c in cats %}
{% if c.dir_travel_ count > 0 %}
{% if c.pk == cat_selected %}
<li class="selected">{{c.name}}</li>
{% else %}
<li> <a href="{{ c.get_absolute_url }}">
{{c.name}}</a></li>
{% endif %}
{% endif %}
{% endfor %}
■{% for c in cats %}
{% if c.dir_travel_ count > 0 %}
{% if c.pk == cat_selected %}
<li class=" select ed">-({c. name}}</li>
{% else %}
<li> <a href="-{{ c. get_absolute_url }}">-{-{c. name}}</ax/li>
endif %}
■{% endif %}
{% endfor %}
Continents
Asia
Africa
Europe
North America
South America
Our channel
a YouTube
And, as you can see, the category without any posts is
absent.
Pagination
Pagination, or as often called, paging, is needed when
there's a long list of posts on a page that impairs text
readability. This option allows breaking long lists into
multiple pages and displaying navigational links at the
bottom for each page, presented as easily accessible
links.
For more details on pagination, you can read at the
following link...
https://django.fun/ru/docs/django/4.1/topics/pagination/
It's worth noting that this option can be applied using
various approaches.
1. Can be used separately.
2. In ListView, where pagination is already
embedded.
3. Pagination handling in the template.
4. For view functions.
5. Using attributes and methods of the Paginator
class
Let's go over the first approach.
We'll open the Python console and, first of all, import
from django.core.paginator import Paginator
We'll use it with some list.
We'll take an arbitrary list, for example...
Dir_travel = ['Ukraine', 'poland', 'austria', 'germany',
'italy', 'spain', 'hungary']
9 I™ Python 3.10.7 (tags/v3.10.7:6cc6bl3, Sep 5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on Win32
0. ►» from django.core.paginator import Paginator
+ Q Oir_travel = ['Ukraine1, 'poland', 'austria', 'germany', 'Italy', 'spain’, 'hungary']
9 ’ pl - p.page(l)
C* ►» pl.object_list
+ © ['Ukraine', ’potand’, 'austria']
O, ►» pi .has_other_pages()
+ True
G, ►» pl.n ext_page_numberO
+ © 2
def about(request):
contact_list = Dir_travel.objects.all()
paginator = Paginator(contact_list, 3)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'traveler/about.html',
{'page_obj': page_obj, 'menu': menu, 'title': About
the site'})
□def about(request):
contact_list = Dir_travel.objects.all()
paginator - Paginator(ccntact_list, 3)
page_number = request.GET.get('page')
38 ? page_obj - paginator.get_page(page_number)
return render(request, 1traveler/about.html1, {'page_obj': page_obj, 'menu': menu, 'title': '0 caiiTe'})
page_number = request.Get.get('page') - We
retrieve the page number from the current GET
request, where we take the 'page' parameter formed
within this request.
page_obj = paginator.get_page(page_number) -
The list of elements on the current page, where we
access the instance of the paginator class and utilize a
function... get_page We access the page obtained
from the GET request, 'page_number,' and then the
'page_obj' list should be passed to the template
return render(request, 'traveler/about.html',
{'page_obj': page_obj, menu': menu, 'title': ‘About
the site’})
block content %}
<hl>{-{title}}</hl>
10 {% endblock %}
Tunisia
Tanzania
Netherlands
127.0.0.1:8000/about/?page=2
About the site
Tanzania
Zimbabwe
Cambodia
And so on.
<nav>
<ul>
{% for p in page_obj.paginator.page_range %}
<li>
<a href="?page={{ p }}">{{ p }}</a>
</li>
{% endfor %}
</ul>
</nav>
H<nav>
<ul>
{% for p in page_obj.paginater.page_range %}
<li>
<a href=,T?page={{ p }}">{-{ p }}</a>
</li>
{% endfor %}
</ul?
A</nav>
20 {% endblock %}
Germany
Poland
• 1
• 2
• 4
• 5
• 6
<nav class="list-pages">
<ul>
{% for p in paginator.page_range %}
<li class="page-num">
<a href="?page={{ p }}">{{ p }}</a>
</li>
{% endfor %}
</ul>
</nav>
<nav ctass='T’List-pages">
{% for p in paginator.page_range %}
<li class="page-num1T>
<a href="?page=-{-{ p }}’'>{{ p }}</a>
</li>
{% endfor %}
</ul>
</nav>
.list-pages {
text-align: center;
margin: 0 0 20px 0;
}
.list-pages ul {
margin: 20px 0 0 0;
padding: 0;
list-style: none;
}
.list-pages ul li {
display: inline-block;
margin: 0 20px 0 0;
}
.list-pages a {
color: #000;
font-size: 24px;
text-decoration: none;
}
.list-pages .page-num, .page-num-selected {
display: inline-block;
width: 60px;
height: 44px;
padding: 16px 0 0 0;
border: 1px solid #d0d0d0;
border-radius: 30px;
}
.list-pages .page-num:hover {
box-shadow: 3px 3px 1px #d0d0d0;
}
.list-pages .page-num-selected {
border: none;
color: #000;
font-size: 20px;
}
.list-pages .page-num-selected:hover {
box-shadow: none;
<nav class="list-pages">
<ul>
{% for p in paginator.page_range %}
{% if page_obj.number == p %}
<li class="page-num page-num-selected">{{ p
}}</li>
{% else %}
<li class="page-num">
<a href="?page={{ p }}">{{ p }}</a>
</li>
{% endif %}
{% endfor %}
</ul>
</nav>
<nav class="list-pages">
<ut>
{% for p in paginator.page_range %}
{% if page_obj.number == p %}
<li class="page-num page-num-selected">-{-[ p }}</li>
{% else %}
<li class="page-num">
<a href="?page=-{-{ p }}">-(-( p }}</a>
</li>
{% endif %}
endfor %}
</ul>
</nav?
12 3 4 5
endif %}
■{% endfor %}
</uL>
□ </nav>
{% endif %}
</div>
</nav>
□tnav class="list-pages">
<ut>
{% for p in paginator.page_range %}
{% If page_obj.number == p %}
<U class="page-num page-num-selected">-(-{ p }}</li>
{% elif p >= page_obj.number|add:-2 and page_obj.number|add:2 %}
<li class="page-num">
<a href="?page=-{-[ p }}">-{{ p }}</a>
</li>
{% endif %}
{% endfor %}
f
83 A</nav>
{% if page_obj.has_next %}
<li class="page-num">
<a href="?page={{ page_obj.next_page_number }}">></a>
</li>
{% endif %}
Access rights
Q Active
Check if the user should be considered active. Uncheck this box instead of deleting the account.
E3 Staff status
Check if the user can enter the administrative part of the site.
□ Superuser status
Indicates that the user has al rights without being expUcily assigned.
So, we can request all these fields from the user during
registration. Let's start by adding a link for new user
registration.
First, let's navigate to the base.html template and
locate where the main menu is displayed. Then, we'll
slightly modify this block.
{% for m in menu %}
<li><a href="{o%o url m.url_name %}">
{{m.title}}</a></li>
{% endfor %}
<li class='last'><a href="{% url 'register'
%o}''>Pe^ucTpa^uH</a> | <a href="{%o url 'login'
%}''>BoMTu</a></li>
Registration | To come in
{% extends 'traveler/base.html' %}
{% block content %}
<h1>{{title}}</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit"> Registration </button>
</form>
{% endblock %}
<% extends ’traveler/base.html’ %}
H<form method=,Tpost,T>
{% csrf_token %}
form.as_p }}
<button type=" submit11 Registration </but ton?
Ei</form>
L2 {% endblock %}
Registration
Username: Required | | field. No more than 150 characters. Letters, numbers, and symbols only.
Password: | |
• The password should not be too similar to your other personal information.
* Your password must contain at least 8 characters.
* The password should not be too simple or common.
• The password cannot contain only numbers.
class RegisterUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'password^, 'password2']
widgets = {
'username': forms.TextInput(attrs={'class':
'form-input'}),
'password^: forms.PasswordInput(attrs=
{'class': 'form-input'}),
'password2': forms.PasswordInput(attrs=
{'class': 'form-input'}),
}
Rclass RegisterUserForm(UserCreationForm):
class Meta:
30 model = User
31 fields = ['username1, 'passwordl1, 'password2']
32 widgets = ■{
'username1: forms.TextInput(attrs=-{'class': 'form-input'}),
34 'passwordl': forms.PasswordinputCattrs={'class': 'form-input'}),
35 'password2': forms.PasswordinputCattrs={'class ' : 'form-input'}),
36 }
Change user
root
This user's password, but you can change it using this form.
And navigate
Password:
The password should not be too similar to your other personal information.
Let's also add styles for all fields since the standard
Django method didn't apply styles to all fields.
Registration
Password: | |
• The password should not be too similar to your other personal information
• Your password must contain at least 8 characters.
• The password should not be too simple and common.
• The password cannot consist only of numbers.
Registration
class RegisterUserForm(UserCreationForm):
username = forms.CharField(label='Login',
widget=forms.TextInput(attrs={'class': 'form
input'}))
email = forms.EmailField(label='Email',
widget=forms.EmailInput(attrs={'class': 'form
input'}))
password1 = forms.CharField(label='Password',
widget=forms.PasswordInput(attrs={'class': 'form
input'}))
password2 = forms.CharField(label='Confirm
password', widget=forms.PasswordInput(attrs=
{'class': 'form-input'}))
class Meta:
model = User
fields = ('username', 'email', 'passwordl',
'password2')
28 Hclass RegisterUserForm(UserCreationForm):
username = forms.CharField(label= 'Loain ', widget=forms.Textlnput(attrs={'class 1: 'form-input'}))
email - forms.EmailField(label='Email', widget-forms.EmailInput(attrs-{'class': 'form-input'}))
passwordl = forms.CharField(label='Password ', widget=forms.Passwordlnputfattrs-}'class': 'form-input'}))
password2 = forms. CharField (label='Password repeat ', widget=forms.Passwordinput(attrs=-['class': 'form-input'}))
34 H class Meta:
model = User
fields = ('username', 'email', 'passwordl', 'password2')
{% extends 'traveler/base.html' %}
{% block content %}
<h1>{{title}}</h1>
<form method='"post'">
{% csrf_token %}
{% for f in form %}
<p><label class=''form-label" for="{{ f.id_for_label
}}">{{f.label}}: </label>{{ f }}</p>
<div class=''form-error">{{ f.errors }}</div>
{% endfor %}
{% endblock %}
{% extends 'traveler/base.html' %}
Reform method="post">
{% csrf.token %}
{% for f in form %}
epxlabel class="form-label" for="{{ f.id_for_label }}">{{f.label}}: </label>{{ f }}</p>
<^lv class="form-error">{{ f.errors }}</div>
12 endfor %}
endblock %}
| Registration |
Authorization
Q | || F"a I
Action: [--------- v|[ Run | Selected 0 items out of2
□ root [email protected] O
□ user_1 [email protected] O
used
Username: user_1
Obi 93*07 fl«id htomowfhan 150 charAtXerv Oriyb
Personal information
User authorization
First, in the views.py file, let's add a view responsible
for the authorization form.
Our class, which we have just created, will use the logic
of the LoginView class and the form of the
AuthenticationForm class. The form will be displayed
in the template template_name =
'traveler/login.html'.
And for creating the context for this template
M templates
v M traveler Reform method="post">
ifl abouthtml {% csrf_token %}
iTm addpage.html {-{ form.as_p }}
base.html
index.html ebutton type=" submit"xo come i</button>
list_categories.html Be/form>
login,html
post.html
13 endbtock %}
im register.html
Hdef login(request):
return HttpResponse ("Authorization ")
Password: | |
Authorization
Username: |user 2 |
Password: ....... |
def get_success_url(self):
return reversejazy('home')
LOGIN_REDIRECT_URL = '/'
DEFAULT_AUTO_FIELD = 1django.db.models.BigAutoField1
133 LOGIN_REDIRECT_URL =
39 Hclass LoginUserForm(AuthenticationForm):
username = forms.CharField (label='JlorMH', widget=forms.Textinput(attrs={'class': 'form-input'}))
41 Of B password = forms. CharField(label=' Flapo/ib', widget=forms. Passwordinput (attrs={ ’ class ' : 'form-input'}))
{% for f in form %}
<pxlabel class="form-label" for="{{ f.id_for_label }}">{{f.label}}: </label>{-{ f }}</p>
<div class="form-error">{-{ f.errors }}</div>
{% endfor %}
csrf_token
<div ctass="form-error">-{-{ form. non_fietd_errors }}</div>
Authorization
Please enter the correct username and password. Both fields can be case sensitive
Login:
Password:
Toccmam
Registration | To come in
{% block mainmenu %}
{% if request.user.is_authenticated %}
25 = <11 class='Tlast"> {{user.username}} I <a href="{% url 'logout' %}">Toconneia/a></li>
26 {% else %}
<11 class="last"><a href='T{% url 'register' %}'r>Reaistration </a> I <a href=,T{% url 'login' %}'r>Tocomeifi/a></li>
{% endif %}
def logout_user(request):
logout(request)
return redirect(‘login')
def logout_user(request):
logout(request)
return redirect('login 1)
There is no need to write a whole class, as the function
itself is very simple. This function calls the standard
logout function, which needs to be imported.
from django.contrib.auth import logout
Registration | To come in
and
127.0.0.1 8000/login/
Authorization
Password:
Tooarw ri
Everything is as intended
user_6 I Go out
Caching pages
SQL queries are executed to generate pages for our
website. It's important to understand that each client
request involves the creation of pages and
corresponding SQL queries.
Let's say your website is visited by 100-200, or even
1000-2000 people per day, and there's potential for
even more. For a typical website, the norm might be
several hundred thousand, or even a million queries per
day. How can you reduce the load on your website and
database?
To address this, caching mechanisms for pages were
introduced. You can find more detailed information at
the following link:
https://docs.djangoproject.com/en/4.1/topics/cache/
The idea behind caching is that if page updates are
infrequent and there are numerous requests for the
same page, it makes sense to generate the page the
first time and serve the previously generated HTML
document on subsequent requests.
This significantly reduces the load on databases and
servers.
Memory caching
Caching in Django can be implemented either at the
memory level using Memcached, at the database level,
or at the file system caching level - the most common
caching method. Let's consider this method for
organizing file system caching.
Navigate to settings.py and define a dictionary. Find the
standard lines of code in the documentation, copy
them, and paste them in
CACHES = {
'default': {
'BACKEND':
'django.core.cache.backends.filebased.FileBasedCach
e',
'LOCATION': 'c:/foo/bar',
}
}
139 }_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
settings.py
ft urls.py
&wsgi.py
travels_cache
db.sqliteS
manage.py
travel s_cache
jf?92123fc23b9e1a80ba6452d6dd302b95.djca
if?f6381ebc4d99f5b31350d62738758249.djca(
{% load cache %}
<td valign="top" class="left-chapters">
<ul id="leftchapters">
{% cache 60 sidebar %}
{% if cat_selected == 0 %}
<li class="selected">continents </li>
{% else %}
<lixa href="-{% url 'home' %}">continents</ax/li>
{% endif %}
{% for c in cats %}
{% if c.dir_travel_ count > 0 %}
{% if c.pk == cat_selected %}
<li class=" selected">-{-{c . name}}</li>
{% else %}
<li> <a href="-({ c.get_absolute_url }}">{-{c.na[ne}}</ax/li>
{% endif %}
{% endif %}
{% endfor %}
57 {% endcache %}
Next
cats = cache.get('cats')
if not cats:
cats =
Category.objects.annotate(Count('dir_travel'))
cache.set('cats', cats, 60)
cats = cache.get('cats')
if not cats:
cats = Category.objects.annotate(Count(’dir_travet'))
cache.set('cats ', cats, 60)
Feedback
Feedback
class ContactForm(forms.Form):
name = forms.CharField(label='WMH',
max_length=255)
email = forms.EmailField(label='Email')
content =
forms.CharField(widget=forms.Textarea(attrs=
{'cols': 60, 'rows': 10}))
Hclass ContactForm(forms.Form):
name = forms.CharField(tabel='Name', max_length=255)
email = forms.EmailField(label='Email1)
content = forms.CharField(widget=forms.Textarea(attrs={'cols': 60, 'rows': 10}))
This class will inherit from the general Form class and
will contain three fields.
Next, let's associate the ContactFormView with the
route
path('contact/', ContactFormView.as_view(),
name=,contact'),
base.html
contact.html
index.html
। list_categories.fr
login.html
post.html
itJ register.html
{% extends 'traveler/base.html' %}
{% block content %}
<h1>{{title}}</h1>
<form method="post">
{% csrf_token %}
<div class="form-error">{{ form.non_field_errors }}
</div>
{% for f in form %}
<p><label class="form-label" for="{{ f.id_for_label
}}">{{f.label}}: </label>{{ f }}</p>
<div class="form-error">{{ f.errors }}</div>
{% endfor %}
{% endblock %}
{% extends 'traveler/base.html1 %}
{% block content %}
<hl>{{title}}</hl>
H<form method="post">
{% csrf.token %}
<div class="form-error">{{ form.non_field_errors }}</div>
{% for f in form %}
<pxlabel class="form-label" for="{{ f.id_for_label }}">{{f.label}}: </label>{{ f }}</p>
<div class="form-error">-{-{ f.errors }}</div>
{% endfor %}
17 {% endblock %}
If you fill out the form with any data and submit it, you
will be redirected to the home page, as intended
return redirect('home')
tovenv
to Include
v to Lib
v to site-packages
> El _distutils_hack
> El asgiref
> to asgiref-3.5.Z.dist-info
> El captcha
> to captcha-0.4. di st-info
v El django
> to apps
> El conf
v to contrib
v El admin
> to locale
> El migrations
> to static
v totemplates
to admin
to admin
> to auth
> to editjnline
> to includes
> to widgets
404. h tn I
a 5D0.html
actions.html
app_index.html
app_list.html
base.html
base_site.html
ch a n g e _fo rm. htr
{% extends "admin/base.html" %}
{% block title %}-{% if subtitle %}{{ subtitle }} I -[% endif %}{{ title }} | {-[ site_title | default1 Django site admin'
{% block branding
<hl id="site-name"><a href="{% url 'admin:index' %}">-{-{ site_header|defaultDjango administration') }}</a></hl>
{% endblock %}
And copy all the contents from the previous file into this
one.
{% extends "admin/base.html" %}
□TEMPLATES = [
Django administration
{% extends "admin/base.html" %}
{% load static %}
{% block extrastyle %}
<link rel="stylesheet" href="{% static
'css/admin.css' %}">
{% endblock %}
{% block branding %}
<h1 id='"site-name'"><a href='"{% url 'admin:index' %}'">
{{ site_header|default:_CDjango administration') }}</a>
</h1>
{% endblock %}
Include it
{% load static %}
{% block title %H% if subtitle %}{{ subtitle }} I {% endif %H{ title }} I {{ site_titte I def ault:_(‘ Django site admin') }}{% endblock %}
block branding %}
<hl id="site-name"xa href="{% url 'admin:index' %}''>{{ site_header|defaultDjango administration’) }}</ax/hl>
LI {% endbtock %}
Django administration
Sheader ■{
background: S088A08;
3 }
Django administration
photos/2022/12/27/tu ni si a j pg
Rclass Dir_travelAdmin(admin.ModelAdmin) :
7 ©T list_display = ('id', 'title', 'time_create', 'photo', 'is_pubtished')
8 Of list_disptay_links = ('id', 'title')
9 ©T search_fields = ('title', 'content')
10 ©T list_editable = ('is_published',)
11 ©t list_filter = ('is_published', 'time_create')
12 ©T prepopulated_fields = {"slug": ("title",)}
Rclass Dir_travelAdmin(admin.ModelAdmin):
8 ©t list_display = ('id1, 'title', 'time_create', 'get_html_photo’, 'is_published')
9 O| list_display_links = ('id', 'title')
10 ©T search_fields = ('title', 'content')
11 Of | list_editable = (' is_published1,)
12 Of list_filter = ('is_published', 'time_create1)
13 ©T prepopulated_fields = {"slug": ("title",)}
MINIATURE PUBLICATION
s Publication
14 ©t fields = ('title', 'slug', 'cat1, 'content1, 'photo', 'get_html_photo', 'is_published', 'time_create', 'time_update')
15 ©t readonly_fields = ('time_create', 'time_update', 'get_html_phato')
Miniature:
□ Publication