diff options
author | Ryan Johnson <rjohnson@mozilla.com> | 2021-04-29 16:16:42 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-04-29 16:16:42 -0700 |
commit | 95aca4b4d8fa62815d4bd412fff1a364f842814a (patch) | |
tree | 5e57661720fe9058d5c7db637e764800b50f9060 /files/tr/learn/server-side | |
parent | ee3b1c87e3c8e72ca130943eed260ad642246581 (diff) | |
download | translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.gz translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.bz2 translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.zip |
remove retired locales (#699)
Diffstat (limited to 'files/tr/learn/server-side')
-rw-r--r-- | files/tr/learn/server-side/django/authentication/index.html | 678 | ||||
-rw-r--r-- | files/tr/learn/server-side/django/index.html | 73 | ||||
-rw-r--r-- | files/tr/learn/server-side/django/sessions/index.html | 183 | ||||
-rw-r--r-- | files/tr/learn/server-side/django/skeleton_website/index.html | 395 | ||||
-rw-r--r-- | files/tr/learn/server-side/index.html | 53 |
5 files changed, 0 insertions, 1382 deletions
diff --git a/files/tr/learn/server-side/django/authentication/index.html b/files/tr/learn/server-side/django/authentication/index.html deleted file mode 100644 index d7f0ccc57d..0000000000 --- a/files/tr/learn/server-side/django/authentication/index.html +++ /dev/null @@ -1,678 +0,0 @@ ---- -title: 'Django Tutorial - 8. Bölüm: Kullanıcı doğrulama ve izinler' -slug: Learn/Server-side/Django/Authentication -translation_of: Learn/Server-side/Django/Authentication -original_slug: Öğren/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> diff --git a/files/tr/learn/server-side/django/index.html b/files/tr/learn/server-side/django/index.html deleted file mode 100644 index e86962900e..0000000000 --- a/files/tr/learn/server-side/django/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Django Web Framework (Python) -slug: Learn/Server-side/Django -tags: - - Beginner - - CodingScripting - - Intro - - Learn - - NeedsTranslation - - Python - - Server-side programming - - TopicStub - - django -translation_of: Learn/Server-side/Django -original_slug: Öğren/Server-side/Django ---- -<p>{{draft("Contact Hamish Willee via ~~chrisdavidmills if you have any questions about this work.")}}</p> - -<p class="summary">Django is an extremely popular and fully featured server-side web framework, written in Python. The module shows you why Django is one of the most popular web server frameworks, how to set up a development environment, and how to get started with using it to create your own web applications.</p> - -<h2 id="Prerequisites">Prerequisites</h2> - -<p>Before starting this module you don't need to have any knowledge of Django. You will need to understand what server-side web programming and web frameworks are, ideally by reading the topics in our <a href="/en-US/docs/Learn/Server-side/First_steps">Server-side website programming first steps</a> module.</p> - -<p>A general knowledge of programming concepts and <a href="/en-US/docs/Glossary/Python">Python</a> is recommended, but not essential to understanding the core concepts.</p> - -<div class="note"> -<p><strong>Note</strong>: Python is one of the easiest programming languages for novices to read and understand. That said, if you want to understand this module better then there are numerous free books and tutorials available on the Internet (new programmers might want to check out the <a href="https://wiki.python.org/moin/BeginnersGuide/NonProgrammers">Python for Non Programmers</a> page on the python.org wiki).</p> -</div> - -<h2 id="Guides">Guides</h2> - -<dl> - <dt><a href="/en-US/docs/Learn/Server-side/Django/Introduction">Django Introduction</a></dt> - <dd>In this first Django article we answer the question "What is Django?" and give you an overview of what makes this web framework special. We'll outline the main features, including some of the advanced functionality that we won't have time to cover in detail in this module. We'll also show you some of the main building blocks of a Django application, to give you an idea of what it can do before you then go on to set it up and start playing.</dd> - <dt><a href="/en-US/docs/Learn/Server-side/Django/development_environment">Setting up a Django development environment</a></dt> - <dd>Now that you know what Django is for, we'll show you how to setup and test a Django development environment on Windows, Linux (Ubuntu), and Mac OS X — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps.</dd> - <dt><a href="/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">Django Tutorial — The Local Library website</a></dt> - <dd>The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.</dd> - <dt><a href="/en-US/docs/Learn/Server-side/Django/skeleton_website">Django Tutorial Part 2: Creating a skeleton website</a></dt> - <dd>This article shows how you can create a "skeleton" website project as a basis, which you can then go on to populate with site-specific settings, urls, models, views, and templates.</dd> - <dt><a href="/en-US/docs/Learn/Server-side/Django/Models">Django Tutorial Part 3: Using models</a></dt> - <dd>This article shows how to define models for the <em>LocalLibrary</em> website — models represent the data structures we want to store our app's data in, and also allow Django to store data in a database for us (and modify it later on). It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data.</dd> - <dt><a href="/en-US/docs/Learn/Server-side/Django/Admin_site">Django Tutorial Part 4: Django admin site</a></dt> - <dd>Now that we've created models for the <em>LocalLibrary </em>website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to login and create some data. At the end we show some of ways you can further improve the presentation of the admin site.</dd> - <dt><a href="/en-US/docs/Learn/Server-side/Django/Home_page">Django Tutorial Part 5: Creating our home page</a></dt> - <dd>We're now ready to add the code to display our first full page — a home page for the <em>LocalLibrary</em> that shows how many records we have of each model type and provides sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates.</dd> - <dt><a href="/en-US/docs/Learn/Server-side/Django/Generic_views">Django Tutorial Part 6: Generic list and detail views</a></dt> - <dd>This tutorial extends our <em>LocalLibrary</em> website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching.</dd> - <dt><a href="/en-US/docs/Learn/Server-side/Django/Sessions">Django Tutorial Part 7: Sessions framework</a></dt> - <dd>This tutorial extends our <em>LocalLibrary</em> website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does shows how you can use the session framework to provide peristent behaviour for anonymous users in your own sites.</dd> - <dt><a href="/en-US/docs/Learn/Server-side/Django/authentication_and_sessions">Django Tutorial Part 8: User authentication and permissions</a></dt> - <dd>In this tutorial we'll show you how to allow users to login to your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their <em>permissions</em>. As part of this demonstration we'll extend the <em>LocalLibrary</em> website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed.</dd> - <dd> </dd> - <dt>Forms (TBD)</dt> - <dd><a href="/en-US/docs/Web/Guide/HTML/Forms">HTML Forms</a> are used to collect user data and send it to a website for processing. Form handling can be complicated, and includes creating the HTML code for the form, validating the entered data on both the client and server, processing/storing the returned data, and returning a response. Django simplifies much of this work, and is even capable of reusing data defined in the model for creating a form — this article shows how.</dd> - <dt> </dt> - <dt>Testing Django code (TBD)</dt> - <dd>For very basic sites with only a few lines of code, you may be able to get away with manual testing. As your site gets larger, an automated test suite can help to validate new code as it is written and is the only practical way to ensure that changes to not introduce new bugs. This article provides a very brief overview of the recommended way to write and run unit tests in your Django web application.</dd> - <dt>Django web application security (TBD)</dt> - <dd>Protecting user data is an essential part of any website design. We already explained some of the more common security threats in the topic <a href="/en-US/docs/Web/Security">Web security</a> — this article builds on that information, providing a brief overview of the security features that are provided for Django users out of the box.</dd> - <dt>Deployment to production (TBD)</dt> - <dd>Now that your web application is finished, you will want to upload it to a production server. To make this easier, here we help you find a hosting site that might meet your budget and scaling needs. We then explain some of the changes you need to make to hide any "development settings". Last of all we provide a real "worked example" of how you can install a web application, using hosting on the free tier of the <a href="https://www.heroku.com/">Heroku</a> cloud hosting service.</dd> -</dl> - -<h2 id="Assessments">Assessments</h2> - -<p>The following assessment will test your understanding of how to create a website using Django, as described in the guides listed above</p> - -<dl> - <dt>DIY Mini Blog (TBD)</dt> - <dd>In this assessment you'll use some of the knowledge you've learned from this module to create your own blog.</dd> -</dl> diff --git a/files/tr/learn/server-side/django/sessions/index.html b/files/tr/learn/server-side/django/sessions/index.html deleted file mode 100644 index 9394b62737..0000000000 --- a/files/tr/learn/server-side/django/sessions/index.html +++ /dev/null @@ -1,183 +0,0 @@ ---- -title: 'Django Tutorial Part 7: Sessions framework' -slug: Learn/Server-side/Django/Sessions -tags: - - Başlangıç - - CondingScripting - - Makale - - Python - - Server - - Sunucu - - Tutorial - - django - - django oturumları - - django sessions - - oturumlar - - server-side - - sessions - - sunucu tarafı - - Öğretici - - öğren -translation_of: Learn/Server-side/Django/Sessions -original_slug: Öğren/Server-side/Django/Sessions ---- -<div>{{LearnSidebar}}</div> - -<div>{{PreviousMenuNext("Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django/authentication_and_sessions", "Learn/Server-side/Django")}}</div> - -<p class="summary">Bu tutorial, anasayfaya session temelli bir ziyareti sayacı ekleyerek <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">LocalLibrary</a> websitemizi genişletmektedir. Bu görece basit bir örnek, fakat kendi sitelerinizdeki bilinmeyen kullanıcılar için kalıcı davranış sağlamak için session framework'ünü nasıl kullanacağınızı göstermektedir.</p> - -<table class="learn-box standard-table"> - <tbody> - <tr> - <th scope="row">Ön şartlar:</th> - <td><a href="/en-US/docs/Learn/Server-side/Django/Generic_views">Django Tutorial 6. Bölüm: Generic list ve detail view'lar</a> dahil önceki tüm tutorial konularını tamamlayın</td> - </tr> - <tr> - <th scope="row">Amaç:</th> - <td>Session'ların nasıl kullanıldığını anlamak.</td> - </tr> - </tbody> -</table> - -<h2 id="Genel_Bakış">Genel Bakış</h2> - -<p>Önceki tutorial'larda oluşturduğumuz <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">LocalLibrary</a> websitesi, kullanıcıların katalogdaki kitap ve yazarlara göz atmalarını sağlar. İçerik, veri tabanından dinamik olarak üretilirken, tüm kullanıcılar siteyi kullandıklarında esasen aynı sayfalar ve bilgi türlerine erişebilecektir.</p> - -<p>"Gerçek" bir kütüphanede, her bir kullanıcıya önceki kullanım ve tercihlerini vs. temel alarak kişiselleştirilmiş bir deneyim sunmayı isteyebilirsiniz. Örneğin, kullanıcının daha önce kabul ettiği uyarı iletilerini siteyi veya mağazayı bir sonraki ziyaret edişlerinde gizleyebilir ve tercihlerine (örn. her bir sayfada görüntülenmesini istedikleri arama sonucu sayısı gibi) saygı duyabilirsiniz. </p> - -<p>Session framework'ü her bir site ziyaretçisine dayalı keyfi veriler depolamanızı ve geri almanızı sağlayarak, bu tür davranışları uygulamanızı sağlar. </p> - -<h2 id="Sessions_Nedir">Sessions Nedir?</h2> - -<p>Web tarayıcılar ve sunucular arasındaki tüm iletişim, <em>stateless</em> bir HTTP protokolü aracılığıyladır. Protokolün stateless oluşundan kasıt, client ve server arasındaki iletilerin birbirlerinden tamamen bağımsız olduğudur— önceki iletilere dayalı davranış veya "dizi" kavramı bulunmamaktadır. Sonuç olarak, <span class="translation">bir istemci ile devam eden ilişkileri takip eden bir siteye sahip olmak istiyorsanız</span>, bunu kendiniz uygulamanız gerekiyor.</p> - -<p>Sessions are the mechanism used by Django (and most of the Internet) for keeping track of the "state" between the site and a particular browser. Session'lar her bir tarayıcı için keyfi veriler depolamanızı sağlar ve <span class="translation">tarayıcı bağlandığında bu verileri sitede bulabilirsiniz</span>. Session ile ilişkili her bir veri öğesi Individual data items associated with the session are then referenced by a "key", which is used both to store and retrieve the data.</p> - -<p>Django uses a cookie containing a special <em>session id</em> to identify each browser and its associated session with the site. The actual session <em>data</em> is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users). You can configure Django to store the session data in other places (cache, files, "secure" cookies), but the default location is a good and relatively secure option.</p> - -<h2 id="Session'ları_Etkinleştirme">Session'ları Etkinleştirme</h2> - -<p>Sessions <a href="/en-US/docs/Learn/Server-side/Django/skeleton_website">iskelet websitesini oluşturduğumuzda</a> (tutorial 2'de) otomatik olarak etkinleştirilir.</p> - -<p>Aşağıda görüldüğü 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ına kurulur:</p> - -<pre class="brush: python">INSTALLED_APPS = [ - ... -<strong> 'django.contrib.sessions',</strong> - .... - -MIDDLEWARE = [ - ... -<strong> 'django.contrib.sessions.middleware.SessionMiddleware',</strong> - ....</pre> - -<h2 id="Session'ları_Kullanma">Session'ları Kullanma</h2> - -<p>You can access the <code>session</code> attribute in the view from the <code>request</code> parametresi (an <code>HttpRequest</code> passed in as the first argument to the view). This session attribute represents the specific connection to the current user (or to be more precise, the connection to the current <em>browser</em>, as identified by the session id in the browser's cookie for this site).</p> - -<p><code>session</code> attribute'u view'ınızda istediğiniz kadar yazıp okuyabileceğiniz sözlük benzeri bir nesne olup, dilediğiniz gibi değiştirilebilirdir. You can do all the normal dictionary operations, including clearing all data, testing if a key is present, looping through data, etc. Most of the time though, you'll just use the standard "dictionary" API to get and set values.</p> - -<p>The code fragments below show how you can get, set, and delete some data with the key "<code>my_car</code>", associated with the current session (browser). </p> - -<div class="note"> -<p><strong>Note</strong>: One of the great things about Django is that you don't need to think about the mechanisms that tie the session to your current request in your view. If we were to use the fragments below in our view, we'd know that the information about <code>my_car</code> is associated only with the browser that sent the current request.</p> -</div> - -<pre class="brush: python"># Get a session value by its key (e.g. 'my_car'), raising a KeyError if the key is not present -my_car = request.session['my_car'] - -# Get a session value, setting a default if it is not present ('mini') -my_car = request.session.get('my_car', 'mini') - -# Set a session value -request.session['my_car'] = 'mini' - -# Delete a session value -del request.session['my_car'] -</pre> - -<p>The API also offers a number of other methods that are mostly used to manage the associated session cookie. For example, there are methods to test that cookies are supported in the client browser, to set and check cookie expiry dates, and to clear expired sessions from the data store. You can find out about the full API in <a href="https://docs.djangoproject.com/en/1.10/topics/http/sessions/">How to use sessions</a> (Django belgeleri).</p> - -<h2 id="Session_Verisini_Kaydetmek">Session Verisini Kaydetmek</h2> - -<p>Varsayılan olarak, Django yalnızca session veri tabanını kaydeder ve session <em>değiştirildiğinde</em> veya <em>silindiğinde</em> istemciye session çerezini gönderir. Önceki kısımlarda görüldüğü gibi session anahtarını kullanarak bazı verileri güncellerseniz, sonrasında bu konuda endişelenmenize gerek kalmaz! Örneğin:</p> - -<pre class="brush: python"># This is detected as an update to the session, so session data is saved. -request.session['my_car'] = 'mini'</pre> - -<p>Session verisi <em>içersinde</em> bazı bilgileri güncellerseniz, sonrasında Django session'a bir değişiklik yaptığınızı ve veriyi kaydettiğinizi fark etmeyecektir (örneğin, aşağıda gösterildiği gibi, "<code>my_car</code>" verinizin içerisindeki "<code>wheels</code>" verinizi değiştirmek üzereyseniz). Bu durumda session'ı açık bir şekilde değiştirilmiş olarak işaretlemeniz gerekecektir.</p> - -<pre class="brush: python"># Session object not directly modified, only data within the session. Session changes not saved! -request.session['my_car']['wheels'] = 'alloy' - -# Set session as modified to force data updates/cookie to be saved. -<code>request.session.modified = True</code> -</pre> - -<div class="note"> -<p><strong>Not</strong>: Davranışı değiştirebilirsiniz; böylece site veri tabanını güncelleyecek/proje ayarlarınıza (<strong>locallibrary/locallibrary/settings.py</strong>) <code>SESSION_SAVE_EVERY_REQUEST = True</code> komutunu ekleyerek her bir request'teki çerezi gönderecektir.</p> -</div> - -<h2 id="Basit_Örnek_—_Ziyaret_Sayısını_Almak">Basit Örnek — Ziyaret Sayısını Almak</h2> - -<p>Basit bir gerçek dünya örneği olarak, mevcut kullanıcıya <em>LocalLibrary</em> anasayfasını kaç kere ziyaret ettiklerini söyleyemesi için kütüphanemizi güncelleyeceğiz.</p> - -<p><strong>/locallibrary/catalog/views.py</strong> dosyasını açın ve aşağıda kalın olarak gösterilen değişiklikleri yapın. </p> - -<pre class="brush: python">def index(request): - ... - - num_authors=Author.objects.count() # The 'all()' is implied by default. - -<strong> # Number of visits to this view, as counted in the session variable. - num_visits=request.session.get('num_visits', 0) - request.session['num_visits'] = num_visits+1</strong> - - # Render the HTML template index.html with the data in the context variable. - return render( - request, - 'index.html', -<strong> context={'num_books':num_books,'num_instances':num_instances,'num_instances_available':num_instances_available,'num_authors':num_authors, - 'num_visits':num_visits}, # num_visits appended</strong> - )</pre> - -<p>Here we first get the value of the <code>'num_visits'</code> session key, setting the value to 0 if it has not previously been set. Each time a request is received, we then increment the value and store it back in the session (for the next time the user visits the page). The <code>num_visits</code> variable is then passed to the template in our context variable. </p> - -<div class="note"> -<p><strong>Note</strong>: We might also test whether cookies are even supported in the browser here (see <a href="https://docs.djangoproject.com/en/1.10/topics/http/sessions/">How to use sessions</a> for examples) or design our UI so that it doesn't matter whether or not cookies are supported.</p> -</div> - -<p>Add the line seen at the bottom of the following block to your main HTML template (<strong>/locallibrary/catalog/templates/index.html</strong>) at the bottom of the "Dynamic content" section to display the context variable:</p> - -<pre class="brush: html"><h2>Dynamic content</h2> - -<p>The library has the following record counts:</p> -<ul> -<li><strong>Books:</strong> \{{ num_books }}</li> -<li><strong>Copies:</strong> \{{ num_instances }}</li> -<li><strong>Copies available:</strong> \{{ num_instances_available }}</li> -<li><strong>Authors:</strong> \{{ num_authors }}</li> -</ul> - -<strong><p>You have visited this page \{{ num_visits }}{% if num_visits == 1 %} time{% else %} times{% endif %}.</p></strong> -</pre> - -<p>Değişikliklerinizi kaydedin ve test sunucusunu yeniden başlatın. Sayfayı her yenilediğinizde, numara güncellenmelidir.</p> - -<ul> -</ul> - -<h2 id="Özet">Özet</h2> - -<p><em>Bilinmeyen</em> kullanıcılarla etkileşiminizi arttırmak için oturumları kullanmanın ne kadar kolay olduğunu artık biliyorsunuz.</p> - -<p>Sıradaki makalelerimizde, authentication ve authorisation (izin) framework'ünü açıklayacağız ve kullanıcı hesaplarını nasıl destekleyeceğinizi göstereceğiz.</p> - -<h2 id="Ayrıca_bakın">Ayrıca bakın</h2> - -<ul> - <li><a href="https://docs.djangoproject.com/en/1.10/topics/http/sessions/">Session'lar nasıl kullanılır</a> (Django belgeleri)</li> -</ul> - -<p>{{PreviousMenuNext("Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django/Authentication", "Learn/Server-side/Django")}}</p> diff --git a/files/tr/learn/server-side/django/skeleton_website/index.html b/files/tr/learn/server-side/django/skeleton_website/index.html deleted file mode 100644 index 1c617bcc75..0000000000 --- a/files/tr/learn/server-side/django/skeleton_website/index.html +++ /dev/null @@ -1,395 +0,0 @@ ---- -title: 'Django Tutorial 2. Bölüm: Websitesi İskeleti Oluşturmak' -slug: Learn/Server-side/Django/skeleton_website -translation_of: Learn/Server-side/Django/skeleton_website -original_slug: Öğren/Server-side/Django/website_iskeleti ---- -<div>{{LearnSidebar}}</div> - -<div>{{PreviousMenuNext("Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django/Models", "Learn/Server-side/Django")}}</div> - -<p class="summary"><a href="/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">Django Tutorial</a> serimizin ikinci yazısında, içine siteye özgü ayarları, path'leri, model'leri, view'ları ve template'leri yerleştireceğimiz bir websitesi projesinin "iskelet"ini nasıl oluşturağınızı anlatacağız.</p> - -<table class="learn-box standard-table"> - <tbody> - <tr> - <th scope="row">Gereksinimler:</th> - <td><a href="/en-US/docs/Learn/Server-side/Django/development_environment">Django geliştirme ortamı kur</a>. <a href="/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">Django Tutorial</a>'i gözden geçir.</td> - </tr> - <tr> - <th scope="row">Amaç:</th> - <td>Kendi website projelerinizi oluşturmak için Django araçlarını kullanabilmek</td> - </tr> - </tbody> -</table> - -<h2 id="Genel_Bakış">Genel Bakış</h2> - -<p>Bu yazıda, içine siteye özgü ayarları, path'leri, model'leri, view'ları ve template'leri(bunlardan sonra bahsedeceğiz) yerleştireceğimiz bir websitesi projesinin "iskelet"ini nasıl oluşturağınızı anlatacağız..</p> - -<p>Süreç gayet açık:</p> - -<ol> - <li><code style="font-style: normal; font-weight: normal; line-height: 1.5;">django-admin</code><span style="line-height: 1.5;"> tool to create the project folder, basic file templates, and project management script (</span><strong style="line-height: 1.5;">manage.py</strong><span style="line-height: 1.5;">).</span></li> - <li><span style="line-height: 1.5;">Use </span><strong style="line-height: 1.5;">manage.py</strong><span style="line-height: 1.5;"> to create one or more </span><em>applications</em><span style="line-height: 1.5;">.</span> - <div class="note"> - <p><strong>Note</strong>: A website may consist of one or more sections, e.g. main site, blog, wiki, downloads area, etc. Django encourages you to develop these components as separate <em>applications</em>, which could then be re-used in different projects if desired. </p> - </div> - </li> - <li><span style="line-height: 1.5;">Register the new applications to include them in the project. </span></li> - <li><span style="line-height: 1.5;">Hook up the url/path mapper for each application.</span></li> -</ol> - -<p>For the <a href="/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">Local Library website</a> the website folder and its project folder will be named <em>locallibrary</em>, and we'll have just one application named <em>catalog</em>. The top level folder structure will therefore be as follows:</p> - -<pre class="brush: bash"><em>locallibrary/ # Website folder</em> - <strong>manage.py </strong># Script to run Django tools for this project (created using django-admin) - <em>locallibrary/ # Website/project folder </em>(created using django-admin) - <em>catalog/ # Application folder </em>(created using manage.py) -</pre> - -<p><span style="line-height: 1.5;">The following sections discuss the process steps in detail, and show how you can test the changes. At the end of the article we discuss some of the other site-wide configuration you might also do at this stage.</span></p> - -<h2 id="Projeyi_Oluşturma">Projeyi Oluşturma</h2> - -<p>İlk olarak komut istemi/terminali açın, <a href="/en-US/docs/Learn/Server-side/Django/development_environment#Using_a_virtual_environment">sanal ortamda</a> olduğunuza emin olun, Django uygulamalarının bulunmasını istediğiniz yeri açın(<code>cd</code> komutuyla)<span style="line-height: 1.5;"> (<em>belgeler </em>klasörü gibi kolay bulabileceğiniz bir yer olsun) ve yeni websiteniz için yeni bir klasör oluşturun (biz </span><em>django_projects </em>olarak oluşturduk). Sonra <code>cd</code> komutuyla o klasöre girin:</p> - -<pre class="brush: bash">mkdir django_projects -cd django_projects</pre> - -<p>Gösterildiği gibi <code>django-admin startproject</code> komutuyla yeni projeyi oluşturun ve sonra klasörün içine girin.</p> - -<pre class="brush: bash">django-admin startproject locallibrary -cd locallibrary</pre> - -<p><code>django-admin</code> aracı aşağıda görünen şekilde bir klasör/dosya yapısı oluşturur:</p> - -<pre class="brush: bash"><em>locallibrary/</em> - manage.py - <em>locallibrary/</em> - __init__.py - settings.py - urls.py - wsgi.py</pre> - -<p>Bizim çalıştığımız klasör şuna benzer şekilde görünmeli:</p> - -<pre class="syntaxbox">../django_projects/locallibrary/</pre> - -<p><em>locallibrary</em> proje altklasörü websitemiz için giriş noktası:</p> - -<ul> - <li><strong>__init__.py </strong>Python'a bu klasöre Python paketi olarak davranması gerektiğini söyleyen boş bir dosya.</li> - <li><strong>settings.py</strong> tüm website ayarlarının olduğu dosya. Buraya oluşturduğumuz uygulamaları, static dosyalarımızın bulunduğu yeri, veritabanı ayarlarını vs. kaydederiz. </li> - <li><strong>urls.py</strong> sitemizin url-view eşlemelerinin tanımladığımız yer. Burada tüm url eşlemelerini tanımlayabilsek de bazı eşlemeleri ileride göreceğimiz gibi uygulamalara bölmek daha yaygın kullanılır<span style="line-height: 1.5;">. </span></li> - <li><strong style="line-height: 1.5;">wsgi.py</strong><span style="line-height: 1.5;"> Django uygulamamızın web sunucusuyla iletişim kurmasına yardım eder. Şablon olarak düşünebilirsiniz.</span></li> -</ul> - -<p><strong>manage.py</strong> betiği(script) uygulama oluşturmakta, veritabanı işlemlerinde ve geliştirme ortamı sunucusunu(yerel sunucu: 127.0.0.1:8000) başlatmakta kullanılır. </p> - -<h2 id="Catalog_uygulamasını_oluşturma">Catalog uygulamasını oluşturma</h2> - -<p><em>locallibrary </em>projemizin içinde duracak olan <em>catalog</em> uygulamasını oluşturmak için aşağıdaki komutu çalıştırın (projemizin <strong>manage.py </strong>betiğinin de bulunduğu klasörde çalıştırılmalı):</p> - -<pre class="brush: bash">python3 manage.py startapp catalog</pre> - -<div class="note"> -<p><strong>Not</strong>: Yukarıdaki komut Linux/macOS X içindir. Windows'taki komut şu şekilde olmalı: <code>py -3 manage.py startapp catalog</code></p> - -<p>Windows kullanıyorsanız, bu modül boyunca <code>python3</code> yerine <code>py -3</code> yazmalısınız.</p> - -<p>Python 3.7.0 kullanıyorsanız sadece <code>py manage.py startapp catalog</code> kullanmalısınız.</p> -</div> - -<p>Bu araç yeni bir klasör oluşturup içini uygulamamızın muhtelif kısımları için kullanılacak dosyalarla(aşağıda kalın olarak yazıldı) doldurur. Dosyaların çoğu amaçlarına uygun olarak isimlendirilmiştir (mesela view'lar <strong>views.py'</strong>da, Model'ler <strong>models.py'</strong>da, test'ler <strong>tests.py'</strong>da, site yönetim sayfası ayarları <strong>admin.py'</strong>da, uygulama kayıtları <strong>apps.py'</strong>da bulunur). Ayrıca bu dosyalar ilişkili oldukları nesnelerle çalışırken kullanılabilecek minimal bir kod şablonu da içerir.</p> - -<p>Proje klasörünün son hali şu şekilde görünmeli:</p> - -<pre class="brush: bash"><em>locallibrary/</em> - manage.py - <em>locallibrary/ -</em><strong> <em>catalog/</em> - admin.py - apps.py - models.py - tests.py - views.py - __init__.py - <em>migrations/</em></strong> -</pre> - -<p>In addition we now have:</p> - -<ul> - <li>A <em>migrations</em> folder, used to store "migrations" — files that allow you to automatically update your database as you modify your models. </li> - <li><strong>__init__.py</strong> — an empty file created here so that Django/Python will recognise the folder as a <a href="https://docs.python.org/3/tutorial/modules.html#packages">Python Package</a> and allow you to use its objects within other parts of the project.</li> -</ul> - -<div class="note"> -<p><strong>Note</strong>: Have you noticed what is missing from the files list above? While there is a place for your views and models, there is nowhere for you to put your url mappings, templates, and static files. We'll show you how to create them further along (these aren't needed in every website but they are needed in this example).</p> -</div> - -<h2 id="Registering_the_catalog_application">Registering the catalog application</h2> - -<p>Now that the application has been created we have to register it with the project so that it will be included when any tools are run (for example to add models to the database). Applications are registered by adding them to the <code>INSTALLED_APPS</code> list in the project settings. </p> - -<p>Open the project settings file <strong>django_projects/locallibrary/locallibrary/settings.py</strong> and find the definition for the <code>INSTALLED_APPS</code> list. Then add a new line at the end of the list, as shown in bold below.</p> - -<pre class="brush: bash">INSTALLED_APPS = [ - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', -<strong> 'catalog.apps.CatalogConfig', </strong> -]</pre> - -<p>The new line specifies the application configuration object (<code>CatalogConfig</code>) that was generated for you in <strong>/locallibrary/catalog/apps.py</strong> when you created the application.</p> - -<div class="note"> -<p><strong>Note</strong>: You'll notice that there are already a lot of other <code>INSTALLED_APPS</code> (and <code>MIDDLEWARE</code>, further down in the settings file). These enable support for the <a href="/en-US/docs/Learn/Server-side/Django/Admin_site">Django administration site</a> and as a result lots of the functionality it uses (including sessions, authentication, etc).</p> -</div> - -<h2 id="Specifying_the_database">Specifying the database</h2> - -<p>This is also the point where you would normally specify the database to be used for the project — it makes sense to use the same database for development and production where possible, in order to avoid minor differences in behaviour. You can find out about the different options in <a href="https://docs.djangoproject.com/en/2.0/ref/settings/#databases">Databases</a> (Django docs). </p> - -<p>We'll use the SQLite database for this example, because we don't expect to require a lot of concurrent access on a demonstration database, and also because it requires no additional work to set up! You can see how this database is configured in <strong>settings.py</strong> (more information is also included below):</p> - -<pre class="brush: python">DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), - } -} -</pre> - -<p>Because we are using SQLite, we don't need to do any further setup here. Let's move on!</p> - -<h2 id="Other_project_settings">Other project settings</h2> - -<p>The <strong>settings.py</strong> file is also used for configuring a number of other settings, but at this point you probably only want to change the <a href="https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-TIME_ZONE">TIME_ZONE</a> — this should be made equal to a string from the standard <a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">List of tz database time zones</a> (the TZ column in the table contains the values you want). Change your <code>TIME_ZONE</code> value to one of these strings appropriate for your time zone, for example:</p> - -<pre class="brush: python">TIME_ZONE = 'Europe/London'</pre> - -<p>There are two other settings you won't change now, but that you should be aware of:</p> - -<ul> - <li><code>SECRET_KEY</code>. This is a secret key that is used as part of Django's website security strategy. If you're not protecting this code in development, you'll need to use a different code (perhaps read from an environment variable or file) when putting it into production. </li> - <li><code>DEBUG</code>. This enables debugging logs to be displayed on error, rather than HTTP status code responses. This should be set to <code>False</code> on production as debug information is useful for attackers, but for now we can keep it set to <code>True</code>.</li> -</ul> - -<h2 id="Hooking_up_the_URL_mapper">Hooking up the URL mapper</h2> - -<p>The website is created with a URL mapper file (<strong>urls.py</strong>) in the project folder. While you can use this file to manage all your URL mappings, it is more usual to defer mappings to the associated application.</p> - -<p>Open <strong>locallibrary/locallibrary/urls.py</strong> and note the instructional text which explains some of the ways to use the URL mapper. </p> - -<pre class="brush: python">"""locallibrary URL Configuration - -The `urlpatterns` list routes URLs to views. For more information please see: - https://docs.djangoproject.com/en/2.0/topics/http/urls/ -Examples: -Function views - 1. Add an import: from my_app import views - 2. Add a URL to urlpatterns: path('', views.home, name='home') -Class-based views - 1. Add an import: from other_app.views import Home - 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') -Including another URLconf - 1. Import the include() function: from django.urls import include, path - 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) -""" -from django.contrib import admin -from django.urls import path - -urlpatterns = [ - path('admin/', admin.site.urls), -] -</pre> - -<p>The URL mappings are managed through the <code>urlpatterns</code> variable, which is a Python <em>list</em> of <code>path()</code> functions. Each <code>path()</code> function either associates a URL pattern to a <em>specific view</em>, which will be displayed when the pattern is matched, or with another list of URL pattern testing code (in this second case, the pattern becomes the "base URL" for patterns defined in the target module). The <code>urlpatterns</code> list initially defines a single function that maps all URLs with the pattern <em>admin/</em> to the module <code>admin.site.urls</code> , which contains the Administration application's own URL mapping definitions.</p> - -<div class="note"> -<p><strong>Note</strong>: The route in <code>path()</code> is a string defining a URL pattern to match. This string might include a named variable (in angle brackets), e.g. <code>'catalog/<id>/'</code>. This pattern will match a URL like <strong>/catalog/</strong><em>any_chars</em><strong>/</strong> and pass <em>any_chars</em> to the view as a string with parameter name <code>id</code>). We discuss path methods and route patterns further in later topics.</p> -</div> - -<p>Add the lines below to the bottom of the file in order to add a new list item to the <code>urlpatterns</code> list. This new item includes a <code>path()</code> that forwards requests with the pattern <code>catalog/</code> to the module <code>catalog.urls</code> (the file with the relative URL <strong>/catalog/urls.py</strong>).</p> - -<pre class="brush: python"># Use include() to add paths from the catalog application -from django.conf.urls import include -from django.urls import path - -urlpatterns += [ - path('catalog/', include('catalog.urls')), -] -</pre> - -<p>Now let's redirect the root URL of our site (i.e. <code>127.0.0.1:8000</code>) to the URL <code>127.0.0.1:8000/catalog/</code>; this is the only app we'll be using in this project, so we might as well. To do this, we'll use a special view function (<code>RedirectView</code>), which takes as its first argument the new relative URL to redirect to (<code>/catalog/</code>) when the URL pattern specified in the <code>path()</code> function is matched (the root URL, in this case).</p> - -<p>Add the following lines, again to the bottom of the file:</p> - -<pre class="brush: python">#Add URL maps to redirect the base URL to our application -from django.views.generic import RedirectView -urlpatterns += [ - path('', RedirectView.as_view(url='/catalog/')), -]</pre> - -<p>Leave the first parameter of the path function empty to imply '/'. If you write the first parameter as '/' Django will give you the following warning when you start the development server:</p> - -<pre class="brush: python">System check identified some issues: - -WARNINGS: -?: (urls.W002) Your URL pattern '/' has a route beginning with a '/'. -Remove this slash as it is unnecessary. -If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. -</pre> - -<p>Django does not serve static files like CSS, JavaScript, and images by default, but it can be useful for the development web server to do so while you're creating your site. As a final addition to this URL mapper, you can enable the serving of static files during development by appending the following lines. </p> - -<p>Add the following final block to the bottom of the file now:</p> - -<pre><code># Use static() to add url mapping to serve static files during development (only) -from django.conf import settings -from django.conf.urls.static import static - -urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)</code> -</pre> - -<div class="note"> -<p><strong>Note</strong>: There are a number of ways to extend the <code>urlpatterns</code> list (above we just appended a new list item using the <code>+=</code> operator to clearly separate the old and new code). We could have instead just included this new pattern-map in the original list definition:</p> - -<pre class="brush: python">urlpatterns = [ - path('admin/', admin.site.urls), - path('catalog/', include('catalog.urls')), - path('', RedirectView.as_view(url='/catalog/', permanent=True)), -] + <code>static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)</code> -</pre> - -<p>In addition, we included the import line (<code>from django.urls import include</code>) with the code that uses it (so it is easy to see what we've added), but it is common to include all your import lines at the top of a Python file.</p> -</div> - -<p>As a final step, create a file inside your catalog folder called <strong>urls.py</strong>, and add the following text to define the (empty) imported <code>urlpatterns</code>. This is where we'll add our patterns as we build the application. </p> - -<pre class="brush: python">from django.urls import path -from catalog import views - - -urlpatterns = [ - -] -</pre> - -<h2 id="Testing_the_website_framework">Testing the website framework</h2> - -<p>At this point we have a complete skeleton project. The website doesn't actually <em>do</em> anything yet, but its worth running it to make sure that none of our changes have broken anything. </p> - -<p>Before we do that, we should first run a <em>database migration</em>. This updates our database to include any models in our installed applications (and removes some build warnings).</p> - -<h3 id="Running_database_migrations">Running database migrations</h3> - -<p>Django uses an Object-Relational-Mapper (ORM) to map Model definitions in the Django code to the data structure used by the underlying database. As we change our model definitions, Django tracks the changes and can create database migration scripts (in <strong>/locallibrary/catalog/migrations/</strong>) to automatically migrate the underlying data structure in the database to match the model.</p> - -<p>When we created the website Django automatically added a number of models for use by the admin section of the site (which we'll look at later). Run the following commands to define tables for those models in the database (make sure you are in the directory that contains<strong> manage.py</strong>):</p> - -<pre class="brush: bash">python3 manage.py makemigrations -python3 manage.py migrate -</pre> - -<div class="warning"> -<p><strong>Important</strong>: You'll need to run the above commands every time your models change in a way that will affect the structure of the data that needs to be stored (including both addition and removal of whole models and individual fields).</p> -</div> - -<p>The <code>makemigrations</code> command <em>creates</em> (but does not apply) the migrations for all applications installed in your project (you can specify the application name as well to just run a migration for a single project). This gives you a chance to checkout the code for these migrations before they are applied — when you're a Django expert you may choose to tweak them slightly!</p> - -<p>The <code>migrate</code> command actually applies the migrations to your database (Django tracks which ones have been added to the current database).</p> - -<div class="note"> -<p><strong>Note</strong>: See <a href="https://docs.djangoproject.com/en/2.0/topics/migrations/">Migrations</a> (Django docs) for additional information about the lesser-used migration commands.</p> -</div> - -<h3 id="Running_the_website">Running the website</h3> - -<p>During development you can test the website by first serving it using the <em>development web server</em>, and then viewing it on your local web browser. </p> - -<div class="note"> -<p><strong>Note</strong>: The development web server is not robust or performant enough for production use, but it is a very easy way to get your Django website up and running during development to give it a convenient quick test. By default it will serve the site to your local computer (<code>http://127.0.0.1:8000/)</code>, but you can also specify other computers on your network to serve to. For more information see <a href="https://docs.djangoproject.com/en/2.0/ref/django-admin/#runserver">django-admin and manage.py: runserver</a> (Django docs).</p> -</div> - -<p>Run the <em>development web server</em> by calling the <code>runserver</code> command (in the same directory as <strong>manage.py</strong>):</p> - -<pre class="brush: bash">python3 manage.py runserver - - Performing system checks... - - System check identified no issues (0 silenced). - August 15, 2018 - 16:11:26 - Django version 2.1, using settings 'locallibrary.settings' - Starting development server at http://127.0.0.1:8000/ - Quit the server with CTRL-BREAK. -</pre> - -<p>Once the server is running you can view the site by navigating to <code>http://127.0.0.1:8000/</code> in your local web browser. You should see a site error page that looks like this:</p> - -<p><img alt="Django Debug page for Django 2.0" src="https://mdn.mozillademos.org/files/15729/django_404_debug_page.png"></p> - -<p>Don't worry! This error page is expected because we don't have any pages/urls defined in the <code>catalogs.urls</code> module (which we're redirected to when we get an URL to the root of the site). </p> - -<div class="note"> -<p><strong>Note</strong>: The above page demonstrates a great Django feature — automated debug logging. An error screen will be displayed with useful information whenever a page cannot be found, or any error is raised by the code. In this case we can see that the URL we've supplied doesn't match any of our URL patterns (as listed). The logging will be turned off during production (when we put the site live on the Web), in which case a less informative but more user-friendly page will be served.</p> -</div> - -<p>At this point we know that Django is working! </p> - -<div class="note"> -<p><strong>Note</strong>: You should re-run migrations and re-test the site whenever you make significant changes. It doesn't take very long!</p> -</div> - -<h2 id="Challenge_yourself">Challenge yourself</h2> - -<p>The <strong>catalog/</strong> directory contains files for the views, models, and other parts of the application. Open these files and inspect the boilerplate. </p> - -<p>As you saw above, a URL-mapping for the Admin site has already been added in the project's <strong>urls.py</strong>. Navigate to the admin area in your browser and see what happens (you can infer the correct URL from the mapping above).</p> - -<ul> -</ul> - -<h2 id="Summary">Summary</h2> - -<p>You have now created a complete skeleton website project, which you can go on to populate with urls, models, views, and templates.</p> - -<p>Now the skeleton for the <a href="/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">Local Library website</a> is complete and running, it's time to start writing the code that makes this website do what it is supposed to do. </p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="https://docs.djangoproject.com/en/2.0/intro/tutorial01/">Writing your first Django app - part 1</a> (Django docs)</li> - <li><a href="https://docs.djangoproject.com/en/2.0/ref/applications/#configuring-applications">Applications</a> (Django Docs). Contains information on configuring applications.</li> -</ul> - -<p>{{PreviousMenuNext("Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django/Models", "Learn/Server-side/Django")}}</p> - -<p> </p> - -<h2 id="In_this_module">In this module</h2> - -<ul> - <li><a href="/en-US/docs/Learn/Server-side/Django/Introduction">Django introduction</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/development_environment">Setting up a Django development environment</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website">Django Tutorial: The Local Library website</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/skeleton_website">Django Tutorial Part 2: Creating a skeleton website</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/Models">Django Tutorial Part 3: Using models</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/Admin_site">Django Tutorial Part 4: Django admin site</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/Home_page">Django Tutorial Part 5: Creating our home page</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/Generic_views">Django Tutorial Part 6: Generic list and detail views</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/Sessions">Django Tutorial Part 7: Sessions framework</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/Authentication">Django Tutorial Part 8: User authentication and permissions</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/Forms">Django Tutorial Part 9: Working with forms</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/Testing">Django Tutorial Part 10: Testing a Django web application</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/Deployment">Django Tutorial Part 11: Deploying Django to production</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/web_application_security">Django web application security</a></li> - <li><a href="/en-US/docs/Learn/Server-side/Django/django_assessment_blog">DIY Django mini blog</a></li> -</ul> - -<p> </p> diff --git a/files/tr/learn/server-side/index.html b/files/tr/learn/server-side/index.html deleted file mode 100644 index 10a879b683..0000000000 --- a/files/tr/learn/server-side/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Server-side website programming -slug: Learn/Server-side -tags: - - Beginner - - CodingScripting - - Intro - - Landing - - Learn - - NeedsTranslation - - Server - - Server-side programming - - Topic - - TopicStub -translation_of: Learn/Server-side -original_slug: Öğren/Server-side ---- -<p>{{draft("Contact Hamish Willee via ~~chrisdavidmills if you have any questions about this work.")}}</p> - -<p class="summary">The <strong><em>Dynamic Websites </em></strong>–<em><strong> Server-side programming</strong></em> topic is a series of modules that show how to create dynamic websites; websites that deliver customised information in response to HTTP requests. The modules provide a generic introduction to server-side programming, along with specific beginner-level guides on how to use the Django (Python) and Express (Node.js/JavaScript) web frameworks to create basic applications.</p> - -<p>Most major websites use some kind of server-side technology to dynamically display different data as required. For example, imagine how many products are available on Amazon, and imagine how many posts have been written on Facebook? Displaying all of these using completely different static pages would be completely inefficient, so instead such sites display static templates (built using <a href="/en-US/docs/Learn/HTML">HTML</a>, <a href="/en-US/docs/Learn/CSS">CSS</a>, and <a href="/en-US/docs/Learn/JavaScript">JavaScript</a>), and then dynamically update the data displayed inside those templates when needed, e.g. when you want to view a different product on Amazon.</p> - -<p>In the modern world of web development, learning about server-side development is highly recommended.</p> - -<h2 id="Learning_pathway">Learning pathway</h2> - -<p>Getting started with server-side programming is usually easier than with client-side development, because dynamic websites tend to perform a lot of very similar operations (retrieving data from a database and displaying it in a page, validating user-entered data and saving it in a database, checking user permissions and logging users in, etc.), and are constructed using web frameworks that make these and other common web server operations easy.</p> - -<p>A basic knowledge of programming concepts (or of a particular programming language) is useful, but not essential. Simlarly, expertise in client-side coding is not required, but a basic knowledge will help you work better with the developers creating your client-side web "front end".</p> - -<p>You will need to understand "how the web works". We recommend that you first read the following topics:</p> - -<ul> - <li><a href="/en-US/docs/Learn/Common_questions/What_is_a_web_server">What is a web server</a></li> - <li><a href="/en-US/docs/Learn/Common_questions/What_software_do_I_need">What software do I need to build a website?</a></li> - <li><a href="/en-US/docs/Learn/Common_questions/Upload_files_to_a_web_server">How do you upload files to a web server?</a></li> -</ul> - -<p>With that basic understanding you'll be ready to work your way through the modules in this section. </p> - -<h2 id="Modules">Modules</h2> - -<p>This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks . </p> - -<dl> - <dt><a href="/en-US/docs/Learn/Server-side/First_steps">Server-side website programming first steps</a></dt> - <dd>This module provides server-technology-agnostic information about server-side website programming, including answers to fundamental questions about server-side programming — "what it is", "how it differs from client-side programming", and "why it is so useful" — and an overview of some of the more popular server-side web frameworks and guidance on how to select the most suitable for your site. Lastly we provide an introductory section on web server security.</dd> - <dt><a href="/en-US/docs/Learn/Server-side/Django">Django Web Framework (Python)</a></dt> - <dd>Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.</dd> - <dt>Express (node.js/Javascript) Web Framework (TBD)</dt> - <dd>Express is a popular web framwork, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.</dd> -</dl> |