is_authenticated
attribute을 활용하여 로그인 사용자에 대한 접근을 제한하는 방법에 대해 알아보자!
request.user
에서 이 속성을 사용 (request.user.is_authenticated
)<!-- base.html -->
{% if user.is_authenticated %}
<form action="{% url 'accounts:logout' %}" method="POST">
{% csrf_token %}
<input type="submit" value="로그아웃">
</form>
<a href="{% url 'accounts:update' %}">회원정보 수정</a>
<form action="{% url 'accounts:delete' %}" method="POST">
{% csrf_token %}
<input type="submit" value="회원탈퇴">
</form>
<h3 id="user-hello"><i>안녕하세요, {{user}} 님 !</i></h3>
{% else %}
<a href="{% url 'accounts:signup' %}">회원가입</a>
<a href="{% url 'accounts:login' %}">로그인</a>
{% endif %}
<!-- articles/index.html -->
{% extends 'base.html' %}
{% block content %}
<h1>INDEX</h1>
{% if request.user.is_authenticated %}
<a href="{% url 'articles:create' %}">작성하기</a>
<hr>
{% else %}
<a href="{% url 'accounts:login' %}">새 글을 작성하려면 로그인 하세요</a>
{% endif %}
{% for article in articles %}
<p>
[{{article.id}}] <a href="{% url 'articles:detail' article.pk %}" id="article-title">{{article.title}}</a>
</p>
<hr />
{% endfor %}
{% endblock content %}
# accounts/views.py
def login(request):
if request.user.is_authenticated:
return redirect('articles:index')
if request.method == 'POST':
form = AuthenticationForm(request, request.POST)
if form.is_valid():
auth_login(request, form.get_user())
return redirect('articles:index')
else:
form = AuthenticationForm()
context = {'form': form}
return render(request, 'accounts/login.html', context)