# 목록 가져오기
def post_list(request):
post_list = models.Post.objects.all().order_by('-created_at')
paginator = Paginator(post_list, 8)
current_page = request.GET.get("page")
if current_page is None:
current_page = 1
page = paginator.page(current_page)
return render(request, "posts/post_list.html", {"page": page})
# 목록 가져오기 (조회수 기준)
def post_list_hits(request):
post_list = models.Post.objects.all().order_by('-read_count')
paginator = Paginator(post_list, 8)
current_page = request.GET.get("page")
if current_page is None:
current_page = 1
page = paginator.page(current_page)
return render(request, "posts/post_list.html", {"page": page})
# 상세 페이지
def post_detail(request, post_id):
post = get_object_or_404(models.Post, id=post_id)
post.read_count=post.read_count+1
post.save()
return render(request, "posts/post_detail.html", {"post": post})
상세 페이지에 들어갈 때마다 Post DB의 read_count를 증가시켜서 조회수를 구현
여러 파일이 있지만 base.html
, login.html
, signup.html
만 사용
# models.py
class User(AbstractUser):
LOGIN_EMAIL='email'
LOGIN_KAKAO='kakao'
LOGIN_CHOICES=(
(LOGIN_EMAIL, 'Email'),
(LOGIN_KAKAO, 'kakao'),
)
profile_img=models.ImageField(upload_to='profiles',blank=True)
superhost=models.BooleanField(default=False)
login_method = models.CharField(
max_length=50, choices=LOGIN_CHOICES, default=LOGIN_EMAIL
)
def get_absolute_url(self):
return reverse("users:profile", kwargs={"pk": self.pk})
AbstractUser를 상속받아서 사용
추후 kakao 로그인과 회원가입한 사람을 구별하기 위해 email과 kakao의 login_method를 나눔
mixins.py
class LoggedOutOnlyView(UserPassesTestMixin):
permission_denied_message='Page not found'
def test_func(self):
return not self.request.user.is_authenticated
def handle_no_permission(self):
messages.error(self.request, _("Can't go there"))
return redirect('posts:list')
class LoggedInOnlyView(LoginRequiredMixin):
login_url=reverse_lazy('users:login')
회원가입/로그인을 한 유저만 사용가능한 기능들을 구현하기 위해 사용
# forms.py
class LoginForm(...)
...
def clean(self):
email = self.cleaned_data.get("email")
password = self.cleaned_data.get("password")
try:
user = models.User.objects.get(email=email)
if user.check_password(password):
return self.cleaned_data
else:
self.add_error("password", forms.ValidationError("Password is wrong"))
except models.User.DoesNotExist:
self.add_error("email", forms.ValidationError("User does not exist"))
class SignUpForm(...):
...
def clean_email(self):
email=self.cleaned_data.get('email')
try:
models.User.objects.get(email=email)
raise forms.ValidationError('That email is already taken', code='existing_user')
except models.User.DoesNotExist:
return email
def clean_password1(self):
password=self.cleaned_data.get('password')
password1=self.cleaned_data.get('password1')
if password != password1:
raise forms.ValidationError('Password confirmation does not match')
else:
return password
forms.py를 사용한 email, password의 유효성 검사를 구현