-
Notifications
You must be signed in to change notification settings - Fork 0
/
Notes.txt
910 lines (667 loc) · 33.8 KB
/
Notes.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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
Framework :
1. It is set of conceptual structure and guidelines that can be used to build something useful
2. It may include predefined classes and functions that process input, manage hardware services and interact with system.
3. Purpose of framework is to focus on building unique logic of the project rather than writing code from scratch
why to use framework :
1. Collection of tools
2. No need to start from scratch
3. Code reusability
4. Testing
5. Debugging
==========================================================================================
Web Framework :
1. It is used to build web applications.
2. It provides tools and libraries to simplify comman web applications operations. This may include web services, API's, etc.
3. It helps with variety of tasks,from templating, database access to session management and code reuse.
==========================================================================================
Model View Template (MVT) :
1. It is design pattern that separates an application into three main logical components
Model, View and Template.
2. Each components has their own role in project.
Model :
It is responsible to handle database. It is data access layer which handles the data.
View :
1. The user can send the request by interacting with template, the view handles these requests and send it to Model than get appropriate response from Model, sends the response to template.
2. It may also have required logic.
3. It work as mediator between Model and Template.
Template :
1. It represents how the data should be presented to application user. User can read or write the data from template.
2. Basically, it is responsible for showing end user content, or we can say user interface.
3. It consists of HTML, CSS and JS mixed with Django Template Language.
Working of MVT :
1. user sends the request which further hit to urls which is routed to one of the view.
2. view gets executed if request required data from database then view sends request to Model further model interacts with database and get appropriate response from database.
3. Once model gets response (required data) from database than model sends response to view.
4. View will execute all logical part written inside it than to represent it, It will render the template further template will be presented to user.
==========================================================================================
Django :
1. It is free open source python based high-level web framework.
2. It follows MVT architectural design pattern.
3. It is maintain by Django Software Foundation
What we can build using Django :
1. High end web application
2. It encourages rapid development and clean, pragmatic design.
Applications build using django :
Youtube
Instagram
Bitbucket
NASA
Spotify
Advantages of django :
1. Open Source
2. Secure
3. Fast
4. Scalable
5. Provides authentication
6. Provides web development server by default
7. Provides SQLite database by default
==========================================================================================
Django Project:
1. It may contain multiple project applications which means a group of applications and files are called as django project.
2. An application is part of django project
for example :
SchoolProject
- Registration App
- Fees App
- Exam App
- Attendance App
- Result App
To create a project:
django-admin startproject projectname
==========================================================================================
Django Project Directory Structure :
schoolproject --> outer folder/ root directory
- schoolproject --> inner project folder
- __pycache__ --> this folder contain all cache files
- __init__.py
- asgi.py
- settings.py
- urls.py
- wsgi.py
- db.sqlite3 --> database file
- manage.py
__init__.py :
The folder which contains __init__.py file is considered as python package
wsgi.py :
1. Web server gateway interface work as interface for web server and web application.
2. It provides standard synchronous python apps.
3. When wsgi server loads your application, django needs to import the settings module that's where your entire application is defined.
4. Django use the DJANGO_SETTINGS_MODULE environment variable to locate the appropriate settings module.
5. We can use different value for development and production.
6. If variable isn't set, the default wsgi.py sets it projectname.settings that's how runserver discovers the default settings file.
asgi.py :
1. Asynchronous server gateway interface is successor of wsgi.
2. It work as interface for web server and web application.
3. It provides standard for both asynchronous and synchronous python apps.
settings.py :
This file contains all information and data about project settings.
example : database configuration, templates, installed application, validators, etc
urls.py :
This file contains all information of url attached with applications.
manage.py :
1. It is automatically created in each django project.
2. It is django command line utility and also set DJANGO_SETTINGS_MODULE environment variable so that it points to your project's settings.py file.
3. when working with single django project it is easier to use manage.py than django-admin.
==========================================================================================
How to create application and installed in project :
1. Change directory to root directory : cd schoolproject
2. Create application : python manage.py startapp appname
3. Add/Install application in settings.py file :
- open settings.py file
- add appname below in-built apps in INSTALLED_APPS list
- save settings.py file
==========================================================================================
Application Directory Structure :
course
- migrations
- __init__.py
- __init__.py
- admin.py
- apps.py
- models.py
- tests.py
- views.py
migrations :
This folder contains __init__.py file which means it's python package.
It also contains all files which are created after we run makemigration command
__init__.py :
The folder contains __init__.py file is considered as python package
admin.py :
This file is used to register models (sql tables) so we could perform CRUD operations from Admin application.
Admin application is provided by Django to perform CRUD operations.
apps.py :
This file is used for app configuration.
models.py :
This file is used to create our own model classes later these classes will be converted to database tables by Django for our application.
tests.py :
This file is used to create tests.
views.py :
This file is used to create view. we write all business logic code in the file.
==========================================================================================
urls.py :
It is used to define url pattern for view functions of applications.
path() function:
path(route/url,view,kwargs=None,name=None)
route :
the route argument should be string that contains a url pattern.
view :
the view argument is view function or it can be django.urls.include()
kwargs :
It allows to pass additional arguments to view function. It should be dictionary.
name :
the name argument is used for url reversing.
==========================================================================================
How to write view function and map them to urlpattern :
1. Create project : django-admin startproject projectname
2. Go to root directory : cd projectname
3. Create application : python manage.py startapp appname
4. Add/Install application inside INSTALLED_APPS in project's settings.py file.
5. Write view functions inside views.py file (app dictionary)
6. Define url for view function of application :
- open urls.py (inner project directory)
- import views module of application
- write url pattern
- save urls.py file
==========================================================================================
How to write view function in multiple application and map them to project urlpattern :
1. Create project : django-admin startproject projectname
2. Go to root directory : cd projectname
3. Create application1 : python manage.py startapp appname1
4. Create application2 : python manage.py startapp appname2
5. Add/Install applications inside INSTALLED_APPS in project's settings.py file.
6. Write view functions inside views.py file (app dictionary)
7. Define url for view function of application
NOTE :
drawback of mapping application url in project urls.py :
1. Multiple urls will be mapped inside one project urls.py which will be difficult to handle n number of urls in one place.
2. Need to manage imports of application view function
3. Problem of application reusability
==========================================================================================
How to create templates folder and template files :
1. Create project : django-admin startproject projectname
2. Go to root directory : cd projectname
3. Create application1 : python manage.py startapp appname1
4. Create application2 : python manage.py startapp appname2
5. Add/Install applications inside INSTALLED_APPS in project's settings.py file.
6. Create templates folder inside root dictionary
7. Create TEMPLATES_DIR variable inside settings.py and assign (BASE_DIR / 'templates') value in it.
8. Write view functions inside views.py file (app dictionary)
- use render() function to send HttpResponse object
- syntax : render(request,template_name,context,content_type,status,using)
9. Define url for view function of application
10. Create template files inside templates folder and write html code for representation.
==========================================================================================
How to create templates folder and render template files in each separate sub directory:
1. Create project : django-admin startproject projectname
2. Go to root directory : cd projectname
3. Create application1 : python manage.py startapp appname1
4. Create application2 : python manage.py startapp appname2
5. Add/Install applications inside INSTALLED_APPS in project's settings.py file.
6. Create templates folder inside root dictionary
7. Create separate sub folders for each application inside templates folder.
8. Create TEMPLATES_DIR variable inside settings.py and assign (BASE_DIR / 'templates') value in it.
9. Write view functions inside views.py file (app directory)
- use render() function to send HttpResponse object
- syntax : render(request,path/template_name,context,content_type,status,using)
10. Define url for view function of application
11. Create template files inside templates folder and write html code for representation.
==========================================================================================
Filters in Django Template Language :
When we need to modify a variable before displaying we can use filters.
Pipe '|' is used to apply filter.
syntax : {{ variable | filter }}
ex : {{ name | upper }}
Some of filters takes arguments :
syntax : {{ variable | filter : argument }}
ex : {{ article | truncateword : 40 }}
Filters can be chained :
syntax : {{ variable | filter | filter }}
ex : {{ article | upper | truncateword : 40 }}
capfirst :
It capitalizes the first character of the value. If the first character is not a letter, this filter has no effect.
syntax : {{ value | capfirst }}
default :
If value evaluates to false then it will show default value otherwise uses the value.
syntax : {{ value | default : 'nothing' }}
if string is empty for that also it will show default value
length :
It returns length of value. it works for both strings and lists. it returns 0 for underfined variable.
syntax : {{ value | length }}
lower :
it will change all value to lowercase
syntax : {{ value | lower }}
==========================================================================================
Date & Time :
prefined formats :
DATE_FORMAT : Feb 9, 2023
DATETIME_FORMAT : Feb 9, 2023, 10 p.m.
SHORT_DATE_FORMAT : 02/09/2023
SHORT_DATETIME_FORMAT : 02/09/2023 10 p.m.
TIME_FORMAT : "01:24"
syntax : {{ value | date:'SHORT_DATE_FORMAT' }}
syntax : {{ value | time:'TIME_FORMAT' }}
==========================================================================================
Dot lookup :
Technically, when the template system encounters a dot, it tries the following lookups in the order.
- dictionary lookup
- attribute/method lookup
- numeric index lookup
==========================================================================================
Conditional Statements :
<h1>Example 1 : if </h1>
{% if name %}
<h2>Hello {{ name }}</h2>
{% endif %}
<h1>Example 2 : and </h1>
{% if name and seats %}
<h2>{{seats}} seats are available for course {{name}}</h2>
{% endif %}
<h1>Example 3 : or </h1>
{% if name or seats %}
<h2>{{seats}} seats are available for course {{name}}</h2>
{% endif %}
<h1>Example 4 : '==' </h1>
{% if name == 'Django' %}
<h2>{{seats}} seats are available for course {{name}}</h2>
{% endif %}
<h1>Example 5 : '!=' </h1>
{% if name != 'django' %}
<h2>{{seats}} seats are available for course {{name}}</h2>
{% endif %}
<h1>Example 6 : '>' </h1>
{% if seats > 10 %}
<h2>{{seats}} seats are available for course {{name}}</h2>
{% endif %}
<h1>Example 7 : '<' </h1>
{% if seats < 1 %}
<h2>{{seats}} seats are available for course {{name}}</h2>
{% endif %}
<h1>Example 8 : '>=' </h1>
{% if seats >= 20 %}
<h2>{{seats}} seats are available for course {{name}}</h2>
{% endif %}
<h1>Example 9 : '<=' </h1>
{% if seats <= 20 %}
<h2>{{seats}} seats are available for course {{name}}</h2>
{% endif %}
<h1>Example 10 : 'not' </h1>
{% if not check %}
<h2>{{seats}} seats are available for course {{name}}</h2>
{% endif %}
<h1>Example 11 : 'in' </h1>
{% if 'g' in name %}
<h2>{{seats}} seats are available for course {{name}}</h2>
{% endif %}
==========================================================================================
Control Statements :
<h1>Example 1 : </h1>
{% for name in names %}
{{ name }}
{% endfor %}
<h1>Example 2 : Reverse </h1>
{% for name in names reversed %}
{{ name }}
{% endfor %}
<h1>Example 3 : ul tag </h1>
<ul>
{% for name in names %}
<li>{{ name }}</li>
{% endfor %}
</ul>
<h1>Example 4 : empty tag </h1>
<ul>
{% for name in namei %}
<li>{{ name }}</li>
{% empty %}
<h3>List is empty...</h3>
{% endfor %}
</ul>
<h1>Example 5 : forloop.counter </h1>
{% for name in names %}
{{ forloop.counter }} - {{ name }} <br>
{% endfor %}
<h1>Example 6 : forloop.counter0 </h1>
{% for name in names %}
{{ forloop.counter0 }} - {{ name }} <br>
{% endfor %}
<h1>Example 7 : forloop.revcounter0 </h1>
{% for name in names %}
{{ forloop.revcounter0 }} - {{ name }} <br>
{% endfor %}
<h1>Example 8 : forloop.revcounter </h1>
{% for name in names %}
{{ forloop.revcounter }} - {{ name }} <br>
{% endfor %}
<h1>Example 9 : forloop.first </h1>
{% for name in names %}
{{ forloop.first }} - {{ name }} <br>
{% endfor %}
<h1>Example 10 : forloop.last </h1>
{% for name in names %}
{{ forloop.last }} - {{ name }} <br>
{% endfor %}
<h1>Example 11 : how to access nested dictionary </h1>
<h2>{{ nested_students }}</h2>
<h2>{{ nested_students.st1 }}</h2>
<h2>{{ nested_students.st2 }}</h2>
<h2>{{ nested_students.st3 }}</h2>
<h2>{{ nested_students.st4 }}</h2>
<h2>{{ nested_students.st1.name }}</h2>
<h2>{{ nested_students.st1.age }}</h2>
<h2>{{ nested_students.st2.name }}</h2>
<h2>{{ nested_students.st2.age }}</h2>
<h2>{{ nested_students.st3.name }}</h2>
<h2>{{ nested_students.st3.age }}</h2>
<h2>{{ nested_students.st4.name }}</h2>
<h2>{{ nested_students.st4.age }}</h2>
<h1>Example 12 : nested forloop </h1>
{% for key, value in nested_students.items %}
{% for key, value in value.items %}
<h2>{{ forloop.parentloop.counter}} - {{ key | capfirst }} : {{ value }}</h2>
{% endfor %}
<hr>
{% endfor %}
==========================================================================================
How to create templates inside application :
1. Create project : django-admin startproject projectname
2. Go to root directory : cd projectname
3. Create application1 : python manage.py startapp appname1
4. Create application2 : python manage.py startapp appname2
5. Add/Install applications inside INSTALLED_APPS in project's settings.py file.
6. Create templates folder inside each application directory.
7. Check 'APP_DIRS' : True in settings.py.
8. Create appname_folder inside appname/templates directory for template files.
9. Create template files inside appname/templates/appname_folder.
10. Write view functions inside views.py file (app dictionary)
11. Define url for view function of application
12. Write template files html code for representation.
==========================================================================================
Static Files in Django :
1. CSS files, JS files, Images, Videos etc are considered as static files in django.
2. Django provides django.contrib.staticfiles to help you manage them.
3. django.contrib.staticfiles collects static files from each applications ( and any other places you specify ) into one single location that can be served in production.
==========================================================================================
How to create static folder and files :
We create static folder inside root directory folder then inside static folder we create required folders which will contains all static files respectively like css folder will contain all css files , images folder will contains all images and so on.
- root directory
- application directory
- static folder
- css folder
- style.css
- images folder
- img1.png
- img2.png
- manage.py
==========================================================================================
Add static folder path in settings.py :
STATIC_DIR = BASE_DIR / 'static'
STATICFILES_DIRS = [STATIC_DIR]
==========================================================================================
Load static files :
{% load static %} --> it is used to load custom template tags
{% static 'css/style.css' %} --> it is used to reference the static files
==========================================================================================
STATIC_URL :
This is the URL to use when referring to static file located in STATIC_ROOT. It must end in slash if set to non-empty value.
ex : '/static/'
STATIC_ROOT :
This is absolute path to the directory where collectstatic will collect static files for deployment. It is by default None.
ex : 'BASE / 'static/''
STATICFILES_DIRS :
This setting defines the additional locations the staticfiles app will traverse if FileSystemFinder finder is enabled.
ex : if you use the collectstatic or findstatic management command or use static file serving view. It is by default empty.
STATICFILES_DIRS = [
'static1',
'static2',
static3,
]
STATICFILES_STORAGE :
The file storage engine to use when collecting static files with collectstatic management command.
default : 'django.contrib.staticfiles.storage.StaticFilesStorage'
==========================================================================================
How to create static folder and files inside root directory :
1. Create project : django-admin startproject projectname
2. Go to root directory : cd projectname
3. Create application1 : python manage.py startapp appname1
4. Create application2 : python manage.py startapp appname2
5. Add/Install applications inside INSTALLED_APPS in project's settings.py file.
6. Create templates folder inside each application directory and root directory.
7. Check 'APP_DIRS' : True in settings.py.
8. Create TEMPLATES_DIR variable inside settings.py and assign (BASE_DIR / 'templates') value in it and paste it in TEMPLATES = [].
9. Create appname_folder inside appname/templates directory for template files.
10. Create template files inside appname/templates/appname_folder.
11. Add STATIC_DIR = BASE_DIR / 'static' & STATICFILES_DIRS = [STATIC_DIR,] inside setting.py.
12. Create static folder inside root directory.
13. Create css,js, images ,videos folder inside static folder.
14. Create static files inside respective static folders.
15. Write view functions inside views.py file (app dictionary)
16. Define url for view function of application
17. Write template files html code for representation.
==========================================================================================
How to create static folder and files inside application directory :
1. Create project : django-admin startproject projectname
2. Go to root directory : cd projectname
3. Create application1 : python manage.py startapp appname1
4. Create application2 : python manage.py startapp appname2
5. Add/Install applications inside INSTALLED_APPS in project's settings.py file.
6. Create templates folder inside each application directory and root directory.
7. Check 'APP_DIRS' : True in settings.py.
8. Create TEMPLATES_DIR variable inside settings.py and assign (BASE_DIR / 'templates') value in it and paste it in TEMPLATES = [].
9. Create appname_folder inside appname/templates directory for template files.
10. Create template files inside appname/templates/appname_folder.
11. Create static folder inside each application directory.
12. Create appname_folder inside appname/static directory for static files.
12. Create css,js, images ,videos folder inside appname/static/appname_folder directory.
13. Create static files inside respective appname/static/appname_folder directory.
14. Write view functions inside views.py file (app dictionary)
15. Define url for view function of application
16. Write template files html code for representation.
==========================================================================================
How to create static folder and files inside project & application directory :
1. Create project : django-admin startproject projectname
2. Go to root directory : cd projectname
3. Create application1 : python manage.py startapp appname1
4. Create application2 : python manage.py startapp appname2
5. Add/Install applications inside INSTALLED_APPS in project's settings.py file.
6. Create templates folder inside each application directory and root directory.
7. Check 'APP_DIRS' : True in settings.py.
8. Create TEMPLATES_DIR variable inside settings.py and assign (BASE_DIR / 'templates') value in it and paste it in TEMPLATES = [].
9. Create appname_folder inside appname/templates directory for template files.
10. Create template files inside appname/templates/appname_folder.
11. Add STATIC_DIR = BASE_DIR / 'static' & STATICFILES_DIRS = [STATIC_DIR,] inside setting.py.
12. Create static folder inside each application directory.
13. Create appname_folder inside appname/static directory for static files.
14. Create css,js, images ,videos folder inside appname/static/appname_folder directory.
15. Create static files inside respective appname/static/appname_folder directory.
16. Create static folder inside root directory.
17. Create css,js, images ,videos folder inside static folder.
18. Create static files inside respective static folders.
19. Write view functions inside views.py file (app dictionary)
20. Define url for view function of application
21. Write template files html code for representation.
==========================================================================================
Template Inheritance :
1. It allows you to build base skeleton template that contains all the comman elements of your site and defines blocks that child templates can override.
2. the extends tag is used to inherit the template.
3. extends tag tells the template engine that this template "extends" another template.
4. When the template engine evaluates this template, first it locates the parent's template.
5. You can use as many levels of Inheritance.
extends tag :
It is used to inherit the template.
syntax :
{% extends 'parent_template' %}
{% extends variable %}
block tag :
It is used to override the content of block tag.
syntax :
{% block blockname %}...{% endblock %}
{% block blockname %}...{% endblock blockname %} -- (recommended)
{{ block.super }} -> used to get content of parent template
==========================================================================================
url tag :
The {% url 'name' %} template tag to generate URLs for views.
This tag takes the view name as an argument and returns the URL associated with that view.
NOTE : we define name where our view function is mapped (incase of any include in path)
syntax :
{% url 'name' %}
{% url 'name' as variable %}
{% url '{{variable}}' %}
==========================================================================================
include tag :
1. The {% include %} tag is used to include the contents of another template within the current template.
2. This allows you to reuse code and build modular templates.
syntax :
{% include variable %}
{% include 'folder/template_name.html' %}
Difference between include & extends :
{% include %} is used for reusing the content of one template in another, while {% extends %} is used for creating a template hierarchy where one template serves as a base, and other templates can extend and override its blocks.
NOTE : We can use context in included template which is passed by view function to rendering template or which can pass variables to included template using with keyword.
syntax :
{% include 'folder/template_name.html' with p='Python' %}
If we don't want to included template to access variable passed by view function we can use only keyword.
syntax :
{% include 'folder/template_name.html' with p='Python' only %}
==========================================================================================
Object Relational Mapper (ORM) :
1. It helps application to interact with database such as SQLite, MySql, PostgreSQL & Oracle.
2. It automatically create a database schema from defined classes and models. It generate SQL from python code for particular database which means developer do not need to write SQL code.
3. It maps object attributes to respective table fields.
4. It is easier to change the database if we use ORM hence project becomes more portable.
5. It is just a way to create SQL to query and manipulate your database and get results in a pythonic fashion.
6. ORMs use connectors to connect databases with web application.
==========================================================================================
QuerySet :
It can be defined as a list containing all those objects we have created using the Django model.
It allows you to read the data from database, filter and order it.
==========================================================================================
Model Class :
1. It is class which will represent a table in database.
2. Each model is a python class that subclasses django.db.models.Model
3. Each attribute of the model represents a database field.
4. With all of this, django gives you an automatically generated database access API.
5. Django provides built-in database by default which is sqlite database.
6. We can use other databases like MySql, Oracle, etc.
Create Our Own Model Class :
1. models.py file which is inside application folder, is required to create our own model class.
2. Our own model class will inherit with Django's model class.
syntax :
class ClassName(models.Model):
field_name = models.FieldType(args,options)
Example :
class Student(models.Model):
stuid = models.IntegerField()
stuname = models.CharField(max_length=70) --> max_length parameter is required in CharField
stuemail = models.EmailField(max_length=70)
stupass = models.CharField(max_length=70)
1. This class will create table with columns and their data types
2. Table Name will be ApplicationName_ClassName.
3. FieldName will become table's column name
NOTE : As we have not mentioned primary key in any of the these columns so it will automatically create new column named "id" with data type Integer with primary key and auto increment.
==========================================================================================
Migrations :
It is way of propogating changes you make to your models (adding, deleting or updating) into a database schema.
commands:
makemigrations - This is responsible for creating new migrations based on the changes you have made to your models.
-- syntax : python manage.py makemigrations
migrate - This is responsible for applying and unapplying the migrations.
-- syntax : python manage.py migrate
sqlmigrate - This will display the SQL statements for a migration.
-- syntax : python manage.py sqlmigrate application_name migrationfile_name
showmigrations - This will lists the project's migrations and their status.
-- syntax : python manage.py showmigrations
==========================================================================================
Admin Application :
1. It is built-in application provided by Django.
2. This application provides admin interface for CRUD operations without writing the sql statements.
3. We need to create super user to login admin application.
To create super user :
syntax : python manage.py createsuperuser
==========================================================================================
How to register model in django :
1. Open admin.py file inside application folder
2. import model from models.py file
3. write "admin.site.register(ModelName)"
NOTE : To perform CRUD operations on our own model or table in admin interface we need to register the model
__str__() method :
This method is called whenever we call str() on the object.
==========================================================================================
Model Admin Class :
Need : It used for displaying all table data in admin interface
It is representation of a model in admin interface.
To show all data of table in admin interface we have to create an ModelAdmin class in admin.py file of application folder.
syntax :
Creating ModelAdmin Class :
class ModelAdminClassName(admin.ModelAdmin):
list_display = ('field_name1', 'field_name2',..) --> we can use list too instead of tuple
Register the above class :
admin.site.register(ModelName, ModelAdminClassName)
-----------------------------------------------------------------------------------------
list_display :
It is used to display multiple fields in admin interface of tables if it is not set then by default __str__() representation of each object will be displayed.
There are four types of values that can be displayed in list_display :
1. The name of model field
2. A callable that accepts one argument, model instance
3. A string representing a ModelAdmin method that accepts one argument, model instance
4. A string representing a model attribute or method (without any required argument)
How to register Model using decorator :
@admin.register(ModelName)
class ModelAdminClassName(admin.ModelAdmin):
list_display = ('field_name1', 'field_name2',..)
==========================================================================================
Django Form :
It can simplify and automate the vast portion of work like data prepared for display in a form, rendered as HTML, edit using convenient interface, validating and cleaned up etc.
Django handles three distinct parts of the work involved in forms :
1. preparing and restructuring data to make it ready for rendering
2. creating HTML forms for data
3. receiving and processing submitted forms and data from the client.
Creating Django form using form class :
1. create forms.py file inside application folder
2. form django import forms
3. create class for form :
syntax :
class FormClassName(forms.Form):
label = forms.FieldType()
label = forms.FieldType(label='display')
Display the form object in template :
1. create form object in views.py
- from .forms import FormClassName
- def showobject(request):
form = FormClassName()
return render(request, 'template_name', {'form' : form})
2. Access dict key in template
- <html>{{form}}</html>
Form rendering options :
1. {{form}} -- it will render them all
2. {{form.as_table}} -- it will render them as table cells wrapped inside <tr> tags
3. {{form.as_p}} -- it will render them as table cells wrapped inside <p> tags
4. {{form.as_ul}} -- it will render them as table cells wrapped inside <li> tags
5. {{form.name_of_field}} -- it will render field manually as given
Configure id attribute :
1. we can change id attribute using auto_id parameter
2. we need to pass auto_id parameter in constructor
2. There are 4 ways to change id attribute :
- auto_id='some_%s' (this will change id and label value to given value)
- auto_id=True (this will change id and label value to field name)
- auto_id=False (this will change remove id and label tag)
- auto_id='geeky' (this will act as same as True one)
Display label_suffix :
we can change label suffix by passing label_suffix parameter to constructor
syntax : label_suffix='-'
Configure initial value of field :
we can set initial value of each field at runtime by passing initial={'field' : value } in constructor
Rearranging the order of form field :
we use order_fields method to rearrange the form field.
syntax :
form = StudentRegistration()
form.order_fields(field_order=['field1','field2',..]) NOTE : by default field_order is None
==========================================================================================
Render Form Fields Manually in Django :
1. {{form.field_name.id_for_label}} -- it is used for fetching for value in label tag
2. {{form.field_name}} -- it is used for placing input tag for mentioned field
3. {{form.field_name.label_tag}} -- it is used for placing entire label tag
4. {{form.field_name.label}} -- it is used for fetching label value
5. {{form.field_name.value}} -- it is used for fetching initial value of field
6. {{form.field_name.html_name}} -- it is used for fetching name value of input tag
7. {{form.field_name.help_text}} -- it is used for fetching help text of field
8. {{form.field_name.field.attribute}} -- it is used for fetching value of mentioned attribute of field
==========================================================================================