반응형

<로그인 기능 구현 >


1.accounts app 생성 

1
$python manage.py startapp accounts
cs


-> settings.py ->  app 목록 -> accounts 추가

1
'accounts.apps.AccountsConfig',
cs


2.template 만들기 -> login.html / signup.html =>  accounts/templates/accounts


-> signup.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{% extends 'base.html' %}
 
{% block content %}
 
<h1>Sign Up!</h1>
 
<form>
    Username:
    <br>
    <input name="username" type="text" value="">
    <br>
    Password:
    <br>
    <input name="password1" type="password" value="">
    <br>
    Confirm Password:
    <br>
    <input name="password2" type="password" value="">
    <br>
    <br>
    <input class="btn btn-primary" type="submit" value="Sign Up!">
</form>
 
{% endblock %}
cs


-> login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{% extends 'base.html' %}
 
{% block content %}
 
<h1>Login</h1>
 
<form>
    Username:
    <br>
    <input name="username" type="text" value="">
    <br>
    Password:
    <br>
    <input name="password" type="password" value="">
    <br>
    <br>
    <input class="btn btn-primary" type="submit" value="Login">
</form>
 
{% endblock %}
cs


3. accounts/ views.py 에서 페이지 연결

1
2
3
4
5
6
7
8
9
10
11
from django.shortcuts import render
    
    # Create your views here.
    
    
    def signup(request):
        return render(request, 'accounts/signup.html')
    
    
    def login(request):
        return render(request, 'accounts/login.html')
cs



4.accounts/ulrs.py 생성해서 url 연결

1
2
3
4
5
6
7
8
from django.urls import path
from . import views
 
urlpatterns = [
    path('signup/', views.signup, name='signup'),
    path('login/', views.login, name='login'),
]
 
cs


5. 프로젝트 urls.py -> include로 연결

1
path('accounts/', include('accounts.urls')),
cs


6. navbar 에 login.html과 signup.html 연결될 링크 만들어줌 -> base.html

1
2
    <class="nav-item nav-link" href="{% url 'signup'%}">Signup</a>
    <class="nav-item nav-link" href="{% url 'login'%}">Login</a>
cs

<회원 가입 기능 구현하기>

1.template 수정하기 signup.html

1
2
3
<form method="POST" action="{% url 'signup'%}">
 
{% csrf_token %}
cs


##RESTful - HTTP method

-> GET - 데이터 조회(READ)

-> POST - 데이터 생성(CREATE)

-> PUT - 데이터 수정(UPDATE)

-> DELETE - 데이터 삭제(DELETE)


##{% csrf_toekn %} 

-> 보안 위해 사용하는 내용 


##form태그 안에 적어주어야 form을 submit 할 떄 같이 전송됨


2.view 수정하기 <accounts/views.py>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth
    
    # Create your views here.
    
    
def signup(request):
    if request.method == 'POST':
        if request.POST['password1'== request.POST['password2']:
            user = User.objects.create_user(
                request.POST['username'], password=request.POST['password1'])
            auth.login(request, user)
            return redirect('home')
    return render(request, 'accounts/signup.html')
    
    
cs


<로그인 기능 구현하기>

1.template 수정하기 <login.html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{% extends 'base.html' %}
 
{% block content %}
 
{% if error %}
{{ error }}
<br>
<br>
{% endif %}
 
<h1>Login</h1>
 
<form action="{% url 'login' %}" method="POST">
        {% csrf_token %} <!-- csrf 공격 방어하는 수단 for 보안 -->
    Username:
    <br>
    <input name="username" type="text" value="">
    <br>
    Password:
    <br>
    <input name="password" type="password" value="">
    <br>
    <br>
    <input class="btn btn-primary" type="submit" value="Login">
</form>
 
{% endblock %}
cs


2. accounts/views,py -> login 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
 
        user = auth.authenticate(request, username=username, password=password)
        if user is not None:
            auth.login(request, user)
            return redirect('home')
        else:
            return render(request, 'accounts/login.html', {'error''username or password is incorrect.'})
 
    else:
        return render(request, 'accounts/login.html')
cs


<logout 구현하기>

1.view 추가하기 (accounts/views.py)

1
2
3
4
5
def logout(request):
    if request.method == 'POST':
        auth.logout(request)
        return redirect('home')
    return render(request,'accounts/login.html')  
cs


2.url 추가하기(accounts/urls.py)

1
path('logout/', views.logout, name='logout'),
cs



<login/logou/signup 기능 navbar링크 걸기>

->(base.html)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <class="navbar-brand" href="{% url 'home' %}">Like Lion</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
                aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item">
                        <class="nav-item nav-link" href="{% url 'home' %}">HOME</span></a>
                    </li>
                    <li class="nav-item">
                        <class="nav-item nav-link" href="{% url 'portfolio' %}">Portfolio</a>
                    </li>
                    <li class="nav-item">
                        <class="nav-item nav-link" href="{% static '수료증 - 삼육대 - 오지수.pdf'%}">수료증</a>
                    </li>
                    {% if user.is_authenticated %}
                    <li class="nav-item dropdown">
                        <class="nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown"
                            aria-haspopup="true" aria-expanded="false">환영합니다. {{ user.username }} 님!</a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                            <class="dropdown-item" href="{% url 'new' %}">글쓰기</a>
                            <class="dropdown-item" href="javascript:{document.getElementById('logout').submit()}">Logout</a>
                            <form id="logout" method="POST" action="{% url 'logout' %}">
                                {% csrf_token %} <input type="hidden" />
                            </form>
                        </div>
                    </li>
                    {% else %}
                    <li class="nav-item">
                        <class="nav-item nav-link" href="{% url 'signup' %}">Signup</a>
                    </li>
                    <li class="nav-item">
                        <class="nav-item nav-link" href="{% url 'login' %}">Login</a>
                    </li>
                    {% endif %}
                </ul>
            </div>
        </div>
    </nav>
cs




요렇게 하면 ~

로그인시 화면 이렇게 출력~ hidden도 된다 

반응형

'Web > Django' 카테고리의 다른 글

[5.5주차]Faker  (0) 2019.03.05
[5주차]2.Pagination  (0) 2019.03.05
[4주차]2.blog-(3)  (0) 2019.03.05
[4주차]2.blog-(2)  (0) 2019.03.04
[4주차]2.blog-(1)  (0) 2019.03.04

+ Recent posts