Step 5: Authenticate users in Django
Django에서 사용자 인증
- Article
- 12/13/2022
In this article
Applies to:

Visual Studio

Visual Studio for Mac

Visual Studio Code
Previous step: Use the full Django Web Project template
인증은 웹앱의 일반적 요구사항이므로 "Django 웹프로젝트" 템플릿에는 기본 인증흐름이 포함되어 있습니다.
Django 프로젝트 템플릿을 사용하는 경우 Visual Studio는 Django 프로젝트의 settings.py 파일에 인증에 필요한 모든 모듈을 포함합니다.
이 단계에서는 다음을 학습합니다.
The "Django Web Project" template includes a basic authentication flow, as authentication is a common need for web apps. When you use any of the Django project templates, Visual Studio includes all the necessary modules for authentication in the Django project's settings.py file.
In this step, you learn:
How to use the authentication flow provided in the Visual Studio templates (step 5-1)
Visual Studio 템플릿에서 제공되는 인증흐름 사용방법
5-1 단계: 인증 흐름 사용
Use the authentication flow
다음 단계에서는 인증흐름을 연습하고 프로젝트 일부를 설명:
The following steps exercise the authentication flow and describe the parts of the project:
1. 슈퍼사용자(관리자) 계정 생성을 위해 프로젝트 루트에 있는 readme.html 파일의 지침을 아직 따르지 않았다면 지금 수행하십시오. If you've not already followed the instructions in the readme.html file in the project root to create a super user (administrator) account, do so now.
2. Debug > Start Debugging (F5)을 사용하여 Visual Studio에서 앱을 실행.
앱이 브라우저에 나타나면 탐색 모음의 오른쪽 상단에 로그인 Log in이 나타나는지 확인
Run the app from Visual Studio using Debug > Start Debugging (F5). When the app appears in the browser, observe that Log in appears on the upper right of the nav bar.

