Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ログイン・ログアウト機能の実装 #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 68 additions & 8 deletions accounts/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.conf import settings
from django.contrib.auth import SESSION_KEY, get_user_model
from django.test import TestCase
from django.urls import reverse
Expand Down Expand Up @@ -29,7 +30,7 @@ def test_success_post(self):
# Tweets/homeへのリダイレクト
self.assertRedirects(
response,
reverse("tweets:home"),
reverse(settings.LOGIN_REDIRECT_URL),
status_code=302,
target_status_code=200,
)
Expand Down Expand Up @@ -195,18 +196,77 @@ def test_failure_post_with_mismatch_password(self):
self.assertIn("確認用パスワードが一致しません。", form.errors["password2"])


# class TestLoginView(TestCase):
# def test_success_get(self):
class TestLoginView(TestCase):
def setUp(self):
self.url = reverse("accounts:login")
self.user = User.objects.create_user(username="testuser", password="testpassword")

# def test_success_post(self):
def test_success_get(self):
response = self.client.get(self.url)
self.assertEqual(response.status_code, 200)

# def test_failure_post_with_not_exists_user(self):
def test_success_post(self):
valid_data = {
"username": " testuser",
"password": "testpassword",
}

# def test_failure_post_with_empty_password(self):
response = self.client.post(self.url, valid_data)
self.assertRedirects(
response,
reverse(settings.LOGIN_REDIRECT_URL), # リダイレクト先
status_code=302,
target_status_code=200, # リダイレクト先のステータスコード
)
self.assertIn(SESSION_KEY, self.client.session)

def test_failure_post_with_not_exists_user(self):
invalid_data = {
"username": "testuserr",
"password": "testpassword",
}

# class TestLogoutView(TestCase):
# def test_success_post(self):
response = self.client.post(self.url, invalid_data)
form = response.context["form"]

self.assertEqual(response.status_code, 200)
self.assertNotIn(SESSION_KEY, self.client.session)
self.assertContains(
response,
"正しいユーザー名とパスワードを入力してください。どちらのフィールドも大文字と小文字は区別されます。",
)
self.assertTrue(form.errors)

def test_failure_post_with_empty_password(self):
invalid_data = {
"username": "testuserr",
"password": "",
}

response = self.client.post(self.url, invalid_data)
form = response.context["form"]

self.assertEqual(response.status_code, 200)
self.assertNotIn(SESSION_KEY, self.client.session)
self.assertIn("このフィールドは必須です。", form.errors["password"])


class TestLogoutView(TestCase):
def setUp(self):
self.url = reverse("accounts:logout")
User.objects.create_user(username="testuser", password="testpassword")
self.client.login(username="testuser", password="testpassword")

def test_success_post(self):
response = self.client.post(self.url)

self.assertRedirects(
response,
reverse(settings.LOGOUT_REDIRECT_URL),
status_code=302,
target_status_code=200,
)
self.assertNotIn(SESSION_KEY, self.client.session)


# class TestUserProfileView(TestCase):
Expand Down
5 changes: 3 additions & 2 deletions accounts/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# from django.contrib.auth import views as auth_views
from django.contrib.auth.views import LoginView, LogoutView
from django.urls import path

from . import views
Expand All @@ -7,8 +8,8 @@

urlpatterns = [
path("signup/", views.SignupView.as_view(), name="signup"),
# path('login/', auth_views.LoginView.as_view(), name='login'),
# path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path("login/", LoginView.as_view(template_name="accounts/login.html"), name="login"),
path("logout/", LogoutView.as_view(), name="logout"),
# path('<str:username>/', views.UserProfileView.as_view(), name='user_profile'),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここのコメントアウト外してあげましょう!今のままではプロフィールページ見られないはず

# path('<str:username>/follow/', views.FollowView.as_view(), name='follow'),
# path('<str:username>/unfollow/', views.UnFollowView, name='unfollow'),
Expand Down
21 changes: 19 additions & 2 deletions accounts/views.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
# from django.shortcuts import render

from django.conf import settings
from django.contrib.auth import authenticate, login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここで取って来ているUserモデルは、Djangoでデフォルトで提供されている組み込みのモデルです。
今回持ってきたいのはサインアップ機能の時にmodels.pyに書いて作成したものなので、インポート元を修正しましょう!今の状態だとユーザーのデータ持ってこられていなくてページ開いたときにエラー起きちゃってる🫠

from django.urls import reverse_lazy
from django.views.generic import CreateView
from django.views.generic import CreateView, TemplateView

from .forms import SignupForm


class SignupView(CreateView):
form_class = SignupForm
template_name = "accounts/signup.html"
success_url = reverse_lazy("tweets:home") # リダイレクト先url貼付、success_url使用時遅延評価でurl逆引き
success_url = reverse_lazy(
settings.LOGIN_REDIRECT_URL
) # リダイレクト先url貼付、success_url使用時遅延評価でurl逆引き

def form_valid(self, form):
response = super().form_valid(form)
Expand All @@ -21,3 +26,15 @@ def form_valid(self, form):
user = authenticate(self.request, username=username, password=password)
login(self.request, user)
return response


class UserProfileView(LoginRequiredMixin, TemplateView):
template_name = "accounts/user_profile.html"

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
username = self.kwargs.get("username")
user = User.objects.get(username=username)
context["user"] = user
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コンテキストってテンプレート上で表示するために作成しているもので、
今回は user_profile.html でuserっていう変数使っていないのでこの行は不要です🙅‍♀️

context["username"] = username
return context
6 changes: 6 additions & 0 deletions mysite/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,9 @@

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
AUTH_USER_MODEL = "accounts.User"


LOGIN_URL = "accounts:login"
LOGOUT_URL = "accounts:logout"
LOGIN_REDIRECT_URL = "tweets:home"
LOGOUT_REDIRECT_URL = "accounts:login"
10 changes: 10 additions & 0 deletions templates/accounts/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{% extends "base.html" %}
{% block title %}login{% endblock %}
{% block content %}

<form method="post">
{% csrf_token %}
{{ form.as_p}}
<button type="submit">ログイン</button>
</form>
{% endblock %}
8 changes: 8 additions & 0 deletions templates/accounts/user_profile.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{% extends "base.html" %}

{% block title %}User Profile{% endblock %}

{% block content %}
<p>{(username)}</p>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コンテキストを取ってくるには {{ username }} って {{ }} で囲ってあげてください!


{% endblock %}
Loading