Skip to content
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
9 changes: 8 additions & 1 deletion Users/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
from django.contrib import admin
from .models import Country

# Register your models here.
class CountryAdmin(admin.ModelAdmin):
pass

admin.site.register(Country, CountryAdmin)

# 'Countrys' 텍스트를 'Countries'로 수정
admin.site.verbose_name_plural = 'Countries'
36 changes: 35 additions & 1 deletion Users/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,37 @@
from django.db import models
from django.contrib.auth.models import BaseUserManager

# Create your models here.
class Country(models.Model):
name = models.CharField(max_length=100)

def __str__(self):
return self.name
from django.contrib.auth.models import BaseUserManager

class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError('The Email field must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)

if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')

return self.create_user(email, password, **extra_fields)

class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
password = models.CharField(max_length=100)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
objects=UserManager()
19 changes: 19 additions & 0 deletions Users/templates/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<title>로그인</title>
</head>
<body>
<h1>로그인</h1>
<form action="{% url 'login' %}" method="post">
{% csrf_token %}
<label for="login-name">이름:</label>
<input type="text" id="login-name" name="name" required><br><br>

<label for="login-password">비밀번호:</label>
<input type="password" id="login-password" name="password" required><br><br>

<button type="submit">로그인</button>
</form>
</body>
</html>
19 changes: 19 additions & 0 deletions Users/templates/main.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<title>메인 페이지</title>
</head>
<body>
<h1>메인 페이지</h1>
{% if user.is_authenticated %}
<p>로그인된 사용자: {{ user.username }}</p>
<form action="{% url 'logout' %}" method="post">
{% csrf_token %}
<button type="submit">로그아웃</button>
</form>
{% else %}
<p>로그인 안 됨</p>
<a href="{% url 'login' %}">로그인</a>
{% endif %}
</body>
</html>
12 changes: 12 additions & 0 deletions Users/templates/signup_complete.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<title>회원가입 완료</title>
</head>
<body>
<h1>회원가입이 완료되었습니다!</h1>
<p>이름: {{ name }}</p>
<p>나라: {{ country }}</p>
<p><a href="/">메인페이지로 가기</a></p>
</body>
</html>
29 changes: 29 additions & 0 deletions Users/templates/signup_form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html>
<head>
<title>회원가입</title>
</head>
<body>
<h1>회원가입</h1>
<form method="post">
{% csrf_token %}
<label for="signup-name">이름:</label>
<input type="text" id="signup-name" name="name" required><br><br>

<label for="signup-password">비밀번호:</label>
<input type="password" id="signup-password" name="password" required><br><br>

<label for="signup-country">나라:</label>
<select id="signup-country" name="country" required>
<option value="" disabled selected>나라 선택</option>
<!-- 나라 목록을 드롭다운 옵션으로 추가 -->
{% for country in countries %}
<option value="{{ country.id }}">{{ country.name }}</option>
{% endfor %}
<!-- 나라 옵션들을 추가하세요 -->
</select><br><br>

<button type="submit">가입하기</button>
</form>
</body>
</html>
60 changes: 59 additions & 1 deletion Users/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,61 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.hashers import make_password
from django.contrib.auth import authenticate, logout
from django.conf import settings
import jwt
from django.shortcuts import render

# Create your views here.
from .models import User
from .models import Country
from django.contrib.sessions.backends.db import SessionStore

class CountriesListView(APIView):
def get(self, request):
countries = Country.objects.all()
return render(request, 'signup_form.html', {'countries': countries})
# countries = Country.objects.all().values_list('name', flat=True)
# return Response(countries)

class SignupView(APIView):
def get(self, request):
countries = Country.objects.all()
context = {'countries': countries}
return render(request, 'signup_form.html', context)

def post(self, request):
name = request.data.get('name')
password = request.data.get('password')
country = request.data.get('country')

hashed_password = make_password(password)
user = User.objects.create(name=name, password=hashed_password, country=country)

payload = {'user_id': user.id, 'name': user.name, 'country': user.country} # type: ignore
token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')

# 회원가입이 완료되었다는 문구, 메인페이지로 가기 버튼 있는 페이지로
context = {'name': name}
return render(request, 'signup_complete.html', context)

class LoginView(APIView):
def get(self, request):
return render(request, 'login.html')

def post(self, request):
name = request.data.get('name')
password = request.data.get('password')

user = authenticate(request, username=name, password=password)
if user:
payload = {'user_id': user.id, 'name': user.name, 'country': user.country} # type: ignore
token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
return Response({'token': token})
else:
return Response({'message': 'Login failed.'}, status=status.HTTP_401_UNAUTHORIZED)

class LogoutView(APIView):
def post(self, request):
logout(request)
return Response({'message': 'Logged out.'})
2 changes: 1 addition & 1 deletion config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
Expand Down
10 changes: 9 additions & 1 deletion config/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,16 @@
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from Users import views
from Users.views import SignupView, LoginView, LogoutView, CountriesListView

urlpatterns = [
path('admin/', admin.site.urls),
path('signup/', SignupView.as_view(), name='signup'),
path('api/signup/', SignupView.as_view(), name='api-signup'),
path('login/', LoginView.as_view(), name='login'),
path('logout/', LogoutView.as_view(), name='logout'),
path('countries/', CountriesListView.as_view(), name='countries-list'),
]
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
#+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)