1. template/app/layout.html을 열고 <div class="navbar ...> 요소에 {% include app/loginpartial.html %} 태그가 포함되어 있는지 확인. {% include %} 태그는 Django의 템플릿 시스템에게, 이 시점에서 포함하는 템플릿을 포함하는 포함된 파일의 내용 안으로 끌어오도록 지시.
Open templates/app/layout.html and observe that the <div class="navbar ...> element contains the {% include app/loginpartial.html %} tag. The {% include %} tag instructs Django's template system to pull in the contents of the included file at this point in the containing template.
2. templates/app/loginpartial.html을 열고 조건부 태그 {% if user.is_authenticated %}를 {% else %} 태그와 함께 사용하여 사용자인증 여부에 따라 다양한 UI 요소를 렌더하는 방법을 관찰.
Open templates/app/loginpartial.html and observe how it uses the conditional tag {% if user.is_authenticated %} along with an {% else %} tag to render different UI elements depending on whether the user is authenticated
HTML
{% if user.is_authenticated %}
<form id="logoutForm" action="/logout" method="post" class="navbar-right">
{% csrf_token %}
<ul class="nav navbar-nav navbar-right">
<li><span class="navbar-brand">Hello {{ user.username }}!</span></li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
</form>
{% else %}
<ul class="nav navbar-nav navbar-right">
<li><a href="{% url 'login' %}">Log in</a></li>
</ul>
{% endif %}
앱을 처음 시작할 때 사용자가 인증되지 않으므로 템플릿 코드는 "login" 링크만 상대 "login" 경로로 렌더.
urls.py에 지정된 대로(이전 섹션 참조), 해당 경로는 django.contrib.auth.views.login view에 매핑되고 view는 다음 데이터를 수신:
As no user is authenticated when you first start the app, the template code renders only the "Log in" link to the relative "login" path. As specified in urls.py (as shown in the previous section), that route is mapped to the django.contrib.auth.views.login view and the view receives the following data:
HTML
{
'template_name': 'app/login.html',
'authentication_form': app.forms.BootstrapAuthenticationForm,
'extra_context':
{
'title': 'Log in',
'year': datetime.now().year,
}
}
여기서 template_name은 login 페이지의 템플릿을 식별(이 경우, template/app/login.html).
extra_context 속성은 템플릿에 제공된 기본 컨텍스트 데이터에 추가됩니다.
마지막으로 authentication_form은 로그인에 사용할 양식 클래스를 지정;
템플릿에서는 form 객체로 나타납니다.
기본값은 AuthenticationForm(django.contrib.auth.views에서);
대신 Visual Studio 프로젝트 템플릿은 앱의 form.py 파일에 정의된 양식을 사용:
Here, template_name identifies the template for the login page, in this case templates/app/login.html. The extra_context property is added to the default context data given to the template. Finally, authentication_form specifies a form class to use with the login; in the template it appears as the form object. The default value is AuthenticationForm (from django.contrib.auth.views); the Visual Studio project template instead uses the form defined in the app's forms.py file:
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
class BootstrapAuthenticationForm(AuthenticationForm):
"""Authentication form which uses boostrap CSS."""
username = forms.CharField(max_length=254,
widget=forms.TextInput({
'class': 'form-control',
'placeholder': 'User name'}))
password = forms.CharField(label=_("Password"),
widget=forms.PasswordInput({
'class': 'form-control',
'placeholder':'Password'}))
보시다시피 form 클래스는 AuthenticationForm에서 파생되며 특히 사용자 이름 및 비밀번호 필드를 재정의하여 자리 표시자 텍스트를 추가합니다.
Visual Studio 템플릿에는 암호 강도 유효성검사 추가와 같이 form을 사용자 지정하려는 경우가 있다는 가정하에 이 명시적 코드가 포함되어 있습니다.
로그인 페이지로 이동하면 앱이 login.html 템플릿을 렌더합니다.
{{ form.username }} 및 {{ form.password }} 변수는 BootstrapAuthenticationForm에서 CharField 양식을 렌더합니다.
또한 유효성검사 오류를 표시하는 섹션과 해당 서비스를 추가하기로 선택한 경우 소셜로그인을 위해 미리 만들어진 요소도 있습니다.
As you can see, the form class derives from AuthenticationForm and specifically overrides the username and password fields to add placeholder text. The Visual Studio template includes this explicit code on the assumption that you likely want to customize the form, such as adding password strength validation.
When you navigate to the login page, then, the app renders the login.html template. The variables {{ form.username }} and {{ form.password }} render the CharField forms from BootstrapAuthenticationForm. There's also a built-in section to show validation errors, and a ready-made element for social logins if you choose to add those services.
HTML
{% extends "app/layout.html" %}
{% block content %}
<h2>{{ title }}</h2>
<div class="row">
<div class="col-md-8">
<section id="loginForm">
<form action="." method="post" class="form-horizontal">
{% csrf_token %}
<h4>Use a local account to log in.</h4>
<hr />
<div class="form-group">
<label for="id_username" class="col-md-2 control-label">User name</label>
<div class="col-md-10">
{{ form.username }}
</div>
</div>
<div class="form-group">
<label for="id_password" class="col-md-2 control-label">Password</label>
<div class="col-md-10">
{{ form.password }}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="hidden" name="next" value="/" />
<input type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
{% if form.errors %}
<p class="validation-summary-errors">Please enter a correct user name and password.</p>
{% endif %}
</form>
</section>
</div>
<div class="col-md-4">
<section id="socialLoginForm"></section>
</div>
</div>
{% endblock %}
form을 제출하면 Django는 자격증명(예: 슈퍼사용자의 자격증명)을 인증하려고 시도합니다.
인증에 실패하면 현재 페이지가 유지되지만 form.errors는 true로 설정됩니다.
인증이 성공하면 Django는 "next" 필드의 상대 URL인 <input type="hidden" name="next" value="/" />로 이동하는데, 이 경우 홈 페이지(/)입니다.
이제 홈 페이지가 다시 렌더되면 loginpartial.html 템플릿이 렌더링될 때 user.is_authenticated 속성이 true가 됩니다.
결과적으로 Hello(사용자이름) 메시지가 표시되고 로그오프됩니다.
앱의 다른 부분에서 user.is_authenticated를 사용하여 인증을 확인할 수 있습니다.
When you submit the form, Django attempts to authenticate your credentials (such as the super user's credentials). If authentication fails, you remain on the current page however, form.errors is set to true. If authentication is successful, Django navigates to the relative URL in the "next" field, <input type="hidden" name="next" value="/" />, which in this case is the home page (/).
Now, when the home page is rendered again, the user.is_authenticated property is true when the loginpartial.html template is rendered. As a result, you see a Hello (username) message and Log off. You can use user.is_authenticated in other parts of the app to check authentication.

인증된 사용자가 특정 리소스에 액세스할 수 있는 권한이 있는지 확인하려면 데이터베이스에서 사용자별 권한을 검색해야 합니다.
자세한 내용은 Using the Django authentication system (Django docs)을 참조.
You need to retrieve user-specific permissions from your database to check whether the authenticated user is authorized to access specific resources. For more information, see Using the Django authentication system (Django docs).
특히 슈퍼유저 또는 관리자는 상대 URL "/admin/" 및 "/admin/doc/"를 사용, 내장된 Django 관리자 인터페이스에 액세스할 수 있는 권한이 있습니다.
이러한 인터페이스를 활성화하려면 아래 단계를 따르십시오.
The super user or administrator, in particular, is authorized to access the built-in Django administrator interfaces using the relative URLs "/admin/" and "/admin/doc/." To enable these interfaces, follow the steps below:
docutils Python 패키지를 환경에 설치합니다.
가장 좋은 설치방법은 requirements.txt file에 "docutils"를 추가하는 것.
그런 다음 솔루션 탐색기로 이동하여 프로젝트를 확장하고 Python 환경노드를 확장한 다음 사용 중인 환경을 마우스오른쪽단추로 클릭하고 Install from requirements.txt 를 선택.
Django 프로젝트의 urls.py 파일을 열고 다음을 추가합.
Install the docutils Python package into your environment. A great way to install is to add "docutils" to your requirements.txt file. Then, go to Solution Explorer, expand the project, expand the Python Environments node, and then right-click the environment you're using and select Install from requirements.txt.
Open the Django project's urls.py file and add the following:
Python
from django.conf.urls import include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
path('admin/doc/', include('django.contrib.admindocs.urls'))
]
Django 프로젝트의 settings.py 파일에서 INSTALLED_APPS 컬렉션으로 이동하여 'django.contrib.admindocs'를 추가.
앱을 다시 시작하면 "/admin/" 및 "/admin/doc/"로 이동할 수 있습니다.
In the Django project's settings.py file, go to the INSTALLED_APPS collection and add 'django.contrib.admindocs'.
When you restart the app, you can navigate to "/admin/" and "/admin/doc/" and perform tasks like creating more user accounts.

