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
|
---
title: 'Django Tutorial - 8. Bölüm: Kullanıcı doğrulama ve izinler'
slug: Öğren/Server-side/Django/Authentication
translation_of: Learn/Server-side/Django/Authentication
---
<div>{{LearnSidebar}}</div>
<div>{{PreviousMenuNext("Learn/Server-side/Django/Sessions", "Learn/Server-side/Django/Forms", "Learn/Server-side/Django")}}</div>
<p class="summary">Bu eğitimde size, kullanıcılara sizin sitenize kendi hesapları ile giriş yapabilmesi için, nasıl izin vereceğinizi, giriş yapmış ya da yapmamış olmaları durumuna ve izinlerine göre neler yapabileceklerini ve neleri görebileceklerini, nasıl kontrol edebileceğinizi göstereceğiz. Bu eğitimin parçası olarak, <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">Yerel Kütüphane</a> web sitesini, giriş sayfası, çıkış sayfası ve ödünç alınan kitapların görüntülenmesi için kullanıcı ve personele özel sayfalar ekleyerek geliştireceğiz.</p>
<table class="learn-box standard-table">
<tbody>
<tr>
<th scope="row">Ön şartlar:</th>
<td>Complete all previous tutorial topics, up to and including <a href="/en-US/docs/Learn/Server-side/Django/Sessions">Django Tutorial Part 7: Sessions framework</a>.</td>
</tr>
<tr>
<th scope="row">Amaç:</th>
<td>Kullanıcı doğrulama ve izinlerin nasıl kurulacağı ve kullanılacağını anlamak.</td>
</tr>
</tbody>
</table>
<h2 id="Genel_bakış">Genel bakış</h2>
<p>Django provides an authentication and authorisation ("permission") system, built on top of the session framework discussed in the <a href="/en-US/docs/Learn/Server-side/Django/Sessions">previous tutorial</a>, that allows you to verify user credentials and define what actions each user is allowed to perform. The framework includes built-in models for <code>Users</code> and <code>Groups</code> (a generic way of applying permissions to more than one user at a time), permissions/flags that designate whether a user may perform a task, forms and views for logging in users, and view tools for restricting content.</p>
<div class="note">
<p><strong>Note</strong>: According to Django the authentication system aims to be very generic, and so does not provide some features provided in other web authentication systems. Solutions for some common problems are available as third party packages. For example, throttling of login attempts and authentication against third parties (e.g. OAuth).</p>
</div>
<p>In this tutorial we'll show you how to enable user authentication in the <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">LocalLibrary</a> website, create your own login and logout pages, add permissions to your models, and control access to pages. We'll use the authentication/permissions to display lists of books that have been borrowed for both users and librarians.</p>
<p>The authentication system is very flexible, and you can build up your URLs, forms, views, and templates from scratch if you like, just calling the provided API to login the user. However, in this article we're going to use Django's "stock" authentication views and forms for our login and logout pages. We'll still need to create some templates, but that's pretty easy.</p>
<p>We'll also show you how to create permissions, and check on login status and permissions in both views and templates.</p>
<h2 id="Doğrulamayı_etkinleştirme">Doğrulamayı etkinleştirme</h2>
<p>Doğrulama <a href="/en-US/docs/Learn/Server-side/Django/skeleton_website">iskelet websitesini oluşturduğumuzda</a> (tutorial 2'de) otomatik olarak etkinleştirilmiştir, bu yüzden bu noktada daha fazla bir şey yapmanız gerekmemektedir.</p>
<div class="note">
<p><strong>Not</strong>: <code>django-admin startproject</code> komutunu kullarak uygulamayı oluşturduğumuzda gerekli yapılandırmanın hepsi yapıldı. <code>python manage.py migrate</code>komutunu çağırdığımızda, kullanıcılar ve izinler için veri tabanı tabloları oluşturuldu.</p>
</div>
<p>Aşağıda gösterildiği gibi, yapılandırma, proje dosyasının (<strong>locallibrary/locallibrary/settings.py</strong>) <code>INSTALLED_APPS</code> ve <code>MIDDLEWARE</code> kısımlarında kurulmuştur:</p>
<pre class="brush: python">INSTALLED_APPS = [
...
<strong> 'django.contrib.auth', </strong>#Core authentication framework and its default models.
<strong> 'django.contrib.contenttypes', #</strong>Django content type system (allows permissions to be associated with models).
....
MIDDLEWARE = [
...
<strong> 'django.contrib.sessions.middleware.SessionMiddleware',</strong> #Manages sessions across requests
...
<strong> 'django.contrib.auth.middleware.AuthenticationMiddleware',</strong> #Associates users with requests using sessions.
....
</pre>
<h2 id="Kullanıcılar_ve_gruplar_oluşturma">Kullanıcılar ve gruplar oluşturma</h2>
<p>Tutorial 4'te <a href="/en-US/docs/Learn/Server-side/Django/Admin_site">Django admin sitesi</a>'ne baktığımızda zaten ilk kullanıcınızı oluşturmuştunuz (<code>python manage.py createsuperuser</code> komutuyla oluşturulan bir superuser idi). Superuser'ımız zaten doğrulanmış ve tüm izinlere sahipti, bu yüzden normal bir site kullanıcısını temsilen bir test kullanıcısı oluşturmamız gerekmektedir. Y<span class="translation">apmanın en hızlı yollarından biri olduğu için,</span> <em>locallibrary</em> gruplarımızı ve websitesi oturumlarımızı oluşturmak için admin sitesini kullanıyor olacağız.</p>
<div class="note">
<p>Not: Aşağıda gösterildiği gibi, ayrıca programatik olarak da kullanıcılar oluşturabilirsiniz. Örneğin, kullanıcıların kendi oturumlarını oluşturmalarını sağlayan bir arayüz geliştiriliyorsa, bunu yapmak zorunda kalabilirsiniz (kullancılara admin sitesine erişim vermemelisiniz).</p>
<pre class="brush: python">from django.contrib.auth.models import User
# Create user and save to the database
user = User.objects.create_user('myusername', 'myemail@crazymail.com', 'mypassword')
# Update fields and then save again
user.first_name = 'John'
user.last_name = 'Citizen'
user.save()
</pre>
</div>
<p>Aşağıda ilk bir grup ve sonra bir kullanıcı oluşturacağız. Henüz kütüphane üyelerimize ekleme iznimiz olmasa da, sonrasında ihtiyacımız olursa, her bir üyeye ayrı ayrı eklemektense gruba tek bir seferde eklemek daha kolay olacaktır.</p>
<p>Geliştirme sunucusunu başlatın ve yerel web tarayıcınızda admin sitesine gidin (<a href="http://127.0.0.1:8000/admin/">http://127.0.0.1:8000/admin/</a>). Superuser hesabınız için kimlik bilgilerini kullanarak siteye giriş yapın. Admin sitesinin üst seviyesi, "django application" tarafından sıralanmış tüm modellerinizi görüntüler. <strong>Authentication and Authorisation</strong> kısmından, mevcut kayıtlarını görmek için <strong>Users</strong> veya <strong>Groups</strong> bağlantılarına tıklayabilirsiniz.</p>
<p><img alt="Admin site - add groups or users" src="https://mdn.mozillademos.org/files/14091/admin_authentication_add.png" style="border-style: solid; border-width: 1px; display: block; height: 364px; margin: 0px auto; width: 661px;"></p>
<p>İlk olarak kütüphane üyelerimiz için yeni bir grup oluşturalım.</p>
<ol>
<li>Yeni bir <em>Group</em> oluşturmak için <strong>Add</strong> düğmesine (Group'un yanındaki) tıklayın; grup için <strong>Name</strong> kısmına "Library Members" girin.<img alt="Admin site - add group" src="https://mdn.mozillademos.org/files/14093/admin_authentication_add_group.png" style="border-style: solid; border-width: 1px; display: block; height: 561px; margin: 0px auto; width: 800px;"></li>
<li>Grup için herhangi bir izne ihtiyacımız yok, bu yüzden yalnızca <strong>SAVE</strong> düğmesine basın (sizi gruplar listesine götürecek).</li>
</ol>
<p>Şimdi yeni bir kullanıcı oluşturalım:</p>
<ol>
<li>Admin sitesinin anasayfasına geri gidin.</li>
<li><em>Add user</em> diyaloğunu açmak için <em>Users</em>'ın yanındaki <strong>Add</strong> düğmesine tıklayın.<img alt="Admin site - add user pt1" src="https://mdn.mozillademos.org/files/14095/admin_authentication_add_user_prt1.png" style="border-style: solid; border-width: 1px; display: block; height: 409px; margin: 0px auto; width: 800px;"></li>
<li>Test kullanıcınız için uygun bir <strong>Username</strong> ve <strong>Password</strong>/<strong>Password confirmation</strong> girin.</li>
<li>Kullanıcıyı oluşturmak için <strong>SAVE</strong> düğmesine basın.<br>
<br>
Admin sitesi yeni kullanıcıyı oluşturacak ve hemen sizi <strong>username</strong>'inizi değiştirebileceğinz ve User modelin isteğe bağlı alanlarına bilgi ekleyebileceğiniz bir <em>Change user</em> ekranına götürecektir. Bu alanlar ad, soyad, e-posta adresi, kullanıcı durumu ve izinleri (yalnızca <strong>Active</strong> flag ayarlanmalı). Daha aşağıda kullanıcı grupları ve izinlerini belirleyebilir ve kullanıcıyla ilgili önemli tarihleri görebilirsiniz (katılım tarihi ve son giriş tarihi gibi).<img alt="Admin site - add user pt2" src="https://mdn.mozillademos.org/files/14097/admin_authentication_add_user_prt2.png" style="border-style: solid; border-width: 1px; display: block; height: 635px; margin: 0px auto; width: 800px;"></li>
<li><em>Groups</em> kısmında, select <strong>Library Member</strong> group from the list of <em>Available groups</em>, and then press the<strong> right-arrow</strong> between the boxes to move it into the <em>Chosen groups</em> box.<img alt="Admin site - add user to group" src="https://mdn.mozillademos.org/files/14099/admin_authentication_user_add_group.png" style="border-style: solid; border-width: 1px; display: block; height: 414px; margin: 0px auto; width: 933px;"></li>
<li>We don't need to do anything else here, so just select <strong>SAVE</strong> again, to go to the list of users.</li>
</ol>
<p>That's it! Now you have a "normal library member" account that you will be able to use for testing (once we've implemented the pages to enable them to login).</p>
<div class="note">
<p><strong>Note</strong>: You should try creating another library member user. Also, create a group for Librarians, and add a user to that too!</p>
</div>
<h2 id="Doğrulama_view'lerinizi_kurma">Doğrulama view'lerinizi kurma</h2>
<p>Django's provides almost everything you need to create authentication pages to handle login, logout, and password management "out of the box". This includes an url mapper, views and forms, but it does not include the templates — we have to create our own!</p>
<p>In this section we show how to integrate the default system into the <em>LocalLibrary</em> website and create the templates. We'll put them in the main project URLs.</p>
<div class="note">
<p><strong>Note</strong>: You don't have to use any of this code, but it is likely that you'll want to because it makes things a lot easier. You'll almost certainly need to change the form handling code if you change your user model (an advanced topic!) but even so, you would still be able to use the stock view functions.</p>
</div>
<div class="note">
<p><strong>Note: </strong>In this case we could reasonably put the authentication pages, including the URLs and templates, inside our catalog application. However if we had multiple applications it would be better to separate out this shared login behaviour and have it available across the whole site, so that is what we've shown here!</p>
</div>
<h3 id="Proje_URL'leri">Proje URL'leri</h3>
<p>Add the following to the bottom of the project urls.py file (<strong>locallibrary/locallibrary/urls.py</strong>) file:</p>
<pre class="brush: python">#Add Django site authentication urls (for login, logout, password management)
urlpatterns += [
url(r'^accounts/', include('django.contrib.auth.urls')),
]
</pre>
<p>Navigate to the <a href="http://127.0.0.1:8000/accounts/">http://127.0.0.1:8000/accounts/</a> URL (note the trailing forward slash!) and Django will show an error that it could not find this URL, and listing all the URLs it tried. From this you can see the URLs that will work, for example:</p>
<div class="note">
<p><strong>Note: </strong>Using the above method adds the following urls with names in square brackets, which can be used to reverse the url mappings. You don't have to implement anything else — the above url mapping automatically maps the below mentioned URLs.</p>
</div>
<div class="note">
<pre class="brush: python">^accounts/login/$ [name='login']
^accounts/logout/$ [name='logout']
^accounts/password_change/$ [name='password_change']
^accounts/password_change/done/$ [name='password_change_done']
^accounts/password_reset/$ [name='password_reset']
^accounts/password_reset/done/$ [name='password_reset_done']
^accounts/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$ [name='password_reset_confirm']
^accounts/reset/done/$ [name='password_reset_complete']</pre>
</div>
<p>Now try to navigate to the login URL (<a href="http://127.0.0.1:8000/accounts/login/">http://127.0.0.1:8000/accounts/login/</a>). This will fail again, but with an error that tells you that we're missing the required template (<strong>registration/login.html</strong>) on the template search path. You'll see the following lines listed in the yellow section up the top:</p>
<pre class="brush: python">Exception Type: TemplateDoesNotExist
Exception Value: <strong>registration/login.html</strong></pre>
<p>The next step is to create a registration directory on the search path and then add the <strong>login.html</strong> file.</p>
<h3 id="Şablon_dizini">Şablon dizini</h3>
<p>The urls (and implicitly views) that we just added expect to find their associated templates in a directory <strong>/registration/</strong> somewhere in the templates search path.</p>
<p>For this site we'll put our HTML pages in the <strong>templates/registration/</strong> directory. This directory should be in your project root directory, i.e the same directory as as the <strong>catalog</strong> and <strong>locallibrary</strong> folders). Please create these folders now.</p>
<div class="note">
<p><strong>Note:</strong> Your folder structure should now look like the below:<br>
locallibrary (django project folder)<br>
|_catalog<br>
|_locallibrary<br>
|_templates <strong>(new)</strong><br>
|_registration</p>
</div>
<p>To make these directories visible to the template loader (i.e. to put this directory in the template search path) open the project settings (<strong>/locallibrary/locallibrary/settings.py</strong>), and update the <code>TEMPLATES</code> section's <code>'DIRS'</code> line as shown.</p>
<pre class="brush: python">TEMPLATES = [
{
...
<strong> 'DIRS': ['./templates',],</strong>
'APP_DIRS': True,
...
</pre>
<h3 id="Login_template">Login template</h3>
<div class="warning">
<p><strong>Important</strong>: The authentication templates provided in this article are very basic/slightly modified version of the Django demonstration login templates. You may need to customise them for your own use!</p>
</div>
<p>Create a new HTML file called /<strong>locallibrary/templates/registration/login.html</strong>. give it the following contents:</p>
<pre class="brush: html">{% extends "base_generic.html" %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
{% if next %}
{% if user.is_authenticated %}
<p>Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>
{% else %}
<p>Please login to see this page.</p>
{% endif %}
{% endif %}
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<div>
<td>\{{ form.username.label_tag }}</td>
<td>\{{ form.username }}</td>
</div>
<div>
<td>\{{ form.password.label_tag }}</td>
<td>\{{ form.password }}</td>
</div>
<div>
<input type="submit" value="login" />
<input type="hidden" name="next" value="\{{ next }}" />
</div>
</form>
{# Assumes you setup the password_reset view in your URLconf #}
<p><a href="{% url 'password_reset' %}">Lost password?</a></p>
{% endblock %}</pre>
<p id="sect1">This template shares some similarities with the ones we've seen before — it extends our base template and overrides the <code>content</code> block. The rest of the code is fairly standard form handling code, which we will discuss in a later tutorial. All you need to know for now is that this will display a form in which you can enter your username and password, and that if you enter invalid values you will be prompted to enter correct values when the page refreshes.</p>
<p>Navigate back to the login page (<a href="http://127.0.0.1:8000/accounts/login/">http://127.0.0.1:8000/accounts/login/</a>) once you've saved your template, and you should see something like this:</p>
<p><img alt="Library login page v1" src="https://mdn.mozillademos.org/files/14101/library_login.png" style="border-style: solid; border-width: 1px; display: block; height: 173px; margin: 0px auto; width: 441px;"></p>
<p>If you try to login that will succeed and you'll be redirected to another page (by default this will be <a href="http://127.0.0.1:8000/accounts/profile/">http://127.0.0.1:8000/accounts/profile/</a>). The problem here is that by default Django expects that after login you will want to be taken to a profile page, which may or may not be the case. As you haven't defined this page yet, you'll get another error!</p>
<p>Open the project settings (<strong>/locallibrary/locallibrary/settings.py</strong>) and add the text below to the bottom. Now when you login you should be redirected to the site home page by default.</p>
<pre class="brush: python"># Redirect to home URL after login (Default redirects to /accounts/profile/)
LOGIN_REDIRECT_URL = '/'
</pre>
<h3 id="Logout_template">Logout template</h3>
<p>If you navigate to the logout url (<a href="http://127.0.0.1:8000/accounts/logout/">http://127.0.0.1:8000/accounts/logout/</a>) then you'll see some odd behaviour — your user will be logged out sure enough, but you'll be taken to the <strong>Admin</strong> logout page. That's not what you want, if only because the login link on that page takes you to the Admin login screen (and that is only available to users who have the <code>is_staff</code> permission).</p>
<p>Create and open /<strong>locallibrary/templates/registration/logged_out.html</strong>. Copy in the text below:</p>
<pre class="brush: html">{% extends "base_generic.html" %}
{% block content %}
<p>Logged out!</p>
<a href="{% url 'login'%}">Click here to login again.</a>
{% endblock %}</pre>
<p>This template is very simple. It just displays a message informing you that you have been logged out, and provides a link that you can press to go back to the login screen. If you go to the logout URL again you should see this page:</p>
<p><img alt="Library logout page v1" src="https://mdn.mozillademos.org/files/14103/library_logout.png" style="border-style: solid; border-width: 1px; display: block; height: 169px; margin: 0px auto; width: 385px;"></p>
<h3 id="Password_reset_templates">Password reset templates</h3>
<p>The default password reset system uses email to send the user a reset link. You need to create forms to get the user's email address, send the email, allow them to enter a new password, and to note when the whole process is complete.</p>
<p>The following templates can be used as a starting point.</p>
<h4 id="Password_reset_form">Password reset form</h4>
<p>This is the form used to get the user's email address (for sending the password reset email). Create <strong>/locallibrary/templates/registration/password_reset_form.html</strong>, and give it the following contents:</p>
<pre class="brush: html">{% extends "base_generic.html" %}
{% block content %}
<form action="" method="post">{% csrf_token %}
{% if form.email.errors %} \{{ form.email.errors }} {% endif %}
<p>\{{ form.email }}</p>
<input type="submit" class="btn btn-default btn-lg" value="Reset password" />
</form>
{% endblock %}
</pre>
<h4 id="Password_reset_done">Password reset done</h4>
<p>This form is displayed after your email address has been collected. Create <strong>/locallibrary/templates/registration/password_reset_done.html</strong>, and give it the following contents:</p>
<pre class="brush: html">{% extends "base_generic.html" %}
{% block content %}
<p>We've emailed you instructions for setting your password. If they haven't arrived in a few minutes, check your spam folder.</p>
{% endblock %}
</pre>
<h4 id="Password_reset_email">Password reset email</h4>
<p>This template provides the text of the HTML email containing the reset link that we will send to users. Create <strong>/locallibrary/templates/registration/password_reset_email.html</strong>, and give it the following contents:</p>
<pre class="brush: html">Someone asked for password reset for email \{{ email }}. Follow the link below:
\{{ protocol}}://\{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
</pre>
<h4 id="Password_reset_confirm">Password reset confirm</h4>
<p>This page is where you enter your new password after clicking the link in the password-reset email. Create <strong>/locallibrary/templates/registration/password_reset_confirm.html</strong>, and give it the following contents:</p>
<pre class="brush: html">{% extends "base_generic.html" %}
{% block content %}
{% if validlink %}
<p>Please enter (and confirm) your new password.</p>
<form action="" method="post">
<div style="display:none">
<input type="hidden" value="\{{ csrf_token }}" name="csrfmiddlewaretoken">
</div>
<table>
<tr>
<td>\{{ form.new_password1.errors }}
<label for="id_new_password1">New password:</label></td>
<td>\{{ form.new_password1 }}</td>
</tr>
<tr>
<td>\{{ form.new_password2.errors }}
<label for="id_new_password2">Confirm password:</label></td>
<td>\{{ form.new_password2 }}</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Change my password" /></td>
</tr>
</table>
</form>
{% else %}
<h1>Password reset failed</h1>
<p>The password reset link was invalid, possibly because it has already been used. Please request a new password reset.</p>
{% endif %}
{% endblock %}
</pre>
<h4 id="Password_reset_complete">Password reset complete</h4>
<p>This is the last password-reset template, which is displayed to notify you when the password reset has succeeded. Create <strong>/locallibrary/templates/registration/password_reset_complete.html</strong>, and give it the following contents:</p>
<pre class="brush: html">{% extends "base_generic.html" %}
{% block content %}
<h1>The password has been changed!</h1>
<p><a href="{% url 'login' %}">log in again?</a></p>
{% endblock %}</pre>
<h3 id="Testing_the_new_authentication_pages">Testing the new authentication pages</h3>
<p>Now that you've added the URL configuration and created all these templates, the authentication pages should now just work!</p>
<p>You can test the new authentication pages by attempting to login and then logout your superuser account using these URLs:</p>
<ul>
<li><a href="http://127.0.0.1:8000/accounts/login/">http://127.0.0.1:8000/accounts/login/</a></li>
<li><a href="http://127.0.0.1:8000/accounts/logout/">http://127.0.0.1:8000/accounts/logout/</a></li>
</ul>
<p>You'll be able to test the password reset functionality from the link in the login page. <strong>Be aware that Django will only send reset emails to addresses (users) that are already stored in its database!</strong></p>
<div class="note">
<p><strong>Note</strong>: The password reset system requires that your website supports email, which is beyond the scope of this article, so this part <strong>won't work yet</strong>. To allow testing, put the following line at the end of your settings.py file. This logs any emails sent to the console (so you can copy the password reset link from the console).</p>
<pre class="brush: python">EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
</pre>
<p>For more information, see <a href="https://docs.djangoproject.com/en/1.10/topics/email/">Sending email</a> (Django docs).</p>
</div>
<h2 id="Testing_against_authenticated_users">Testing against authenticated users</h2>
<p>This section looks at what we can do to selectively control content the user sees based on whether they are logged in or not.</p>
<h3 id="Testing_in_templates">Testing in templates</h3>
<p>You can get information about the currently logged in user in templates with the <code>\{{ user }}</code> template variable (this is added to the template context by default when you set up the project as we did in our skeleton).</p>
<p>Typically you will first test against the <code>\{{ user.is_authenticated }}</code> template variable to determine whether the user is eligible to see specific content. To demonstrate this, next we'll update our sidebar to display a "Login" link if the user is logged out, and a "Logout" link if they are logged in.</p>
<p>Open the base template (<strong>/locallibrary/catalog/templates/base_generic.html</strong>) and copy the following text into the <code>sidebar</code> block, immediately before the <code>endblock</code> template tag.</p>
<pre class="brush: html"> <ul class="sidebar-nav">
...
<strong>{% if user.is_authenticated %}</strong>
<li>User: <strong>\{{ user.get_username }}</strong></li>
<li><a href="{% url 'logout'%}?next=\{{request.path}}">Logout</a></li>
<strong>{% else %}</strong>
<li><a href="{% url 'login'%}?next=\{{request.path}}">Login</a></li>
<strong>{% endif %} </strong>
</ul></pre>
<p>As you can see, we use <code>if</code>-<code>else</code>-<code>endif</code> template tags to conditionally display text based on whether <code>\{{ user.is_authenticated }}</code> is true. If the user is authenticated then we know that we have a valid user, so we call <strong>\{{ user.get_username }} </strong>to display their name.</p>
<p>We create the login and logout link URLs using the <code>url</code> template tag and the names of the respective URL configurations. Note also how we have appended <code>?next=\{{request.path}}</code> to the end of the URLs. What this does is add a URL parameter <font face="Consolas, Liberation Mono, Courier, monospace">next</font> containing the address (URL) of the <em>current</em> page, to the end of the linked URL. After the user has successfully logged in/out, the views will use this "<code>next</code>" value to redirect the user back to the page where they first clicked the login/logout link.</p>
<div class="note">
<p><strong>Note</strong>: Try it out! If you're on the home page and you click Login/Logout in the sidebar, then after the operation completes you should end up back on the same page.</p>
</div>
<h3 id="Testing_in_views">Testing in views</h3>
<p>If you're using function-based views, the easiest way to restrict access to your functions is to apply the <code>login_required</code> decorator to your view function, as shown below. If the user is logged in then your view code will execute as normal. If the user is not logged in, this will redirect to the login URL defined in the project settings (<code>settings.LOGIN_URL</code>), passing the current absolute path as the <code>next</code> URL parameter. If the user succeeds in logging in then they will be returned back to this page, but this time authenticated.</p>
<pre class="brush: python">from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...</pre>
<div class="note">
<p><strong>Note:</strong> You can do the same sort of thing manually by testing on <code>request.user.is_authenticated</code>, but the decorator is much more convenient!</p>
</div>
<p>Similarly, the easiest way to restrict access to logged-in users in your class-based views is to derive from <code>LoginRequiredMixin</code>. You need to declare this mixin first in the super class list, before the main view class.</p>
<pre class="brush: python">from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, View):
...</pre>
<p>This has exactly the same redirect behaviour as the <code>login_required</code> decorator. You can also specify an alternative location to redirect the user to if they are not authenticated (<code>login_url</code>), and a URL parameter name instead of "<code>next</code>" to insert the current absolute path (<code>redirect_field_name</code>).</p>
<pre class="brush: python">class MyView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
</pre>
<p>For additional detail, check out the <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#limiting-access-to-logged-in-users">Django docs here</a>.</p>
<h2 id="Example_—_listing_the_current_user's_books">Example — listing the current user's books</h2>
<p>Now that we know how to restrict a page to a particular user, lets create a view of the books that the current user has borrowed.</p>
<p>Unfortunately we don't yet have any way for users to borrow books! So before we can create the book list we'll first extend the <code>BookInstance</code> model to support the concept of borrowing and use the Django Admin application to loan a number of books to our test user.</p>
<h3 id="Models">Models</h3>
<p>First we're going to have to make it possible for users to have a <code>BookInstance</code> on loan (we already have a <code>status</code> and a <code>due_back</code> date, but we don't yet have any association between this model and a User. We'll create one using a <code>ForeignKey</code> (one-to-many) field. We also need an easy mechanism to test whether a loaned book is overdue.</p>
<p>Open <strong>catalog/models.py</strong>, and import the <code>User</code> model from <code>django.contrib.auth.models</code> (add this just below the previous import line at the top of the file, so <code>User</code> is available to subsequent code that makes use of it):</p>
<pre class="brush: python">from django.contrib.auth.models import User
</pre>
<p>Next add the <code>borrower</code> field to the <code>BookInstance</code> model:</p>
<pre class="brush: python">borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
</pre>
<p>While we're here, lets add a property that we can call from our templates to tell if a particular book instance is overdue. While we could calculate this in the template itself, using a property as shown below will be much more efficient.</p>
<pre class="brush: python">from datetime import date
@property
def is_overdue(self):
if self.due_back and date.today() > self.due_back:
return True
return False</pre>
<div class="note">
<p><strong>Note</strong>: We first verify whether <code>due_back</code> is empty before making a comparison. An empty <code>due_back</code> field would cause Django to throw an error instead of showing the page: empty values are not comparable. This is not something we would want our users to experience!</p>
</div>
<p>Now that we've updated our models, we'll need to make fresh migrations on the project and then apply those migrations:</p>
<pre class="brush: bash">python3 manage.py makemigrations
python3 manage.py migrate
</pre>
<h3 id="Admin">Admin</h3>
<p>Now open <strong>catalog/admin.py</strong>, and add the <code>borrower</code> field to the <code>BookInstanceAdmin</code> class in both the <code>list_display</code> and the <code>fieldsets</code> as shown below. This will make the field visible in the Admin section, so that we can assign a <code>User</code> to a <code>BookInstance</code> when needed.</p>
<pre class="brush: python">@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_display = ('book', 'status'<strong>, 'borrower'</strong>, 'due_back', 'id')
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book','imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back'<strong>,'borrower'</strong>,)
}),
)</pre>
<h3 id="Loan_a_few_books">Loan a few books</h3>
<p>Now that its possible to loan books to a specific user, go and loan out a number of <code>BookInstance</code> records. Set their <code>borrowed</code> field to your test user, make the <code>status</code> "On loan" and set due dates both in the future and the past.</p>
<div class="note">
<p><strong>Note</strong>: We won't spell the process out, as you already know how to use the Admin site!</p>
</div>
<h3 id="On_loan_view">On loan view</h3>
<p>Now we'll add a view for getting the list of all books that have been loaned to the current user. We'll use the same generic class-based list view we're familiar with, but this time we'll also import and derive from <code>LoginRequiredMixin</code>, so that only a logged in user can call this view. We will also choose to declare a <code>template_name</code>, rather than using the default, because we may end up having a few different lists of BookInstance records, with different views and templates.</p>
<p>Add the following to catalog/views.py:</p>
<pre class="brush: python">from django.contrib.auth.mixins import LoginRequiredMixin
class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
"""
Generic class-based view listing books on loan to current user.
"""
model = BookInstance
template_name ='catalog/bookinstance_list_borrowed_user.html'
paginate_by = 10
def get_queryset(self):
return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')</pre>
<p>In order to restrict our query to just the BookInstance objects for the current user, we re-implement <code>get_queryset()</code> as shown above. Note that "o" is the stored code for "on loan" and we order by the <code>due_back</code> date so that the oldest items are displayed first.</p>
<h3 id="URL_conf_for_on_loan_books">URL conf for on loan books</h3>
<p>Now open <strong>/catalog/urls.py</strong> and add an <code>url()</code> pointing to the above view (you can just copy the text below to the end of the file).</p>
<pre class="brush: python">urlpatterns += [
url(r'^mybooks/$', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'),
]</pre>
<h3 id="Template_for_on_loan_books">Template for on loan books</h3>
<p>Now all we need to do for this page is add a template. First, create the template file <strong>/catalog/templates/catalog/bookinstance_list_borrowed_user.html</strong> and give it the following contents:</p>
<pre class="brush: python">{% extends "base_generic.html" %}
{% block content %}
<h1>Borrowed books</h1>
{% if bookinstance_list %}
<ul>
{% for bookinst in bookinstance_list %}
<li class="{% if bookinst.is_overdue %}text-danger{% endif %}">
<a href="{% url 'book-detail' bookinst.book.pk %}">\{{bookinst.book.title}}</a> (\{{ bookinst.due_back }})
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no books borrowed.</p>
{% endif %}
{% endblock %}</pre>
<p>This template is very similar to those we've created previously for the <code>Book</code> and <code>Author</code> objects. The only thing "new" here is that we check the method we added in the model <code>(bookinst.is_overdue</code>) and use it to change the colour of overdue items.</p>
<p>When the development server is running, you should now be able to view the list for a logged in user in your browser at <a href="http://127.0.0.1:8000/catalog/mybooks/">http://127.0.0.1:8000/catalog/mybooks/</a>. Try this out with your user logged in and logged out (in the second case, you should be redirected to the login page).</p>
<h3 id="Add_the_list_to_the_sidebar">Add the list to the sidebar</h3>
<p>The very last step is to add a link for this new page into the sidebar. We'll put this in the same section where we display other information for the logged in user.</p>
<p>Open the base template (<strong>/locallibrary/catalog/templates/base_generic.html</strong>) and add the line in bold to the sidebar as shown.</p>
<pre class="brush: python"> <ul class="sidebar-nav">
{% if user.is_authenticated %}
<li>User: \{{ user.get_username }}</li>
<strong> <li><a href="{% url 'my-borrowed' %}">My Borrowed</a></li></strong>
<li><a href="{% url 'logout'%}?next=\{{request.path}}">Logout</a></li>
{% else %}
<li><a href="{% url 'login'%}?next=\{{request.path}}">Login</a></li>
{% endif %}
</ul>
</pre>
<h3 id="Nasıl_görünüyor">Nasıl görünüyor?</h3>
<p>Herhangi bir kullanıcı giriş yaptığında, aşağıda görüntülendiği şekilde, kenar çubuğunda <em>My Borrowed</em> bağlantısını ve kitaplar listesini görecekler (ilk kitabın due date'i yok, bir sonraki tutorial'da gidereceğimiz bir bug!).</p>
<p><img alt="Library - borrowed books by user" src="https://mdn.mozillademos.org/files/14105/library_borrowed_by_user.png" style="border-style: solid; border-width: 1px; display: block; height: 215px; margin: 0px auto; width: 530px;"></p>
<h2 id="İzinler">İzinler</h2>
<p>İzinler modellerle ilişklidir ve izni olan bir kullanıcı tarafından bir modele uygulanabilecek operasyonları tanımlar. Varsayılan olarak, Django otomatik olarak tüm modellere <em>add</em>, <em>change</em> ve <em>delete</em> izinlerini verir, which izinli kullanıcıların admin sitesi aracılığıyla ilgili eylemleri uygulamaasını sağlar. You can define your own permissions to models and grant them to specific users. You can also change the permissions associated with different instances of the same model.</p>
<p>Testing on permissions in views and templates is then very similar for testing on the authentication status (and in fact, testing for a permission also tests for authentication).</p>
<h3 id="Models_2">Models</h3>
<p>Defining permissions is done on the model "<code>class Meta</code>" section, using the <code>permissions</code> field. You can specify as many permissions as you need in a tuple, each permission itself being defined in a nested tuple containing the permission name and permission display value. For example, we might define a permission to allow a user to mark that a book has been returned as shown:</p>
<pre class="brush: python">class BookInstance(models.Model):
...
class Meta:
...
<strong> permissions = (("can_mark_returned", "Set book as returned"),) </strong> </pre>
<p>We could then assign the permission to a "Librarian" group in the Admin site.</p>
<p>Open the <strong>catalog/models.py</strong>, and add the permission as shown above. You will need to re-run your migrations (call <code>python3 manage.py makemigrations</code> and <code>python3 manage.py migrate</code>) to update the database appropriately.</p>
<h3 id="Templates">Templates</h3>
<p>The current user's permissions are stored in a template variable called <code>\{{ perms }}</code>. You can check whether the current user has a particular permission using the specific variable name within the associated Django "app" — e.g. <code>\{{ perms.catalog.can_mark_returned }}</code> will be <code>True</code> if the user has this permission, and <code>False</code> otherwise. We typically test for the permission using the template <code>{% if %}</code> tag as shown:</p>
<pre class="brush: python">{% if perms.catalog.<code>can_mark_returned</code> %}
<!-- We can mark a BookInstance as returned. -->
<!-- Perhaps add code to link to a "book return" view here. -->
{% endif %}
</pre>
<h3 id="Views">Views</h3>
<p>Permissions can be tested in function view using the <code>permission_required</code> decorator or in a class-based view using the <code>PermissionRequiredMixin</code>. The pattern and behaviour are the same as for login authentication, though of course you might reasonably have to add multiple permissions.</p>
<p>Function view decorator:</p>
<pre class="brush: python">from django.contrib.auth.decorators import permission_required
@permission_required('catalog.<code>can_mark_returned</code>')
@permission_required('catalog.<code>can_edit</code>')
def my_view(request):
...</pre>
<p>Permission-required mixin for class-based views.</p>
<pre class="brush: python">from django.contrib.auth.mixins import PermissionRequiredMixin
class MyView(PermissionRequiredMixin, View):
permission_required = 'catalog.<code>can_mark_returned</code>'
# Or multiple permissions
permission_required = ('catalog.<code>can_mark_returned</code>', 'catalog.can_edit')
# Note that 'catalog.can_edit' is just an example
# the catalog application doesn't have such permission!</pre>
<h3 id="Example">Example</h3>
<p>We won't update the <em>LocalLibrary</em> here; perhaps in the next tutorial!</p>
<h2 id="Challenge_yourself">Challenge yourself</h2>
<p>Earlier in this article we showed you how to create a page for the current user listing the books that they have borrowed. The challenge now is to create a similar page that is only visible for librarians, that displays <em>all</em> books that have been borrowed, and which includes the name of each borrower.</p>
<p>You should be able to follow the same pattern as for the other view. The main difference is that you'll need to restrict the view to only librarians. You could do this based on whether the user is a staff member (function decorator: <code>staff_member_required</code>, template variable: <code>user.is_staff</code>) but we recommend that you instead use the <code>can_mark_returned</code> permission and <code>PermissionRequiredMixin</code>, as described in the previous section.</p>
<div class="warning">
<p><strong>Important</strong>: Remember not to use your superuser for permissions based testing (permission checks always return true for superusers, even if a permission has not yet been defined!). Instead create a librarian user, and add the required capability.</p>
</div>
<p>When you are finished, your page should look something like the screenshot below.</p>
<p><img alt="All borrowed books, restricted to librarian" src="https://mdn.mozillademos.org/files/14115/library_borrowed_all.png" style="border-style: solid; border-width: 1px; display: block; height: 283px; margin: 0px auto; width: 500px;"></p>
<ul>
</ul>
<h2 id="Summary">Summary</h2>
<p>Excellent work — you've now created a website that library members can login into and view their own content, and that librarians (with the correct permission) can use to view all loaned books and their borrowers. At the moment we're still just viewing content, but the same principles and techniques are used when you want to start modifying and adding data.</p>
<p>In our next article we'll look at how you can use Django forms to collect user input, and then start modifying some of our stored data.</p>
<h2 id="See_also">See also</h2>
<ul>
<li><a href="https://docs.djangoproject.com/en/1.10/topics/auth/">User authentication in Django</a> (Django docs)</li>
<li><a href="https://docs.djangoproject.com/en/1.10/topics/auth/default//">Using the (default) Django authentication system</a> (Django docs)</li>
<li><a href="https://docs.djangoproject.com/en/1.10/topics/class-based-views/intro/#decorating-class-based-views">Introduction to class-based views > Decorating class-based views</a> (Django docs)</li>
</ul>
<p>{{PreviousMenuNext("Learn/Server-side/Django/Sessions", "Learn/Server-side/Django/Forms", "Learn/Server-side/Django")}}</p>
|