본문 바로가기

Django

Django Login, Logout 템플릿 이용하기

반응형

 

이미지 썸네일 삭제
Django Tutorial Part 8: User authentication and permissions - Learn web development | MDN

Excellent work — you've now created a website that library members can log in 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...

developer.mozilla.org

1. Default Project의 urls.py에 아래 코드를 넣는다.

urlpatterns += [
    path('accounts/', include('django.contrib.auth.urls')),
]
 
 

2. settings.py에 아래 코드를 넣는다.

STATICFILES_DIRS = ( os.path.join('static'), )
 

3. 프로젝트 최상위에 template/registration 폴더를 만들고 login.html 을 만든다.

{% extends 'HelloWorld/base.html' %}
{% block title-main %}Write Blog Post{% endblock %}
{% block title-sub %}{% endblock %}
{% block title-meta %}{% endblock %}
{% load static %}
{% block main-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 action="{% url 'login' %}" method="post">
    {% csrf_token %}
<div class="d-grid gap-3">
    <div class="input-group">
        <span class="input-group-text w-25">ID</span>
        <input type="text" class="form-control" name="username" aria-describedby="idHelp" placeholder="ID">
    </div>
    <div class="input-group">
        <span class="input-group-text w-25">Password</span>
        <input type="password" class="form-control" name="password" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-primary">Login</button>
</div>
<input type="hidden" name="next" value="{{ next }}" />
</form>
  {# Assumes you setup the password_reset view in your URLconf #}
  <p><a href="{% url 'password_reset' %}">Lost password?</a></p>
{% endblock %}
 

4. 로긴에 성공하면 기본 화면으로 보내기 위해서 settings.py 파일에 아래 설정을 넣는다.

LOGIN_REDIRECT_URL = '/'
 

5. 로그 아웃을 만들기 위해 /templates/registration/logged_out.html 을 만든다.

{% extends 'HelloWorld/base.html' %}
{% block title-main %}John & Sunny Blog{% endblock %}
{% block title-sub %}A sound mind in a sound body.{% endblock %}

{% block main-content %}
  <p>Logged out!</p>
  <a href="{% url 'login'%}">Click here to login again.</a>
{% endblock %}
 

 

 

반응형