인증 흐름의 마지막 부분은 로그오프입니다.
loginpartial.html에서 볼 수 있듯이 로그오프 링크는 내장된 view django.contrib.auth.views.logout에 의해 처리되는 상대 URL "/login"에 대한 POST를 수행합니다.
이 view는 UI를 표시하지 않고 단지 홈페이지로 이동("^logout$" 패턴에 대해 urls.py에 표시됨).
로그오프 페이지를 표시하려면 먼저 URL 패턴을 다음과 같이 변경하여 "template_name" 속성을 추가하고 "next_page" 속성을 제거.
The final part to the authentication flow is logging off. As you can see in loginpartial.html, the Log off link simply does a POST to the relative URL "/login", which is handled by the built-in view django.contrib.auth.views.logout. This view doesn't display any UI and just navigates to the home page (as shown in urls.py for the "^logout$" pattern). If you want to display a logoff page, first change the URL pattern as follows to add a "template_name" property and remove the "next_page" property:
Python
path('logout/', django.contrib.auth.views.logout, { 'template_name': 'app/loggedoff.html', # 'next_page': '/', }, name='logout')
그런 다음 다음 (최소) 내용으로 template/app/loggedoff.html을 만듭니다.
Then create templates/app/loggedoff.html with the following (minimal) contents:
HTML
{% extends "app/layout.html" %} {% block content %} <h3>You have been logged off</h3> {% endblock %}
결과는 아래와 같습니다:
The result appears as below:

모두 완료되면 서버를 중지하고 변경 사항을 소스 제어에 다시 한 번 커밋합니다.
When you're all done, stop the server and once again commit your changes to source control.
질문: <form> 요소에 나타나는 {% csrf_token %} 태그의 목적은 무엇입니까?
Question: What is the purpose of the {% csrf_token %} tag that appears in the <form> elements?
답변: {% csrf_token %} 태그에는 Django에 내장된 사이트 간 요청 위조(csrf) 보호 기능(Django 문서)이 포함되어 있습니다.
일반적으로 양식과 같이 POST, PUT 또는 DELETE 요청 메서드와 관련된 모든 요소에 이 태그를 추가합니다.
그런 다음 템플릿 렌더링 기능(렌더링)이 필요한 보호 기능을 삽입합니다.
The {% csrf_token %} tag includes Django's built-in cross-site request forgery (csrf) protection (Django docs). You usually add this tag to any element that involves POST, PUT, or DELETE request methods, such as a form. The template rendering function (render) then inserts the necessary protection.
Next steps
Note
이 자습서 과정 전체에서 Visual Studio 솔루션을 소스제어에 커밋했다면 이제 또 다른 커밋을 수행할 좋은 기회입니다.
솔루션은 GitHub의 자습서 소스 코드인 Microsoft/python-sample-vs-learning-django와 일치해야 합니다.
이제 Visual Studio에서 "빈 Django 웹 프로젝트" 및 "Django 웹프로젝트" 템플릿 전체를 살펴보았습니다.
view 및 템플릿 사용 같은 Django의 모든 기본사항을 배웠습니다.
또한 라우팅, 인증, 사용된 데이터베이스 모델을 살펴보았습니다.
이제 필요한 view와 모델을 사용하여 자신만의 웹앱을 만들 수 있습니다.
개발 컴퓨터에서 웹앱을 실행하는 것은 고객이 앱을 사용할 수 있도록 하기 위한 한 단계일 뿐입니다.
다음 단계에는 다음 작업이 포함될 수 있습니다.
If you've been committing your Visual Studio solution to source control throughout the course of this tutorial, now is a good time to do another commit. Your solution should match the tutorial source code on GitHub: Microsoft/python-sample-vs-learning-django.
You've now explored the entirety of the "Blank Django Web Project" and "Django Web Project" templates in Visual Studio. You've learned all the basics of Django such as using views and templates. You've also explored routing, authentication, and used database models. You should now be able to create a web app of your own with any views and models that you need.
Running a web app on your development computer is just one step in making the app available to your customers. Next steps might include the following tasks:
template/404.html이라는 템플릿을 생성하여 404 페이지를 사용자 정의하세요.
존재하는 경우 Django는 기본 템플릿 대신 이 템플릿을 사용합니다.
자세한 내용은 Django 설명서의 오류 보기를 참조하세요.
Customize the 404 page by creating a template named templates/404.html. When present, Django uses this template instead of its default one. For more information, see Error views in the Django documentation.
Tests.py에 단위 테스트를 작성하세요.
Visual Studio 프로젝트 템플릿은 이에 대한 시작점을 제공하며, 자세한 내용은 Writing your first Django app, part 5 - testing and Testing in Django in the Django documentation에서 찾을 수 있습니다.
Write unit tests in tests.py; the Visual Studio project templates provide starting points for these, and more information can be found on Writing your first Django app, part 5 - testing and Testing in Django in the Django documentation.
앱을 SQLite에서 PostgreSQL, MySQL 및 SQL Server(모두 Azure에서 호스팅 가능) 같은 프로덕션 수준 데이터저장소로 변경.
SQLite를 사용해야 하는 경우(sqlite.org)에 설명된 대로 SQLite는 일일 조회수가 100,000회 미만인 낮거나 중간 정도의 트래픽 사이트에서 잘 작동합니다.
그러나 SQLite는 더 높은 볼륨에는 권장되지 않습니다.
또한 SQLite는 단일 컴퓨터로 제한되므로 부하 분산 및 지역 복제와 같은 다중 서버 시나리오에서는 사용할 수 없습니다.
Django의 다른 데이터베이스 지원에 대한 자세한 내용은 데이터베이스 설정을 참조하세요.
Python용 Azure SDK를 사용하여 테이블 및 Blob과 같은 Azure Storage 서비스로 작업할 수도 있습니다.
Change the app from SQLite to a production-level data store such as PostgreSQL, MySQL, and SQL Server (all of which can be hosted on Azure). As described on When to use SQLite (sqlite.org), SQLite works fine for low to medium traffic sites with fewer than 100 K hits/day. However, SQLite isn't recommended for higher volumes. SQLite is also limited to a single computer, so it can't be used in any multi-server scenario such as load-balancing and geo-replication. For information on Django's support for other databases, see Database setup. You can also use the Azure SDK for Python to work with Azure storage services like tables and blobs.
Azure DevOps와 같은 서비스에서 지속적 통합/지속적인 배포 파이프라인을 설정합니다.
Azure Repos, GitHub 또는 다른 곳을 통해 소스제어 작업 외에도 릴리스를 위한 전제조건으로 단위 테스트를 자동으로 실행하도록 Azure DevOps 프로젝트를 구성할 수 있습니다.
프로덕션에 배포하기 전에 추가 테스트를 위해 스테이징 서버에 배포하도록 파이프라인을 구성할 수도 있습니다.
또한 Azure DevOps는 App Insights와 같은 모니터링 솔루션과 통합되고 민첩한 계획도구를 사용하여 전체 주기를 마무리합니다.
자세한 내용은 Azure DevOps 프로젝트를 사용하여 Python용 CI/CD 파이프라인 만들기 및 일반 Azure DevOps 설명서를 참조하세요.
Set up a continuous integration/continuous deployment pipeline on a service like Azure DevOps. In addition to working with source control (via Azure Repos or GitHub, or elsewhere), you can configure an Azure DevOps Project to automatically run your unit tests as a pre-requisite for release. You can also configure the pipeline to deploy to a staging server for more tests before deploying to production. Azure DevOps, furthermore, integrates with monitoring solutions like App Insights and closes the whole cycle with agile planning tools. For more information, see Create a CI/CD pipeline for Python with the Azure DevOps project and also the general Azure DevOps documentation.
Go deeper
Django에서 사용자 인증(docs.djangoproject.com)
GitHub의 튜토리얼 소스 코드: Microsoft/python-sample-vs-learning-django
- User authentication in Django (docs.djangoproject.com)
- Tutorial source code on GitHub: Microsoft/python-sample-vs-learning-django
댓글