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

[euuunchae] 백엔드 장고 3주차 미션 제출합니다. #2

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
2 changes: 1 addition & 1 deletion functional_specification.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
- 출력 : 성공적으로 회원이 삭제되었음을 알림
- 참고 : 없음

# [미션 1] 회원 관리 앱 DB 테이블 설계
## [미션 1] 회원 관리 앱 DB 테이블 설계

회원 관리 앱의 기능 명세서를 기반으로, 앱에서 사용할 데이터베이스(DB) 테이블을 설계하는 것이 미션입니다. 회원의 필수 정보를 효과적으로 저장하고 관리할 수 있도록 DB 구조를 설계하고, 각 테이블과 필드에 대한 설명을 작성하세요.

Expand Down
Binary file added mission_course/db.sqlite3
Binary file not shown.
22 changes: 22 additions & 0 deletions mission_course/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mission.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
5 changes: 5 additions & 0 deletions mission_course/members/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.contrib import admin
from members.models import Member

# Register your models here.
admin.site.register(Member)
6 changes: 6 additions & 0 deletions mission_course/members/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class MembersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'members'
24 changes: 24 additions & 0 deletions mission_course/members/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 5.1.3 on 2024-12-26 07:43

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Member',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=10)),
('email', models.TextField(unique=True)),
('birth', models.DateField(null=True)),
('join_date', models.DateField()),
],
),
]
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
9 changes: 9 additions & 0 deletions mission_course/members/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.db import models

# Create your models here.

class Member(models.Model):
name = models.CharField(max_length=10)
email = models.TextField(unique=True)
birth = models.DateField(null=True)
join_date = models.DateField(auto_now_add=True)
13 changes: 13 additions & 0 deletions mission_course/members/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from rest_framework import serializers
from .models import Member

class MemberSerializer(serializers.ModelSerializer):
class Meta :
model = Member
fields = ['id', 'name', 'email', 'birth', 'join_date']


class MemberListSerializer(serializers.ModelSerializer):
class Meta :
model = Member
fields = ['id', 'name', 'email']
Empty file.
Empty file.
4 changes: 4 additions & 0 deletions mission_course/members/templates/member_detail.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<h>{{member.name}}</h1>
<p>{{member.email}}</p>
<p>{{member.birth}}</p>
<p>{{member.join_date}}</p>
5 changes: 5 additions & 0 deletions mission_course/members/templates/member_list.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<ol>
{%for member in members%}
<a href="/members/{{member.id}}"><li>{{member.member_id}}</li></a>
{% endfor %}
</ol>
3 changes: 3 additions & 0 deletions mission_course/members/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
56 changes: 56 additions & 0 deletions mission_course/members/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
from .models import Member
#from django.shortcuts import render, redirect
#from django.http import JsonResponse

from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import MemberSerializer
from .serializers import MemberListSerializer

# 회원 전체 목록 조회
@api_view(['GET'])
def member_list(request):
members = Member.objects.all()
serializer = MemberListSerializer(members, many=True)
return Response(serializer.data)

# 회원 가입
@api_view(['POST'])
def member_create(request):
serializer = MemberSerializer(data = request.data)
if serializer.is_valid():
serializer.save()
return Response({"data" : serializer.data, "message" : "가입되었습니다."}, status=200)
return Response(serializer.errors, status=400)


@api_view(['GET','PUT','DELETE'])
def member_detail(request, member_id):
try:
member = Member.objects.get(id=member_id)
except Member.DoesNotExist:
return Response({"message" : "존재하지 않는 사용자입니다."}, status=404)

if request.method == 'GET': # 회원 상세 조회
serializer = MemberSerializer(member)
return Response(serializer.data)

elif request.method == 'PUT': # 회원 정보 수정
serializer = MemberSerializer(member, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=200)
return Response(serializer.errors, status=400)


elif request.method == 'DELETE': #회원 삭제
member.delete()
return Response({"message" : "삭제되었습니다." }, status=200)








Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
16 changes: 16 additions & 0 deletions mission_course/mission/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for mission project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mission.settings')

application = get_asgi_application()
128 changes: 128 additions & 0 deletions mission_course/mission/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""
Django settings for mission project.

Generated by 'django-admin startproject' using Django 5.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!

SECRET_KEY = 'django-insecure-==_cax+f@j=%umo8m3@df=5@5gykf^h#j^q8q6acq#sk1q!ylt'


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members.apps.MembersConfig',
'rest_framework',
]


MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mission.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'mission.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/

LANGUAGE_CODE = 'ko-kr'

TIME_ZONE = 'Asia/Seoul'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
27 changes: 27 additions & 0 deletions mission_course/mission/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
URL configuration for mission project.

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from members import views

urlpatterns = [
path('admin/', admin.site.urls),
path('api/members/', views.member_list, name = 'member_list'),
path('api/members/<int:member_id>/', views.member_detail, name = 'member_detail/update/delete'),
path('api/members/create/', views.member_create, name = 'member_create'),
path('api/', include('rest_framework.urls')),
]
16 changes: 16 additions & 0 deletions mission_course/mission/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for mission project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mission.settings')

application = get_wsgi_application()