-
Notifications
You must be signed in to change notification settings - Fork 0
/
DjangoDetails.txt
639 lines (430 loc) · 18.6 KB
/
DjangoDetails.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
DJANGO FRAMEWORK
NEEDS:
-Python Syntax
-Functions, return, arguments/ parameters
-modules --> group of functions, classes
-create own modules
-packages --> group of modules (folder) __init__.py (Script file)
-Exceptions Handling
DJANGO (2003-2005)
-Open Source
-Macro FRAMEWORK
-Micro FRAMEWORK (Flask FRAMEWORK)
-Web FRAMEWORK
-Free
Web Application --> Design Pattern (MVC) for other frameworks
But,DJANGO doesn't followed MVC Pattern
It follows MVT pattern
M - model
V - view
T - template
Other Python frameworks like pyramid, bottle, cherrypy and tornod etc.,
Features of DJANGO:
- Ridiculously Fast
- Fully Loaded
- Reassuringly secure
- Exceeding scalable
- Incredibly versatile
Version Check DJANGO
python3 -m django --version
(or)
django-admin --version
VS Code Extension
- Platformio IDE
- Autocomplete Python (Tabnine AI Assistant)
- Django for VSCode
project --> Applications + configuration files
Single Site --> Application --> books, audio, video pages
Django Project --> Many Django Applications
COMMAND LINE TOOL:
1. django-admin - Run Django project
2. django-admin startproject (foldername) - Create and Start project
3. tree -f - Checking for folder files
4. python3 manage.py runserver - server is running
5. python3 manage.py startapp applicationName - application is created
6. python3 manage.py shell - Open interactiveConsole application
7. python3 manage.py makemigrations - ready to instruction to create model. conversion into db and python. SQL Query Creation Process.
8. python3 manage.py migrate - created a table. SQL Query Execution Process.
9. python3 manage.py sqlmigrate appName 0001 - for checking purpose
10. python3 manage.py createsuperuser - create a django admin page for user
Django Folder Files:
__init__.py
- Blank Python Script Files
- Django will consider the particular folder as python packages
settings.py (Mostly Used)
- Project settings, configuration files, installed applications, database configuration files, middleware configuration etc.,
urls.py (Effectively Used)
- urls patterns will be stored
ex: /home, /aboutus, /contactus
- website consists web pages stored
EXAMPLE for URL PATTERNS: http://example.com/home, http://example.com/aboutus, http://example.com/contactus
wsgi.py (oldest file)
-Web Server Gateway Interface
-This file is used for production movement
-This file is used when we deploy our application in production Server
Three Main Servers
1. DEV Environment Server - Development Environment Server
2. UAT - User Acceptance Test Environment Server (final stage of Development process)
3. Production Environment Server - Production Environment Server
asgi.py (newest file)
-Asynchronous Server Gateway Interface
Synchronous - Full site is load for refresh
Asynchronous - In particular frame will be loaded
ex: Cricket Website (Scorecard only load every balls).This is called Asynchronous loading.
manage.py (most usage files)
-server starting
-running our server
-running Test
-creating migrations
Goto Django Project folder and runserver. click the url http://127.0.0.1:8000
Web server
- Providing environment to run web applicaitons.
- Servers
- HTTPRequest --> Web Components --> HTTPResponse
http://127.0.0.1:8000
127.0.0.1 - IP Address - LocalHost
8000 - Port Number
After Run Server - db.sqlite3 file is created. sqlite3 supported in Django (Default database connection)
Web Application Creation:
python3 manage.py startapp applicationName
- application folder is created and some files are present in the folder.
Web Application folder Files
__init__.py
- Blank Python Script Files
- Django will consider the particular folder as python packages
admin.py
- admin interface --> Django models
apps.py
models.py
- application data models
test.py
- testing functions
views.py
- function based views
- class based views
migrations
- db specific information stored
Step#1 : Create Web App Setting in Project setting.py file
-Goto project folder --> settings.py --> goto "INSTALLED_APPS"
-Add your applicationName('firstapplication')
Step#2 : User settings
-Goto application folder --> views.py
-import HTTPResponse
from django.http import HttpResponse
add request and response messages
def anyName(request):
// block of Code
return HttpResponse()
ex:
def welcome(request):
message = '<h1>Welcome to Our First Project</h1>'
return HttpResponse(message)
Step#3 : Browser URL Setting
-Goto Project Folder --> urls.py file
-import views.py file
from firstapplication import views
-add url path
path('name/', views.functionName)
ex:
path('welcome', views.welcome)
After runserver, goto http://127.0.0.1:8080/welcome, your message was displayed.
Incase port number is changed
python3 manage.py runserver portNumber
ex:
python3 manage.py runserver 8080
----------------------------------------------------------------------------------------------------------------------------------------
In second application was created. views.py update some issue faced
ex: from appName1 import views
from appName2 import views
two views files are same name. it confused to urls.py file in python. so, overcome the problem in two methods like
1. File Name is changed like views1.py, views2.py etc., but large applications doesn't have possible this method.
2. In python have solution, like
from appName1 import views as v1
from appName2 import views as v2
In More number of application in One Project to have more no.of urls are created. So, this urls.py file is not present in project level file. urls.py file is present in application level file will be created in application. It is a good practice and code reusability is achieved.
New Step #3: Create or copy a new file 'urls.py' from project folder to your application folder
- update your urls in urls.py file
Step #4: Goto urls.py file in project folder
- connect to urls in project folders like
from django.conf.urls import include
path('appName/', include(appName.urls))
ex:
path('urlTest/', include('urlTest.urls'))
In Browser url like http://127.0.0.1:8000/appName/url (ex: http://127.0.0.1:8000/urlTest/one)
----------------------------------------------------------------------------------------------------------------------------------------
Model:
View - Business Logics
Template - Presentation layers
VIEW:
Style - CSS (Cascading Style Sheet)
Image/ video /audio /CSS /JavaScript - Static Files
Create a static folder in project folder and upload your static files.
Rendering HTML Files or Create a Template Folder
-create a template folder in project folder
-create a html file in template folder
-connect the html file to views.py in application folder
def home(request):
return render(request, 'index.html')
-goto settings.py in project folder
import os
TEMPLATES Section add the path
'DIRS': [os.path.join(BASE_DIR, 'templates')],
or
BASE_DIR2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR2, 'templates')
-follow above Step 3 and 4
Incase your pass it values from views.py to HTML files
views.py
def home(request):
return render(request, 'index.html',{'Name': 'Arunkumar'})
index.html
<h2>{{Name}}</h2>
Static Folder
- create a static folder --> images folder --> image files
- goto settings.py update the static folder details
ex:
STATIC_DIR = os.path.join(BASE_DIR2, 'static')
- add staticfiles_dir in below static url
ex:
STATICFILES_DIRS = [
STATIC_DIR,
]
- add static syntax and image tag in html file
ex:
{% load static %} -- Above Head Section
<img src="{% static 'folderName/imageFileName.exe' %}" alt="">
ex:
<img src="{% static 'images/imageFile.jpg' %}" alt="demo image">
add external css file:
ex:
<link rel="stylesheet" href="{% static 'css/style.css' %}">
models.py connection into database:
- goto settings.py
- update your database details compulsory 'ENGINE' and 'NAME' in dictionary format for any database
ex: Default db.sqlite3 database in django
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
ex: For PostgreSQL database, first install your machine and then use it.
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "mydatabase",
"USER": "mydatabaseuser",
"PASSWORD": "mypassword",
"HOST": "127.0.0.1",
"PORT": "5432",
}
}
- check the db configuration connection
- open terminal type - python3 manage.py shell
- open interactiveConsole
>>> from django.db import connection
>>> con = connection.cursor()
no error connection is successful.
Use exit() or Ctrl-D in interactiveConsole.
---------------------------------------------------------------------------------------------------------------------------------------
Models.py
Connect django and database using models.py
Layers Link: https://docs.djangoproject.com/en/4.2/
Models Link: https://docs.djangoproject.com/en/4.2/topics/db/models/
Models Class Link: https://docs.djangoproject.com/en/4.2/ref/models/class/
MODEL
* A model is the single, definative source of information about your data.
* It contains essential fields and behavious(methods) of the data you're storing.
* In Generally, each model class pointing to a single database table
* Each model is a python class that subclass of django.db.models.Model
* Each attribute of model is represents a database field (table column heading)
* With all of this, Django gives you can automatically-generated database-access API.
ex:(models.py)
from django.db import models
# Create your models here.
class Employees(models.Model):
empNo = models.IntegerField()
empName = models.CharField(max_length=25)
empRole = models.CharField(max_length=25)
empSalary = models.IntegerField()
--------------------------------------------------------------------------------------------------------------------------------
database ---> views ---> templates
Model ---> Views ---> Templates (MVT) Django Project
Create a model(table) Employees:
Ready to instruction to create model. conversion into db and python. SQL Query Creation Process.
python3 manage.py makemigrations - for single application
python3 manage.py makemigrations applicationName - for one more application
Created a table. SQL Query Execution Process.
python3 manage.py migrate
For checking purpose
python3 manage.py sqlmigrate appName 0001
ex: python3 manage.py sqlmigrate modelsApp 0001
- goto admin.py in application folder
from applicationName.models import ClassName
admin.site.register(ClassName)
ex:
from modelsApp.models import Employees
# Register your models here.
admin.site.register(Employees)
Table was created successfully.
Create a Superuser in django-admin:
python3 manage.py createsuperuser
Create your username and password.
MVT Process:
models.py --> views.py --> index.html
- Goto models.py
- Create a function like
def __str__(self):
return 'message' + fieldName
ex:
def __str__(self):
return 'Employees details are showed. Employee Name :' + empName
- Goto admin.py
(admin.py can't handle directly in sql. But admin.py to inform sql information. So class is handle sql to import the admin.py)
- Create a class like
from modelsApp.models import Employees
class EmployeesAdmin(admin,ModelAdmin):
employeesDetails = ['empNo', 'empName', 'empRole', 'empSalary']
admin.site.register(Employees, EmployeesAdmin)
- Goto views.py
- import first models.py file
from modelsApp.models import Employees
def models(request):
emp_data = Employee.objects.all() # To get all data for the employee model
emp_dict = {'emp_list':emp_data} # To create a dictionary in above data for sharing to html file
return render(request,'modelsApp/index.html', context=emp_dict) # context= dictionary datatype format send into html
- Goto index.html
- To render the employee model in the index.html
- using jinja template syntax
------------------------------------------------------------------------------------------------------------------------------------------------
Django Templates:
- Code Readability
- Code reusability
html file - Template - Rendering
-print(__file__) # to print filename or file path with file name
#os module
import os
#print(os.path.abspath(__file__)) # absolute path
#dirname()
print(os.path.dirname(os.path.abspath(__file__))) #directory location
separate folder for template
render the template files in views.py file in application folder
update the project urls.py file
--------------------------------------------------------------------------------------------------------------------------------
Django Forms
Django Forms are Secured.
Automated Validation.
forms.Form --> modules
- Create a App -> create file "forms.py" in application folder
- update views.py file
After update the urls.py file in project folder
CSRF protection
Cross Site Request Forgery
Django will raise a Forbidden (403) error, protecting the application from CSRF attacks.
Include "csrf token" in form inside
{% csrf_token %}
example:
<form method="post" action="/your_form_action/">
{% csrf_token %}
<!--Extra Input Tags-->
<input type="submit" value="Submit">
</form>
------------------------------------------------------------------------------------------------------------------------------------
Session Management:
Client <------------------> Server
Data Transfer
Protocol:
http
Stateless Protocol:
- it is a communication protocol in which no session information is retained by the receiver, usually a server.
Session Management: (Time Period)
- cookies
- session API (for django)
request
Client <------------------------> Server
response + cookies
cookie object: store client
- Temporary cookie
- Persistent cookie
Cookies Drawback:
- No Security
- Less information store, only string value - other datatypes are not supported
- Maximum count of cookies decided to Browser
Overcome this problem, for django
SESSION ID MAINTAINED
How to use session?
- The session framework let you store and retrieve arbitrary data on a per-site-visitor basis.
- It stores data on the server side and abstract sending and receiving of cookies.
- Cookies contains a SESSION ID - not the data itself.
- it stores database in session management information
request
Client <------------------------> Server
response + session id
Benefits of Session Id:
- both client and server side should be maintained session id.
----------------------------------------------------------------------------------------------------------------------------------------------------
CRUD OPERATION:
Create - Insert the Data
Retrieve - Retrieve the Data from database to template
Update - Edit the Data
Delete - Delete the Data
In Python CRUD Approach have two types. There are
- Function based views
- Class based views
Important Two Classes:
-models
-forms (forms.ModelForm)
* models - create a sub class of the model
* forms - create a sub class of the ModalForm
Faker Model in Python - To generated a fake data in Python
pip install Faker
- create a python file in project folder.
- copy the data for faker.py file and paste it your python file
- change the projectName.settings
- change variables for your project data
- run the python file separately
- After run the server and ,check the data from admin dashboard
Template Tags:
{% block content%}{% endblock %}
- block is used for overriding specific parts of a template
- In your case, you have a block name "content" and this is supposed to be overridden by children that inherit
from this template.
- Template to be extended, named base.html
Meta Data - Data about Data (Information)
Flow of DataBase Connection:
1. Create a django project
2. cd to the project folderName
3. App Creation
4. Create a Folder in Project level
Templates
Application Name
.html files
5. Update "settings.py" file
6. Connect DB to "models.py" file
7. makemigrations
8. migrate (Table created)
9. update "admin.py" file
10. createsuperuser
11. runserver
12. 127.0.0.1:8000/ into web Browser
Optional: Data generated
1. Create a "generate.py" file
2. using "Faker Module" import your "generate.py" file
13. create "forms.py" and get to inputs to "views.py"
Delete Data and Update Data using Primary key or Id is Important
Update operation to be initiated to instance in old object change the value
Class Based Views:
- create a project and applicaiton
- update "settings.py"
- goto "views.py"
- write a class
- create a class view (Views inbuilt class)
from django.views.generic import View
- Create a Class using instance
- instance is compulsory self constructor
- update urls.py and run server
views.ClaseName.as_view() ---> Class to function views
Small application used to this class based views (views write class not function)
Class Based View (TemplateView class) using Templates.
Template_name is important.
-------------------------------------------- END -----------------------------------------------------------------