티스토리 뷰
반응형
0. 들어가면서
프로젝트 안의 accounts 앱 안의 코드를 정리한 것이다. 코딩 시 참고만 하기 바라며 이전에 내용들을 따라 하나씩 따라오길 추천한다.
1. urls.py
app_name = 'accounts'
urlpatterns = [
path('signup/', views.signup, name='signup'),
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout'),
path('<int:pk>/', views.detail, name='detail'),
path('delete/', views.delete, name='delete'),
path('update/', views.update, name='update'),
path('<int:pk>/follow/', views.follow, name='follow'),
]
2. admin.py
from django.contrib import admin
from .models import User
admin.site.register(User)
3. forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ['username', 'first_name', 'last_name', 'email']
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ['username', 'email']
4. models.py
import hashlib
from django.db import models
from django.conf import settings
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
followers = models.ManyToManyField(
settings.AUTH_USER_MODEL,
related_name='followings'
)
@property
def gravatar_url(self):
return f"https://s.gravatar.com/avatar/{hashlib.md5(self.email.encode('utf-8').strip().lower()).hexdigest()}?s=80"
5, views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import get_user_model
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from django.views.decorators.http import require_POST
from .forms import CustomUserChangeForm, CustomUserCreationForm
def signup(request):
if request.user.is_authenticated:
return redirect('articles:index')
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('articles:index')
else:
form = CustomUserCreationForm()
context = {
'form': form
}
return render(request, 'accounts/signup.html', context)
def detail(request, pk):
User = get_user_model()
user = get_object_or_404(User, pk=pk)
context = {
'user': user
}
return render(request, 'accounts/detail.html', context)
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(request.GET.get('next') or 'articles:index')
else:
form = AuthenticationForm()
context = {
'form': form
}
return render(request, 'accounts/login.html', context)
@login_required
def logout(request):
auth_logout(request)
return redirect('articles:index')
@require_POST
@login_required
def delete(request):
request.user.delete()
return redirect('articles:index')
def update(request):
if request.method == 'POST':
form = CustomUserChangeForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('articles:index')
else:
form = CustomUserChangeForm(instance=request.user)
context = {
'form': form
}
return render(request, 'accounts/update.html', context)
def follow(request, pk):
User = get_user_model()
user = get_object_or_404(User, pk=pk)
if user != request.user:
if user.followers.filter(pk=request.user.pk).exists():
user.followers.remove(request.user)
else:
user.followers.add(request.user)
return redirect('accounts:detail', user.pk)
6. gravatar.py
import hashlib
from django import template
register = template.Library()
@register.filter
def profile_url(email):
return f"https://s.gravatar.com/avatar/{hashlib.md5(email.encode('utf-8').strip().lower()).hexdigest()}?s=80"
7. detail.html
{% extends 'base.html' %}
{% block body %}
<h1>{{ user.pk }} : {{ user.username }}</h1>
{% with user_followers=user.followers.all %}
{% if request.user == user %}
<a href="{% url 'accounts:update' %}">회원 수정</a>
<form action="{% url 'accounts:delete' %}" method="POST">
{% csrf_token %}
<button class="btn btn-secondary">회원 탈퇴</button>
</form>
{% else %}
<hr>
{% if request.user in user_followers %}
<a href="{% url 'accounts:follow' user.pk %}">팔로우 취소</a>
{% else %}
<a href="{% url 'accounts:follow' user.pk %}">팔로우</a>
{% endif %}
{% endif %}
<p> {{ user_followers|length }}명이 팔로우하고 있습니다.</p>
<p> {{ user.followings.count }}명을 내가 팔로우하고 있습니다.</p>
{% endwith %}
<hr>
<h3>작성한 글 목록</h3>
{% for article in user.article_set.all %}
<a href="{% url 'articles:detail' article.pk %}">
<p>{{ article.title }}</p>
</a>
{% endfor %}
<h3>좋아요한 글 목록</h3>
{% for article in user.like_articles.all %}
<a href="{% url 'articles:detail' article.pk %}">
<p>{{ article.title }}</p>
</a>
{% endfor %}
{% endblock %}
8. login.html
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block body %}
<h2 class="text-center">로그인</h2>
<form action="" method="POST">
{% csrf_token %}
{% bootstrap_form form %}
<button class="btn btn-primary">로그인</button>
<a href="{% url 'accounts:signup' %}">회원가입</a>
</form>
{% endblock %}
9. signup.html
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block body %}
<h2 class="text-center">회원가입</h2>
<form action="" method="POST">
{% csrf_token %}
{% bootstrap_form form %}
<button class="btn btn-primary">회원가입 신청</button>
<a href="{% url 'accounts:login' %}">로그인</a>
</form>
{% endblock %}
10. update.html
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block body %}
<form action="" method="POST">
{% csrf_token %}
{% bootstrap_form form %}
<button class="btn btn-primary">수정</button>
</form>
{% endblock %}
반응형
'Web > Django' 카테고리의 다른 글
Django rest framework_2. 포스트맨(POSTMAN) 시작하기 (0) | 2020.09.15 |
---|---|
Django rest framework_1. 프로젝트시작하기(서버) (0) | 2020.09.15 |
[Django] 좋아요기능과 팔로우기능의 DB 네이밍 컨벤션(ManyToManyField) (0) | 2020.08.30 |
[Django]데이터베이스관리(N:M)_팔로우 기능 구현(custom user) (0) | 2020.08.29 |
[Django]데이터베이스관리(N:M)_좋아요 기능 구현 (32) | 2020.08.28 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- NextJS
- vuejs
- nodejs
- django
- mongoDB
- Python
- TensorFlow
- next.config.js
- UserCreationForm
- login
- useState
- react autoFocus
- nextjs autoFocus
- Queue
- Vue
- 자연어처리
- Express
- 자료구조
- Deque
- react
- JavaScript
- pandas
- DFS
- 클라우데라
- typescript
- logout
- useHistory 안됨
- error:0308010C:digital envelope routines::unsupported
- BFS
- read_csv
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함