-
Notifications
You must be signed in to change notification settings - Fork 0
/
A Complete Beginner's Guide to Django - Part 3.html
2715 lines (2112 loc) · 210 KB
/
A Complete Beginner's Guide to Django - Part 3.html
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<!-- saved from url=(0104)https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="ir-site-verification-token" value="-233745807">
<title>A Complete Beginner's Guide to Django - Part 3</title>
<meta name="description" content="In this tutorial we are going to dive deep into two fundamental concepts, URLs and Forms. In the process we are going to explore many other concepts like cre...">
<link href="./A Complete Beginner's Guide to Django - Part 3_files/css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="./A Complete Beginner's Guide to Django - Part 3_files/main.css">
<link rel="stylesheet" href="./A Complete Beginner's Guide to Django - Part 3_files/font-awesome.min.css">
<link rel="canonical" href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html">
<link rel="alternate" type="application/rss+xml" title="Simple is Better Than Complex" href="https://simpleisbetterthancomplex.com/feed.xml">
<link rel="icon" type="image/png" href="https://simpleisbetterthancomplex.com/favicon.png">
<link rel="mask-icon" href="https://simpleisbetterthancomplex.com/safari-pinned-tab.svg" color="#5bbad5">
<script async="" src="./A Complete Beginner's Guide to Django - Part 3_files/fbevents.js"></script><script async="" src="./A Complete Beginner's Guide to Django - Part 3_files/analytics.js"></script><script src="./A Complete Beginner's Guide to Django - Part 3_files/jquery.min.js"></script>
<script src="./A Complete Beginner's Guide to Django - Part 3_files/site.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-42049022-10', 'auto');
ga('send', 'pageview');
</script>
<script>
$(function () {
$("#ad").on("click", "#carbonads .carbon-wrap a", function () {
var page_id = '/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html';
ga('send', 'event', 'carbonads', 'click', page_id, {
'transport': 'beacon'
});
});
});
</script>
<script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
document,'script','https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '1689711451348257');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none" alt="PageView"
src="https://www.facebook.com/tr?id=1689711451348257&ev=PageView&noscript=1"
/></noscript>
<script data-ad-client="ca-pub-5430683801108011" async="" src="./A Complete Beginner's Guide to Django - Part 3_files/f.txt"></script>
<meta property="og:title" content="A Complete Beginner's Guide to Django - Part 3">
<meta property="og:url" content="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html">
<meta property="og:image" content="https://simpleisbetterthancomplex.com/media/series/beginners-guide/1.11/part-3/thumbnail.jpg">
<meta property="og:description" content="In this tutorial we are going to dive deep into two fundamental concepts, URLs and Forms. In the process we are going to explore many other concepts like cre...">
<meta property="og:site_name" content="Simple is Better Than Complex">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2017-09-18T08:00:00+03:00">
<meta property="article:author" content="https://facebook.com/vitorfs">
<meta property="fb:admins" content="100000024295617">
<meta property="fb:app_id" content="1645747765697865">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="vitorfs">
<meta name="twitter:creator" content="vitorfs">
<meta name="twitter:title" content="A Complete Beginner's Guide to Django - Part 3">
<meta name="twitter:description" content="In this tutorial we are going to dive deep into two fundamental concepts, URLs and Forms. In the process we are going to explore many other concepts like creating reusable templates and installing ...">
<meta name="twitter:image" content="https://simpleisbetterthancomplex.com/media/series/beginners-guide/1.11/part-3/thumbnail.jpg">
<meta name="p:domain_verify" content="e262845cb18e4c68b0cff535a0eaea5d">
<meta property="og:type" content="article">
<meta property="article:tag" content="python">
<meta property="article:tag" content="django">
<meta property="article:tag" content="guide">
<meta property="article:tag" content="beginners">
<meta property="article:tag" content="urls">
<meta property="article:tag" content="forms">
<meta property="article:tag" content="templates">
<script id="_carbonads_projs" type="text/javascript" src="https://srv.carbonads.net/ads/CKYIEKQM.json?segment=placement:simpleisbetterthancomplexcom&callback=_carbonads_go"></script><script src="./A Complete Beginner's Guide to Django - Part 3_files/embed.js" data-timestamp="1625248278365"></script><style type="text/css">@media (min-width: 1200px) {#seriesSideBar.affix div.card { max-height: 679px!important; }}</style></head>
<body class="platform-linux" data-new-gr-c-s-check-loaded="14.1018.0" data-gr-ext-installed="">
<div id="top" style="visibility: hidden"></div>
<header class="nav-down">
<div class="container">
<ul class="menu menu-right">
<li class="menu-item">
<a href="https://simpleisbetterthancomplex.com/search/">
<span class="fa fa-search"></span>
</a>
</li>
<li class="toggle-menu">
<a href="javascript:void(0);">
<span class="fa fa-bars"></span>
</a>
</li>
</ul>
<ul class="menu menu-left">
<li class="logo">
<a href="https://simpleisbetterthancomplex.com/" style="font-weight: 900">simple<span class="brand">is</span>better<span class="brand">than</span>complex</a>
</li>
<li class="menu-item">
<a href="https://simpleisbetterthancomplex.com/">
<span class="fa fa-home" style="margin-right: 3px"></span>
Home
</a>
</li>
<!--li class="menu-item">
<a href="/ask/">
<span class="fa fa-bullhorn" style="margin-right: 3px"></span>
Ask a Question
</a>
</li-->
<li class="menu-item">
<a href="https://simpleisbetterthancomplex.com/archive/">
<span class="fa fa-archive" style="margin-right: 3px"></span>
Articles
</a>
</li>
<li class="menu-item">
<a href="https://simpleisbetterthancomplex.com/videos/">
<span class="fa fa-video-camera" style="margin-right: 3px"></span>
Videos
</a>
</li>
<li class="menu-item">
<a href="https://community.simpleisbetterthancomplex.com/">
<span class="fa fa-comments" style="margin-right: 3px"></span>
Community
</a>
</li>
<!--li class="menu-item">
<a href="/contact/">
<span class="fa fa-envelope" style="margin-right: 3px"></span>
Contact
</a>
</li-->
<li class="menu-item">
<a href="https://simpleisbetterthancomplex.com/series/">
<span class="fa fa-book" style="margin-right: 3px"></span>
Series
</a>
</li>
<li class="menu-item">
<a href="https://simpleisbetterthancomplex.com/snippets/">
<span class="fa fa-code" style="margin-right: 3px"></span>
Snippets
</a>
</li>
<li class="menu-item">
<a href="https://simpleisbetterthancomplex.com/sponsor/">
<span class="fa fa-bullhorn" style="margin-right: 3px"></span>
Sponsor
</a>
</li>
<li class="menu-item">
<a href="https://simpleisbetterthancomplex.com/feed.xml" target="_blank">
<span class="fa fa-rss" style="margin-right: 3px"></span>
RSS
</a>
</li>
<li class="menu-item">
<a href="https://colossus.simpleisbetterthancomplex.com/subscribe/d2320a41-0378-4aa8-8f4e-5bb1ffcd521d/" class="brand" target="_blank">
<span class="fa fa-send" style="margin-right: 3px"></span> Subscribe
</a>
</li>
<li class="menu-item hidden-mobile">
<a href="https://simpleisbetterthancomplex.com/search/">
<span class="fa fa-search"></span> Search
</a>
</li>
</ul>
</div>
</header>
<div class="container">
<div class="row">
<div class="twelve columns post">
<div class="card post-author">
<div class="author-picture">
<img src="./A Complete Beginner's Guide to Django - Part 3_files/picture.jpg" alt="Vitor Freitas">
</div>
<div class="author-info">
<p class="name">By <strong>Vitor Freitas</strong></p>
<p class="bio">
I'm a passionate software developer and researcher. I write about Python, Django and Web Development on a weekly basis. <a href="https://simpleisbetterthancomplex.com/about/" rel="author">Read more</a>.
</p>
<p class="contact">
<a href="https://www.youtube.com/VitorFreitas" rel="me noopener" target="_blank" title="YouTube"><i class="fa fa-youtube-play"></i></a>
<a href="https://github.com/vitorfs" rel="me noopener" target="_blank" title="GitHub"><i class="fa fa-github"></i></a>
<a href="https://twitter.com/vitorfs" rel="me noopener" target="_blank" title="Twitter"><i class="fa fa-twitter"></i></a>
<a href="https://facebook.com/vitorfs" rel="me noopener" target="_blank" title="Facebook"><i class="fa fa-facebook-official"></i></a>
<a href="https://linkedin.com/in/vitorfs" rel="me noopener" target="_blank" title="LinkedIn"><i class="fa fa-linkedin-square"></i></a>
<a href="https://instagram.com/vitorfs" rel="me noopener" target="_blank" title="Instagram"><i class="fa fa-instagram"></i></a>
<a href="https://simpleisbetterthancomplex.com/contact/" title="Contact"><i class="fa fa-envelope"></i></a>
</p>
</div>
</div>
</div>
</div>
<div id="main-content" class="row">
<div id="seriesSideBar" class="three columns affix" style="">
<div class="card">
<div id="ad">
<script async="" type="text/javascript" src="./A Complete Beginner's Guide to Django - Part 3_files/carbon.js" id="_carbonads_js"></script>
</div>
<nav id="platformSideBar" class="platform js-set-platform" style="margin-bottom: 2rem; font-size: 1.2rem; display: block;">
<a href="javascript:void(0);" data-platform="mac" title="Set platform to Mac"><i class="fa fa-apple"></i> Mac</a>
<a href="javascript:void(0);" data-platform="windows" title="Set platform to Windows"><i class="fa fa-windows"></i> Win</a>
<a href="javascript:void(0);" data-platform="linux" title="Set platform to Linux" class="active"><i class="fa fa-linux"></i> Linux</a>
</nav>
<h5>Table of Contents</h5>
<ul>
<li><a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#introduction" class="">Introduction</a></li>
<li><a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#urls" class="">URLs</a></li>
<li style="padding-left: 1.5rem; font-size: 1.4rem; margin-bottom: 0.25rem">
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#basic-urls" class="">
Basic URLs
</a>
</li>
<li style="padding-left: 1.5rem; font-size: 1.4rem; margin-bottom: 0.25rem">
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#advanced-urls" class="">
Advanced URLs
</a>
</li>
<li style="padding-left: 1.5rem; font-size: 1.4rem; margin-bottom: 0.25rem">
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#using-the-urls-api" class="">
Using the URLs API
</a>
</li>
<li style="padding-left: 1.5rem; font-size: 1.4rem; margin-bottom: 0.25rem">
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#list-of-useful-url-patterns" class="">
List of Useful URL Patterns
</a>
</li>
<li><a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#reusable-templates" class="">Reusable Templates</a></li>
<li><a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#forms" class="">Forms</a></li>
<li style="padding-left: 1.5rem; font-size: 1.4rem; margin-bottom: 0.25rem">
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#how-not-implement-a-form" class="">
How Not Implement a Form
</a>
</li>
<li style="padding-left: 1.5rem; font-size: 1.4rem; margin-bottom: 0.25rem">
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#testing-the-form-view" class="">
Testing The Form View
</a>
</li>
<li style="padding-left: 1.5rem; font-size: 1.4rem; margin-bottom: 0.25rem">
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#creating-forms-the-right-way" class="active">
Creating Forms The Right Way
</a>
</li>
<li style="padding-left: 1.5rem; font-size: 1.4rem; margin-bottom: 0.25rem">
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#rendering-bootstrap-forms" class="">
Rendering Bootstrap Forms
</a>
</li>
<li style="padding-left: 1.5rem; font-size: 1.4rem; margin-bottom: 0.25rem">
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#reusable-forms-templates" class="">
Reusable Forms Templates
</a>
</li>
<li style="padding-left: 1.5rem; font-size: 1.4rem; margin-bottom: 0.25rem">
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#adding-more-tests" class="">
Adding More Tests
</a>
</li>
<li><a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#conclusions" class="">Conclusions</a></li>
</ul>
<hr style="margin: 1.5rem 0;">
<ul style="font-size: 1.4rem">
<li><a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#top"><i class="fa fa-arrow-up" style="margin-right: .2rem"></i> scroll to top</a></li>
<li><a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#comments"><i class="fa fa-comments" style="margin-right: .2rem"></i> go to comments</a></li>
<li><a href="https://simpleisbetterthancomplex.com/series/beginners-guide/1.11/"><i class="fa fa-list" style="margin-right: .2rem"></i> go to series index</a></li>
</ul>
</div>
</div>
<div class="nine columns content post" style="float:right">
<div class="card">
<h5 class="post-category">
series
</h5>
<hr class="dashed">
<h3 class="post-title">A Complete Beginner's Guide to Django - Part 3</h3>
<ul class="post-meta">
<li>
<i class="fa fa-calendar"></i> Sep 18, 2017
</li>
<li>
<i class="fa fa-clock-o"></i>
71 minutes read
</li>
<li>
<i class="fa fa-comments"></i>
<a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#disqus_thread" data-disqus-identifier="/series/2017/09/18/a-complete-beginners-guide-to-django-part-3">comments</a>
</li>
<li>
<i class="fa fa-eye"></i>
<span class="ga-page-views" data-ga-identifier="/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html"></span> views
</li>
<li>
<i class="fa fa-book"></i>
<a href="https://simpleisbetterthancomplex.com/series/beginners-guide/1.11/">Part 3 of 7</a>
</li>
</ul>
<div class="post-featured-image">
<img src="./A Complete Beginner's Guide to Django - Part 3_files/featured.jpg" alt="A Complete Beginner's Guide to Django - Part 3" class="featured-image">
</div>
<div class="row" style="margin-bottom: 2rem;">
<div class="five columns">
<nav id="platformArticle" class="platform js-set-platform">
<a href="javascript:void(0);" data-platform="mac" title="Set platform to Mac"><i class="fa fa-apple"></i> Mac</a>
<a href="javascript:void(0);" data-platform="windows" title="Set platform to Windows"><i class="fa fa-windows"></i> Windows</a>
<a href="javascript:void(0);" data-platform="linux" title="Set platform to Linux" class="active"><i class="fa fa-linux"></i> Linux</a>
</nav>
</div>
<div class="three columns">
<nav class="platform">
<a href="https://simpleisbetterthancomplex.com/series/beginners-guide/1.11/" class="series-nav">Series 3/7</a>
</nav>
</div>
<div class="four columns versions">
<img src="./A Complete Beginner's Guide to Django - Part 3_files/python-3.6.2-brightgreen.svg" alt="Python 3.6.2">
<img src="./A Complete Beginner's Guide to Django - Part 3_files/django-1.11.4-brightgreen.svg" alt="Django 1.11.4">
</div>
</div>
<hr class="dashed">
<div style="text-align:center;">
<div style="color:#aaa;font-size:1.2rem;margin-bottom:1rem;text-align:center;">ADVERTISEMENT</div>
<script async="" src="./A Complete Beginner's Guide to Django - Part 3_files/f.txt"></script>
<ins class="adsbygoogle" style="display:block; text-align:center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-5430683801108011" data-ad-slot="5978297717"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<hr class="dashed">
<article>
<h4 id="introduction">Introduction</h4>
<p>In this tutorial, we are going to dive deep into two fundamental concepts: URLs and Forms. In the process, we are going
to explore many other concepts like creating reusable templates and installing third-party libraries. We are also
going to write plenty of unit tests.</p>
<p>If you are following this tutorial series since the first part, coding your project and following the tutorial step by
step, you may need to update your <strong>models.py</strong> before starting:</p>
<p><strong>boards/models.py</strong></p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">class</span> <span class="nc">Topic</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
<span class="c"># other fields...</span>
<span class="c"># Add `auto_now_add=True` to the `last_updated` field</span>
<span class="n">last_updated</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="n">auto_now_add</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Post</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
<span class="c"># other fields...</span>
<span class="c"># Add `null=True` to the `updated_by` field</span>
<span class="n">updated_by</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s">'+'</span><span class="p">)</span></code></pre></figure>
<p>Now run the commands with the virtualenv activated:</p>
<figure class="highlight"><pre><code class="language-bash" data-lang="bash">python manage.py makemigrations
python manage.py migrate</code></pre></figure>
<p>If you already have <code class="highlighter-rouge">null=True</code> in the <code class="highlighter-rouge">updated_by</code> field and the <code class="highlighter-rouge">auto_now_add=True</code> in the <code class="highlighter-rouge">last_updated</code> field,
you can safely ignore the instructions above.</p>
<p>If you prefer to use my source code as a starting point, you can grab it on GitHub.</p>
<p>The current state of the project can be found under the release tag <strong>v0.2-lw</strong>. The link below will take you to the
right place:</p>
<p><a href="https://github.com/sibtc/django-beginners-guide/tree/v0.2-lw" target="_blank">https://github.com/sibtc/django-beginners-guide/tree/v0.2-lw</a></p>
<p>The development will follow from here.</p>
<hr>
<h4 id="urls">URLs</h4>
<p>Proceeding with the development of our application, now we have to implement a new page to list all the topics that
belong to a given <strong>Board</strong>. Just to recap, below you can see the wireframe we drew in the previous tutorial:</p>
<div id="figure-1">
<p><img src="./A Complete Beginner's Guide to Django - Part 3_files/wireframe-topics.png" alt="Wireframe Topics"></p>
<p style="text-align: center">
<small>Figure 1: Boards project wireframe listing all topics in the Django board.</small>
</p>
</div>
<p>We will start by editing the <strong>urls.py</strong> inside the <strong>myproject</strong> folder:</p>
<p><strong>myproject/urls.py</strong></p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">django.contrib</span> <span class="kn">import</span> <span class="n">admin</span>
<span class="kn">from</span> <span class="nn">boards</span> <span class="kn">import</span> <span class="n">views</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">home</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'home'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^boards/(?P<pk></span><span class="err">\</span><span class="s">d+)/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">board_topics</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'board_topics'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^admin/'</span><span class="p">,</span> <span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">urls</span><span class="p">),</span>
<span class="p">]</span></code></pre></figure>
<p>This time let’s take a moment and analyze the <code class="highlighter-rouge">urlpatterns</code> and <code class="highlighter-rouge">url</code>.</p>
<p>The URL dispatcher and <strong>URLconf</strong> (URL configuration) are fundamental parts of a Django application. In the beginning,
it can look confusing; I remember having a hard time when I first started developing with Django.</p>
<p>In fact, right now the Django Developers are working on a <a href="https://github.com/django/deps/blob/master/accepted/0201-simplified-routing-syntax.rst" target="_blank">proposal to make simplified routing syntax</a>.
But for now, as per the version 1.11, that’s what we have. So let’s try to understand how it works.</p>
<p>A project can have many <strong>urls.py</strong> distributed among the apps. But Django needs a <strong>url.py</strong> to use as a starting
point. This special <strong>urls.py</strong> is called <strong>root URLconf</strong>. It’s defined in the <strong>settings.py</strong> file.</p>
<p><strong>myproject/settings.py</strong></p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="n">ROOT_URLCONF</span> <span class="o">=</span> <span class="s">'myproject.urls'</span></code></pre></figure>
<p>It already comes configured, so you don’t need to change anything here.</p>
<p>When Django receives a request, it starts searching for a match in the project’s URLconf. It starts with the first
entry of the <code class="highlighter-rouge">urlpatterns</code> variable, and test the requested URL against each <code class="highlighter-rouge">url</code> entry.</p>
<p>If Django finds a match, it will pass the request to the <strong>view function</strong>, which is the second parameter of the
<code class="highlighter-rouge">url</code>. The order in the <code class="highlighter-rouge">urlpatterns</code> matters, because Django will stop searching as soon as it finds a match. Now, if
Django doesn’t find a match in the URLconf, it will raise a <strong>404</strong> exception, which is the error code for
<strong>Page Not Found</strong>.</p>
<p>This is the anatomy of the <code class="highlighter-rouge">url</code> function:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">url</span><span class="p">(</span><span class="n">regex</span><span class="p">,</span> <span class="n">view</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
<span class="c"># ...</span></code></pre></figure>
<ul>
<li><strong>regex</strong>: A regular expression for matching URL patterns in strings. Note that these regular expressions do not
search <strong>GET</strong> or <strong>POST</strong> parameters. In a request to <strong>http://127.0.0.1:8000/boards/?page=2</strong> only <strong>/boards/</strong> will
be processed.</li>
<li><strong>view</strong>: A view function used to process the user request for a matched URL. It also accepts the return of the
<strong>django.conf.urls.include</strong> function, which is used to reference an external <strong>urls.py</strong> file. You can, for example,
use it to define a set of app specific URLs, and include it in the root URLconf using a prefix. We will explore more
on this concept later on.</li>
<li><strong>kwargs</strong>: Arbitrary keyword arguments that’s passed to the target view. It is normally used to do some simple
customization on reusable views. We don’t use it very often.</li>
<li><strong>name</strong>: A unique identifier for a given URL. This is a very important feature. Always remember to name your URLs.
With this, you can change a specific URL in the whole project by just changing the regex. So it’s important to never
hard code URLs in the views or templates, and always refer to the URLs by its name.</li>
</ul>
<p><img src="./A Complete Beginner's Guide to Django - Part 3_files/Pixton_Comic_URL_Patterns.png" alt="Matching URL patterns"></p>
<h5 id="basic-urls">Basic URLs</h5>
<p>Basic URLs are very simple to create. It’s just a matter of matching strings. For example, let’s say we wanted to
create an “about” page, it could be defined like this:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">boards</span> <span class="kn">import</span> <span class="n">views</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">home</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'home'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^about/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">about</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'about'</span><span class="p">),</span>
<span class="p">]</span></code></pre></figure>
<p>We can also create deeper URL structures:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">boards</span> <span class="kn">import</span> <span class="n">views</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">home</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'home'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^about/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">about</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'about'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^about/company/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">about_company</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'about_company'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^about/author/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">about_author</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'about_author'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^about/author/vitor/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">about_vitor</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'about_vitor'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^about/author/erica/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">about_erica</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'about_erica'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^privacy/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">privacy_policy</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'privacy_policy'</span><span class="p">),</span>
<span class="p">]</span></code></pre></figure>
<p>Those are some examples of simple URL routing. For all the examples above, the view function will follow this
structure:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">about</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="c"># do something...</span>
<span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s">'about.html'</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">about_company</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="c"># do something else...</span>
<span class="c"># return some data along with the view...</span>
<span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s">'about_company.html'</span><span class="p">,</span> <span class="p">{</span><span class="s">'company_name'</span><span class="p">:</span> <span class="s">'Simple Complex'</span><span class="p">})</span></code></pre></figure>
<h5 id="advanced-urls">Advanced URLs</h5>
<p>A more advanced usage of URL routing is achieved by taking advantage of the regex to match certain types of data and
create dynamic URLs.</p>
<p>For example, to create a profile page, like many services do like github.com/vitorfs or twitter.com/vitorfs, where
“vitorfs” is my username, we can do the following:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">boards</span> <span class="kn">import</span> <span class="n">views</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">home</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'home'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^(?P<username>[</span><span class="err">\</span><span class="s">w.@+-]+)/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">user_profile</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'user_profile'</span><span class="p">),</span>
<span class="p">]</span></code></pre></figure>
<p>This will match all valid usernames for a Django User model.</p>
<p>Now observe that the example above is a very <em>permissive</em> URL. That means it will match lots of URL patterns because
it is defined in the root of the URL, with no prefix like <strong>/profile/<username>/</strong>. In this case, if we wanted to
define a URL named <strong>/about/</strong>, we would have do define it <em>before</em> the username URL pattern:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">boards</span> <span class="kn">import</span> <span class="n">views</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">home</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'home'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^about/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">about</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'about'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^(?P<username>[</span><span class="err">\</span><span class="s">w.@+-]+)/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">user_profile</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'user_profile'</span><span class="p">),</span>
<span class="p">]</span></code></pre></figure>
<p>If the “about” page was defined <em>after</em> the username URL pattern, Django would never find it, because the word “about”
would match the username regex, and the view <code class="highlighter-rouge">user_profile</code> would be processed instead of the <code class="highlighter-rouge">about</code> view function.</p>
<p>There are some side effects to that. For example, from now on, we would have to treat “about” as a forbidden username,
because if a user picked “about” as their username, this person would never see their profile page.</p>
<p><img src="./A Complete Beginner's Guide to Django - Part 3_files/Pixton_Comic_The_Order_Matters.png" alt="URL routing order matters"></p>
<div class="info">
<p>
<strong><i class="fa fa-info-circle"></i> Sidenote:</strong>
If you want to design cool URLs for user profiles, the easiest solution to avoid URL collision is by adding a prefix
like <strong>/u/vitorfs/</strong>, or like Medium does <strong>/@vitorfs/</strong>, where "@" is the prefix.
</p>
<p>
If you want no prefix at all, consider using a list of forbidden names like this:
<a href="https://github.com/shouldbee/reserved-usernames/blob/master/reserved-usernames.csv" target="_blank">github.com/shouldbee/reserved-usernames</a>.
Or another example is an application I developed when I was learning Django; I created my list at the time:
<a href="https://github.com/vitorfs/parsifal/blob/master/parsifal/authentication/forms.py#L6" target="_blank">github.com/vitorfs/parsifal/</a>.
</p>
<p>
Those collisions are very common. Take GitHub for example; they have this URL to list all the repositories you are
currently watching: <a href="https://github.com/watching" target="_blank">github.com/watching</a>. Someone registered a username
on GitHub with the name "watching," so this person can't see his profile page. We can see a user with this
username exists by trying this URL: <a href="https://github.com/watching/repositories" target="_blank">github.com/watching/repositories</a>
which was supposed to list the user's repositories, like mine for example <a href="https://github.com/vitorfs/repositories" target="_blank">github.com/vitorfs/repositories</a>.
</p>
</div>
<p>The whole idea of this kind of URL routing is to create dynamic pages where part of the URL will be used as an
identifier for a certain resource, that will be used to compose a page. This identifier can be an integer ID or a
string for example.</p>
<p>Initially, we will be working with the <strong>Board</strong> ID to create a dynamic page for the <strong>Topics</strong>. Let’s read again the
example I gave at the beginning of the <strong>URLs</strong> section:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="n">url</span><span class="p">(</span><span class="s">r'^boards/(?P<pk></span><span class="err">\</span><span class="s">d+)/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">board_topics</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'board_topics'</span><span class="p">)</span></code></pre></figure>
<p>The regex <code class="highlighter-rouge">\d+</code> will match an integer of arbitrary size. This integer will be used to retrieve the <strong>Board</strong> from the
database. Now observe that we wrote the regex as <code class="highlighter-rouge">(?P<pk>\d+)</code>, this is telling Django to capture the value into a
keyword argument named <strong>pk</strong>.</p>
<p>Here is how we write a view function for it:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">board_topics</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">pk</span><span class="p">):</span>
<span class="c"># do something...</span></code></pre></figure>
<p>Because we used the <code class="highlighter-rouge">(?P<pk>\d+)</code> regex, the keyword argument in the <code class="highlighter-rouge">board_topics</code> must be named <strong>pk</strong>.</p>
<p>If we wanted to use any name, we could do it like this:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="n">url</span><span class="p">(</span><span class="s">r'^boards/(</span><span class="err">\</span><span class="s">d+)/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">board_topics</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'board_topics'</span><span class="p">)</span></code></pre></figure>
<p>Then the view function could be defined like this:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">board_topics</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">board_id</span><span class="p">):</span>
<span class="c"># do something...</span></code></pre></figure>
<p>Or like this:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">board_topics</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="nb">id</span><span class="p">):</span>
<span class="c"># do something...</span></code></pre></figure>
<p>The name wouldn’t matter. But it’s a good practice to use named parameters because when we start composing bigger
URLs capturing multiple IDs and variables, it will be easier to read.</p>
<div class="info">
<p>
<strong><i class="fa fa-info-circle"></i> Sidenote:</strong> PK or ID?
</p>
<p>
<strong>PK</strong> stands for <strong>Primary Key</strong>. It's a shortcut for accessing a model's primary key.
All Django models have this attribute.
</p>
<p>
For the most cases, using the <code>pk</code> property is the same as <code>id</code>. That's because if we
don't define a primary key for a model, Django will automatically create an <code>AutoField</code> named
<code>id</code>, which will be its primary key.
</p>
<p>
If you defined a different primary key for a model, for example, let's say the field <code>email</code> is
your primary key. To access it you could either use <code>obj.email</code> or <code>obj.pk</code>.
</p>
</div>
<h5 id="using-the-urls-api">Using the URLs API</h5>
<p>It’s time to write some code. Let’s implement the topic listing page (see <a href="https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#figure-1">Figure 1</a>) I mentioned at the
beginning of the <strong>URLs</strong> section.</p>
<p>First, edit the <strong>urls.py</strong> adding our new URL route:</p>
<p><strong>myproject/urls.py</strong></p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">django.contrib</span> <span class="kn">import</span> <span class="n">admin</span>
<span class="kn">from</span> <span class="nn">boards</span> <span class="kn">import</span> <span class="n">views</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">home</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'home'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^boards/(?P<pk></span><span class="err">\</span><span class="s">d+)/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">board_topics</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'board_topics'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^admin/'</span><span class="p">,</span> <span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">urls</span><span class="p">),</span>
<span class="p">]</span></code></pre></figure>
<p>Now let’s create the view function <code class="highlighter-rouge">board_topics</code>:</p>
<p><strong>boards/views.py</strong></p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Board</span>
<span class="k">def</span> <span class="nf">home</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="c"># code suppressed for brevity</span>
<span class="k">def</span> <span class="nf">board_topics</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">pk</span><span class="p">):</span>
<span class="n">board</span> <span class="o">=</span> <span class="n">Board</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">pk</span><span class="p">)</span>
<span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s">'topics.html'</span><span class="p">,</span> <span class="p">{</span><span class="s">'board'</span><span class="p">:</span> <span class="n">board</span><span class="p">})</span></code></pre></figure>
<p>In the <strong>templates</strong> folder, create a new template named <strong>topics.html</strong>:</p>
<p><strong>templates/topics.html</strong></p>
<figure class="highlight"><pre><code class="language-django" data-lang="django"><span class="cp">{%</span> <span class="nv">load</span> <span class="nv">static</span> <span class="cp">%}<!DOCTYPE html></span>
<span class="nt"><html></span>
<span class="nt"><head></span>
<span class="nt"><meta</span> <span class="na">charset=</span><span class="s">"utf-8"</span><span class="nt">></span>
<span class="nt"><title></span><span class="cp">{{</span> <span class="nv">board.name</span> <span class="cp">}}</span><span class="nt"></title></span>
<span class="nt"><link</span> <span class="na">rel=</span><span class="s">"stylesheet"</span> <span class="na">href=</span><span class="s">"</span><span class="cp">{%</span> <span class="nv">static</span> <span class="s1">'css/bootstrap.min.css'</span> <span class="cp">%}</span><span class="s">"</span><span class="nt">></span>
<span class="nt"></head></span>
<span class="nt"><body></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"container"</span><span class="nt">></span>
<span class="nt"><ol</span> <span class="na">class=</span><span class="s">"breadcrumb my-4"</span><span class="nt">></span>
<span class="nt"><li</span> <span class="na">class=</span><span class="s">"breadcrumb-item"</span><span class="nt">></span>Boards<span class="nt"></li></span>
<span class="nt"><li</span> <span class="na">class=</span><span class="s">"breadcrumb-item active"</span><span class="nt">></span><span class="cp">{{</span> <span class="nv">board.name</span> <span class="cp">}}</span><span class="nt"></li></span>
<span class="nt"></ol></span>
<span class="nt"></div></span>
<span class="nt"></body></span>
<span class="nt"></html></span></code></pre></figure>
<div class="info">
<p>
<strong><i class="fa fa-info-circle"></i> Note:</strong>
For now we are simply creating new HTML templates. No worries, in the following section I will show you how to
create reusable templates.
</p>
</div>
<p>Now check the URL <strong>http://127.0.0.1:8000/boards/1/</strong> in a web browser. The result should be the following page:</p>
<p><img src="./A Complete Beginner's Guide to Django - Part 3_files/topics-1.png" alt="Topics Page"></p>
<p>Time to write some tests! Edit the <strong>tests.py</strong> file and add the following tests in the bottom of the file:</p>
<p><strong>boards/tests.py</strong></p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">django.core.urlresolvers</span> <span class="kn">import</span> <span class="n">reverse</span>
<span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">resolve</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>
<span class="kn">from</span> <span class="nn">.views</span> <span class="kn">import</span> <span class="n">home</span><span class="p">,</span> <span class="n">board_topics</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Board</span>
<span class="k">class</span> <span class="nc">HomeTests</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
<span class="c"># ...</span>
<span class="k">class</span> <span class="nc">BoardTopicsTests</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">Board</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'Django'</span><span class="p">,</span> <span class="n">description</span><span class="o">=</span><span class="s">'Django board.'</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_board_topics_view_success_status_code</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">url</span> <span class="o">=</span> <span class="n">reverse</span><span class="p">(</span><span class="s">'board_topics'</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="p">{</span><span class="s">'pk'</span><span class="p">:</span> <span class="mi">1</span><span class="p">})</span>
<span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">url</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_board_topics_view_not_found_status_code</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">url</span> <span class="o">=</span> <span class="n">reverse</span><span class="p">(</span><span class="s">'board_topics'</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="p">{</span><span class="s">'pk'</span><span class="p">:</span> <span class="mi">99</span><span class="p">})</span>
<span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">url</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">404</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_board_topics_url_resolves_board_topics_view</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">view</span> <span class="o">=</span> <span class="n">resolve</span><span class="p">(</span><span class="s">'/boards/1/'</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="n">view</span><span class="o">.</span><span class="n">func</span><span class="p">,</span> <span class="n">board_topics</span><span class="p">)</span></code></pre></figure>
<p>A few things to note here. This time we used the <code class="highlighter-rouge">setUp</code> method. In the setup method, we created a <strong>Board</strong> instance
to use in the tests. We have to do that because the Django testing suite doesn’t run your tests against the current
database. To run the tests Django creates a new database on the fly, applies all the model migrations, runs the tests,
and when done, destroys the testing database.</p>
<p>So in the <code class="highlighter-rouge">setUp</code> method, we prepare the environment to run the tests, so to simulate a scenario.</p>
<ul>
<li>The <code class="highlighter-rouge">test_board_topics_view_success_status_code</code> method: is testing if Django is returning a status code 200 (success)
for an existing <strong>Board</strong>.</li>
<li>The <code class="highlighter-rouge">test_board_topics_view_not_found_status_code</code> method: is testing if Django is returning a status code 404
(page not found) for a <strong>Board</strong> that doesn’t exist in the database.</li>
<li>The <code class="highlighter-rouge">test_board_topics_url_resolves_board_topics_view</code> method: is testing if Django is using the correct view
function to render the topics.</li>
</ul>
<p>Now it’s time to run the tests:</p>
<figure class="highlight"><pre><code class="language-bash" data-lang="bash">python manage.py <span class="nb">test</span></code></pre></figure>
<p>And the output:</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.E...
======================================================================
ERROR: test_board_topics_view_not_found_status_code (boards.tests.BoardTopicsTests)
----------------------------------------------------------------------
Traceback (most recent call last):
# ...
boards.models.DoesNotExist: Board matching query does not exist.
----------------------------------------------------------------------
Ran 5 tests in 0.093s
FAILED (errors=1)
Destroying test database for alias 'default'...</code></pre></figure>
<p>The test <strong>test_board_topics_view_not_found_status_code</strong> failed. We can see in the Traceback it returned an exception
“boards.models.DoesNotExist: Board matching query does not exist.”</p>
<p><img src="./A Complete Beginner's Guide to Django - Part 3_files/topics-error-500.png" alt="Topics Error 500 Page"></p>
<p>In production with <code class="highlighter-rouge">DEBUG=False</code>, the visitor would see a <strong>500 Internal Server Error</strong> page. But that’s not the
behavior we want.</p>
<p>We want to show a <strong>404 Page Not Found</strong>. So let’s refactor our view:</p>
<p><strong>boards/views.py</strong></p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">Http404</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Board</span>
<span class="k">def</span> <span class="nf">home</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="c"># code suppressed for brevity</span>
<span class="k">def</span> <span class="nf">board_topics</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">pk</span><span class="p">):</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">board</span> <span class="o">=</span> <span class="n">Board</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">pk</span><span class="p">)</span>
<span class="k">except</span> <span class="n">Board</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">Http404</span>
<span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s">'topics.html'</span><span class="p">,</span> <span class="p">{</span><span class="s">'board'</span><span class="p">:</span> <span class="n">board</span><span class="p">})</span></code></pre></figure>
<p>Let’s test again:</p>
<figure class="highlight"><pre><code class="language-bash" data-lang="bash">python manage.py <span class="nb">test</span></code></pre></figure>
<figure class="highlight"><pre><code class="language-text" data-lang="text">Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.....
----------------------------------------------------------------------
Ran 5 tests in 0.042s
OK
Destroying test database for alias 'default'...</code></pre></figure>
<p>Yay! Now it’s working as expected.</p>
<p><img src="./A Complete Beginner's Guide to Django - Part 3_files/topics-error-404.png" alt="Topics Error 404 Page"></p>
<p>This is the default page Django show while with <code class="highlighter-rouge">DEBUG=False</code>. Later on, we can customize the 404 page to show something
else.</p>
<p>Now that’s a very common use case. In fact, Django has a shortcut to try to get an object, or return a 404 with the
object does not exist.</p>
<p>So let’s refactor the <strong>board_topics</strong> view again:</p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">render</span><span class="p">,</span> <span class="n">get_object_or_404</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Board</span>
<span class="k">def</span> <span class="nf">home</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="c"># code suppressed for brevity</span>
<span class="k">def</span> <span class="nf">board_topics</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">pk</span><span class="p">):</span>
<span class="n">board</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">Board</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">pk</span><span class="p">)</span>
<span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s">'topics.html'</span><span class="p">,</span> <span class="p">{</span><span class="s">'board'</span><span class="p">:</span> <span class="n">board</span><span class="p">})</span></code></pre></figure>
<p>Changed the code? Test it.</p>
<figure class="highlight"><pre><code class="language-bash" data-lang="bash">python manage.py <span class="nb">test</span></code></pre></figure>
<figure class="highlight"><pre><code class="language-text" data-lang="text">Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.....
----------------------------------------------------------------------
Ran 5 tests in 0.052s
OK
Destroying test database for alias 'default'...</code></pre></figure>
<p>Didn’t break anything. We can proceed with the development.</p>
<p>The next step now is to create the navigation links in the screens. The homepage should have a link to take the visitor
to the topics page of a given <strong>Board</strong>. Similarly, the topics page should have a link back to the homepage.</p>
<p><img src="./A Complete Beginner's Guide to Django - Part 3_files/wireframe-links.png" alt="Wireframe Links"></p>
<p>We can start by writing some tests for the <code class="highlighter-rouge">HomeTests</code> class:</p>
<p><strong>boards/tests.py</strong></p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">class</span> <span class="nc">HomeTests</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">board</span> <span class="o">=</span> <span class="n">Board</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'Django'</span><span class="p">,</span> <span class="n">description</span><span class="o">=</span><span class="s">'Django board.'</span><span class="p">)</span>
<span class="n">url</span> <span class="o">=</span> <span class="n">reverse</span><span class="p">(</span><span class="s">'home'</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">url</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_home_view_status_code</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_home_url_resolves_home_view</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">view</span> <span class="o">=</span> <span class="n">resolve</span><span class="p">(</span><span class="s">'/'</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="n">view</span><span class="o">.</span><span class="n">func</span><span class="p">,</span> <span class="n">home</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_home_view_contains_link_to_topics_page</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">board_topics_url</span> <span class="o">=</span> <span class="n">reverse</span><span class="p">(</span><span class="s">'board_topics'</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="p">{</span><span class="s">'pk'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">board</span><span class="o">.</span><span class="n">pk</span><span class="p">})</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertContains</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">response</span><span class="p">,</span> <span class="s">'href="{0}"'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">board_topics_url</span><span class="p">))</span></code></pre></figure>
<p>Observe that now we added a <strong>setUp</strong> method for the <strong>HomeTests</strong> as well. That’s because now we are going to need a
<strong>Board</strong> instance and also we moved the <strong>url</strong> and <strong>response</strong> to the <strong>setUp</strong>, so we can reuse the same response in the
new test.</p>
<p>The new test here is the <strong>test_home_view_contains_link_to_topics_page</strong>. Here we are using the <strong>assertContains</strong>
method to test if the response body contains a given text. The text we are using in the test, is the <code class="highlighter-rouge">href</code> part of an
<code class="highlighter-rouge">a</code> tag. So basically we are testing if the response body has the text <code class="highlighter-rouge">href="/boards/1/"</code>.</p>
<p>Let’s run the tests:</p>
<figure class="highlight"><pre><code class="language-bash" data-lang="bash">python manage.py <span class="nb">test</span></code></pre></figure>
<figure class="highlight"><pre><code class="language-text" data-lang="text">Creating test database for alias 'default'...
System check identified no issues (0 silenced).
....F.
======================================================================
FAIL: test_home_view_contains_link_to_topics_page (boards.tests.HomeTests)
----------------------------------------------------------------------
# ...
AssertionError: False is not true : Couldn't find 'href="/boards/1/"' in response
----------------------------------------------------------------------
Ran 6 tests in 0.034s
FAILED (failures=1)
Destroying test database for alias 'default'...</code></pre></figure>
<p>Now we can write the code that will make this test pass.</p>
<p>Edit the <strong>home.html</strong> template:</p>
<p><strong>templates/home.html</strong></p>
<figure class="highlight"><pre><code class="language-django" data-lang="django"><span class="c"><!-- code suppressed for brevity --></span>
<span class="nt"><tbody></span>
<span class="cp">{%</span> <span class="k">for</span> <span class="nv">board</span> <span class="ow">in</span> <span class="nv">boards</span> <span class="cp">%}</span>
<span class="nt"><tr></span>
<span class="nt"><td></span>
<span class="nt"><a</span> <span class="na">href=</span><span class="s">"</span><span class="cp">{%</span> <span class="nv">url</span> <span class="s1">'board_topics'</span> <span class="nv">board.pk</span> <span class="cp">%}</span><span class="s">"</span><span class="nt">></span><span class="cp">{{</span> <span class="nv">board.name</span> <span class="cp">}}</span><span class="nt"></a></span>
<span class="nt"><small</span> <span class="na">class=</span><span class="s">"text-muted d-block"</span><span class="nt">></span><span class="cp">{{</span> <span class="nv">board.description</span> <span class="cp">}}</span><span class="nt"></small></span>
<span class="nt"></td></span>
<span class="nt"><td</span> <span class="na">class=</span><span class="s">"align-middle"</span><span class="nt">></span>0<span class="nt"></td></span>
<span class="nt"><td</span> <span class="na">class=</span><span class="s">"align-middle"</span><span class="nt">></span>0<span class="nt"></td></span>
<span class="nt"><td></td></span>
<span class="nt"></tr></span>
<span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
<span class="nt"></tbody></span>
<span class="c"><!-- code suppressed for brevity --></span></code></pre></figure>
<p>So basically we changed the line:</p>
<figure class="highlight"><pre><code class="language-django" data-lang="django"><span class="cp">{{</span> <span class="nv">board.name</span> <span class="cp">}}</span></code></pre></figure>
<p>To:</p>
<figure class="highlight"><pre><code class="language-django" data-lang="django"><span class="nt"><a</span> <span class="na">href=</span><span class="s">"</span><span class="cp">{%</span> <span class="nv">url</span> <span class="s1">'board_topics'</span> <span class="nv">board.pk</span> <span class="cp">%}</span><span class="s">"</span><span class="nt">></span><span class="cp">{{</span> <span class="nv">board.name</span> <span class="cp">}}</span><span class="nt"></a></span></code></pre></figure>
<p>Always use the <code class="highlighter-rouge"><span class="p">{</span><span class="err">%</span><span class="w"> </span><span class="err">url</span><span class="w"> </span><span class="err">%</span><span class="p">}</span></code> template tag to compose the applications URLs. The first parameter
is the <strong>name</strong> of the URL (defined in the URLconf, i.e., the <strong>urls.py</strong>), then you can pass an arbitrary number of arguments as needed.</p>
<p>If it were a simple URL, like the homepage, it would be just <code class="highlighter-rouge"><span class="p">{</span><span class="err">%</span><span class="w"> </span><span class="err">url</span><span class="w"> </span><span class="err">'home'</span><span class="w"> </span><span class="err">%</span><span class="p">}</span></code>.</p>
<p>Save the file and run the tests again:</p>
<figure class="highlight"><pre><code class="language-bash" data-lang="bash">python manage.py <span class="nb">test</span></code></pre></figure>
<figure class="highlight"><pre><code class="language-text" data-lang="text">Creating test database for alias 'default'...
System check identified no issues (0 silenced).
......
----------------------------------------------------------------------
Ran 6 tests in 0.037s
OK
Destroying test database for alias 'default'...</code></pre></figure>
<p>Good! Now we can check how it looks in the web browser:</p>
<p><img src="./A Complete Beginner's Guide to Django - Part 3_files/boards.png" alt="Boards with Link"></p>
<p>Now the link back. We can write the test first:</p>
<p><strong>boards/tests.py</strong></p>
<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">class</span> <span class="nc">BoardTopicsTests</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
<span class="c"># code suppressed for brevity...</span>
<span class="k">def</span> <span class="nf">test_board_topics_view_contains_link_back_to_homepage</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">board_topics_url</span> <span class="o">=</span> <span class="n">reverse</span><span class="p">(</span><span class="s">'board_topics'</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="p">{</span><span class="s">'pk'</span><span class="p">:</span> <span class="mi">1</span><span class="p">})</span>
<span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">board_topics_url</span><span class="p">)</span>
<span class="n">homepage_url</span> <span class="o">=</span> <span class="n">reverse</span><span class="p">(</span><span class="s">'home'</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertContains</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="s">'href="{0}"'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">homepage_url</span><span class="p">))</span></code></pre></figure>
<p>Run the tests:</p>
<figure class="highlight"><pre><code class="language-bash" data-lang="bash">python manage.py <span class="nb">test</span></code></pre></figure>
<figure class="highlight"><pre><code class="language-text" data-lang="text">Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.F.....
======================================================================
FAIL: test_board_topics_view_contains_link_back_to_homepage (boards.tests.BoardTopicsTests)
----------------------------------------------------------------------