diff --git a/app/apply/admin.py b/app/apply/admin.py index 5864e5c..cb4bf6d 100644 --- a/app/apply/admin.py +++ b/app/apply/admin.py @@ -9,15 +9,33 @@ from django.shortcuts import get_object_or_404 - -@admin.action(description='csv 파일 다운로드') +@admin.action(description="csv 파일 다운로드") def get_all_resume(self, request, queryset): meta = self.model._meta - field_names = ['name', 'applicant', 'phone', 'semester', 'introduce', 'motivate', 'to_do', 'etc', 'fixed_interview_time'] - excel_row = ['이름', '학번', '전화번호','학기', '자기소개', '지원동기', '하고 싶은 것' , '기타', '면접 일자'] - response = HttpResponse(content_type='text/csv') - response['Content-Disposition'] = 'attachment; filename={}.csv'.format( - meta) + field_names = [ + "name", + "applicant", + "phone", + "semester", + "introduce", + "motivate", + "to_do", + "etc", + "fixed_interview_time", + ] + excel_row = [ + "이름", + "학번", + "전화번호", + "학기", + "자기소개", + "지원동기", + "하고 싶은 것", + "기타", + "면접 일자", + ] + response = HttpResponse(content_type="text/csv") + response["Content-Disposition"] = "attachment; filename={}.csv".format(meta) writer = csv.writer(response) writer.writerow(excel_row) @@ -26,85 +44,109 @@ def get_all_resume(self, request, queryset): return response -@admin.action(description='면접 시간 자동 배치') -def set_interview_time(self, request, queryset): #self = resume model , queryset = 체크했던 object들 + +@admin.action(description="면접 시간 자동 배치") +def set_interview_time( + self, request, queryset +): # self = resume model , queryset = 체크했던 object들 times = [queryset.time for queryset in InterviewTime.objects.all()] meta = self.model._meta - q = Resume.objects.annotate(c=Count('interview_time_choice')).order_by('c') + q = Resume.objects.annotate(c=Count("interview_time_choice")).order_by("c") for i in q: for j in i.interview_time_choice.all(): - if j.time in times : + if j.time in times: time_num = 0 s = Resume.objects.annotate() - for _resume in s: #resume에 대해 call하는 부분 문제 어떤방식으로 call해야하나? - if j.time==_resume.fixed_interview_time: time_num = time_num + 1 - if time_num==1: + for ( + _resume + ) in s: # resume에 대해 call하는 부분 문제 어떤방식으로 call해야하나? + if j.time == _resume.fixed_interview_time: + time_num = time_num + 1 + if time_num == 1: plus20 = j.time + datetime.timedelta(minutes=20) a = Resume.objects.annotate() for Res in a: - if plus20 == Res.fixed_interview_time: time_num = time_num + 1 - if time_num == 2: #2개 있을 때 + if plus20 == Res.fixed_interview_time: + time_num = time_num + 1 + if time_num == 2: # 2개 있을 때 i.fixed_interview_time = plus20 + datetime.timedelta(minutes=20) i.save() j.is_fixed = True j.save() times.remove(j.time) break - - else: #1개 있을 + + else: # 1개 있을 i.fixed_interview_time = plus20 i.save() break - - else: # 0개일때 + + else: # 0개일때 i.fixed_interview_time = j.time i.save() break + @admin.action(description="면접 장소 일괄 지정") -def set_interview_place(self,request,queryset): +def set_interview_place(self, request, queryset): place = get_object_or_404(InterviewPlace) for query in queryset: query.interview_place = place query.save() + @admin.action(description="일괄 서류 불합격") -def set_doc_fail(self,request,queryset): +def set_doc_fail(self, request, queryset): for _resume in queryset: _resume.is_pass_document = False _resume.save() + @admin.action(description="일괄 서류 합격") -def set_doc_pass(self,request,queryset): +def set_doc_pass(self, request, queryset): for _resume in queryset: _resume.is_pass_document = True _resume.save() + @admin.action(description="일괄 최종 합격") -def set_final_pass(self,request,queryset): +def set_final_pass(self, request, queryset): for _resume in queryset: _resume.is_pass_final = True _resume.save() + @admin.action(description="일괄 최종 불합격") -def set_final_fail(self,request,queryset): +def set_final_fail(self, request, queryset): for _resume in queryset: _resume.is_pass_final = False _resume.save() + @admin.register(Resume) class ResumeAdmin(admin.ModelAdmin): - list_display = ('name', 'semester', - 'phone', 'fixed_interview_time','interview_place') - search_fields = ['name','applicant__student_id','introduce','motivate'] - actions=[get_all_resume,set_interview_time,set_interview_place,set_doc_fail,set_doc_pass,set_final_pass,set_final_fail] - + list_display = ( + "name", + "semester", + "phone", + "fixed_interview_time", + "interview_place", + ) + search_fields = ["name", "applicant__student_id", "introduce", "motivate"] + actions = [ + get_all_resume, + set_interview_time, + set_interview_place, + set_doc_fail, + set_doc_pass, + set_final_pass, + set_final_fail, + ] def get_ordering(self, request): - return ['fixed_interview_time'] - + return ["fixed_interview_time"] admin.site.register(InterviewPlace) diff --git a/app/apply/models.py b/app/apply/models.py index edf7b01..82f4a1d 100644 --- a/app/apply/models.py +++ b/app/apply/models.py @@ -2,15 +2,18 @@ from django.utils import timezone from user.models import Applicant + class TermType(models.TextChoices): - SPRING = 'spring' - FALL = 'fall' + SPRING = "spring" + FALL = "fall" + class RecruitProcess(models.TextChoices): - CLOSE = 'close' - APPLY = 'apply' - MIDDLE = 'middle' - FINAL = 'final' + CLOSE = "close" + APPLY = "apply" + MIDDLE = "middle" + FINAL = "final" + class Recruitment(models.Model): year = models.PositiveSmallIntegerField() @@ -21,54 +24,62 @@ class Recruitment(models.Model): interview_start_time = models.DateField() interview_end_time = models.DateField() announce_final_time = models.DateTimeField() - process = models.CharField(max_length=10, choices=RecruitProcess.choices ,default=RecruitProcess.CLOSE) + process = models.CharField( + max_length=10, choices=RecruitProcess.choices, default=RecruitProcess.CLOSE + ) def check_process(self): now = timezone.now() - if now >= self.announce_final_time : + if now >= self.announce_final_time: self.process = RecruitProcess.FINAL - elif now >= self.announce_middle_time : + elif now >= self.announce_middle_time: self.process = RecruitProcess.MIDDLE - elif now.date() >= self.start_time : + elif now.date() >= self.start_time: self.process = RecruitProcess.APPLY - else : + else: self.process = RecruitProcess.CLOSE self.save() - + + class InterviewTime(models.Model): time = models.DateTimeField() is_fixed = models.BooleanField(default=False) def __str__(self): return self.time.strftime("%Y/%m/%d %H:%M:%S") - + + class InterviewPlace(models.Model): place = models.CharField(max_length=20) def __str__(self): return self.place + class Resume(models.Model): - applicant = models.OneToOneField(Applicant,on_delete=models.CASCADE) + applicant = models.OneToOneField(Applicant, on_delete=models.CASCADE) phone = models.CharField(max_length=20) name = models.CharField(max_length=20) semester = models.PositiveSmallIntegerField() - #지원서 답변 - introduce = models.TextField(default='') - motivate = models.TextField(default='') - to_do = models.TextField(default='') - etc = models.TextField(default='') - - interview_time_choice = models.ManyToManyField(InterviewTime,related_name="interview_time") - fixed_interview_time = models.DateTimeField(null=True,blank=True) - interview_requirement = models.TextField(default='') - interview_place = models.ForeignKey(InterviewPlace,on_delete=models.CASCADE,null=True,blank=True) + # 지원서 답변 + introduce = models.TextField(default="") + motivate = models.TextField(default="") + to_do = models.TextField(default="") + etc = models.TextField(default="") + + interview_time_choice = models.ManyToManyField( + InterviewTime, related_name="interview_time" + ) + fixed_interview_time = models.DateTimeField(null=True, blank=True) + interview_requirement = models.TextField(default="") + interview_place = models.ForeignKey( + InterviewPlace, on_delete=models.CASCADE, null=True, blank=True + ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_pass_document = models.BooleanField(default=True) is_pass_final = models.BooleanField(default=False) - def __str__(self): return self.name diff --git a/app/apply/serializers.py b/app/apply/serializers.py index f7a3df5..1c40186 100644 --- a/app/apply/serializers.py +++ b/app/apply/serializers.py @@ -1,28 +1,40 @@ from rest_framework import serializers from apply.models import * from user.serializers import * + + class RecruitSerializer(serializers.ModelSerializer): class Meta: model = Recruitment - fields = '__all__' + fields = "__all__" class InterviewtimeSerializer(serializers.ModelSerializer): class Meta: model = InterviewTime - fields = '__all__' + fields = "__all__" class ResumeSerializer(serializers.ModelSerializer): - + class Meta: model = Resume - fields = ['interview_time_choice', 'name', 'semester', 'phone', - 'introduce', 'motivate', 'to_do', 'etc', 'applicant', 'updated_at'] + fields = [ + "interview_time_choice", + "name", + "semester", + "phone", + "introduce", + "motivate", + "to_do", + "etc", + "applicant", + "updated_at", + ] def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass - fields = kwargs.pop('interview_requirement', None) + fields = kwargs.pop("interview_requirement", None) # Instantiate the superclass normally super().__init__(*args, **kwargs) @@ -33,6 +45,7 @@ def __init__(self, *args, **kwargs): existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) + # def update(self, instance, validated_data): # nested_serializer = self.fields['interview_time_choice'] # nested_instance = instance.interview_time_choice @@ -42,7 +55,7 @@ def __init__(self, *args, **kwargs): # # this will not throw an exception, # # as `profile` is not part of `validated_data` # return super(ResumeSerializer, self).update(instance, validated_data) - + # def create(self, validated_data): # times = validated_data.pop('interview_time_choice') # print(times) @@ -54,15 +67,32 @@ def __init__(self, *args, **kwargs): # resume.save() # return resume + class ResumeRequestSerializer(serializers.ModelSerializer): class Meta: model = Resume - fields = ['interview_time_choice', 'name', 'semester', 'phone', - 'introduce', 'motivate', 'to_do', 'etc', 'interview_requirement'] + fields = [ + "interview_time_choice", + "name", + "semester", + "phone", + "introduce", + "motivate", + "to_do", + "etc", + "interview_requirement", + ] class ResultSerializer(serializers.ModelSerializer): - interview_place = serializers.CharField(source='interview_place.place') + interview_place = serializers.CharField(source="interview_place.place") + class Meta: model = Resume - fields = ['name','fixed_interview_time','interview_place','is_pass_document','is_pass_final'] + fields = [ + "name", + "fixed_interview_time", + "interview_place", + "is_pass_document", + "is_pass_final", + ] diff --git a/app/apply/urls.py b/app/apply/urls.py index c5db8cd..31d83bc 100644 --- a/app/apply/urls.py +++ b/app/apply/urls.py @@ -3,8 +3,8 @@ from apply.views import * urlpatterns = [ - path('recruit/', get_recuit_session, name='get_recuit_session'), - path('resume/', ResumeAPI.as_view(), name='resume_api'), - path('interview/', get_interview_time_list, name='get_interview_time_list'), - path('result/', get_result, name='get_result'), + path("recruit/", get_recuit_session, name="get_recuit_session"), + path("resume/", ResumeAPI.as_view(), name="resume_api"), + path("interview/", get_interview_time_list, name="get_interview_time_list"), + path("result/", get_result, name="get_result"), ] diff --git a/app/apply/views.py b/app/apply/views.py index fac04e1..c4fa439 100644 --- a/app/apply/views.py +++ b/app/apply/views.py @@ -1,5 +1,9 @@ from rest_framework.response import Response -from rest_framework.decorators import api_view, permission_classes, authentication_classes +from rest_framework.decorators import ( + api_view, + permission_classes, + authentication_classes, +) from rest_framework.views import APIView from django.http import Http404 from django.shortcuts import get_object_or_404 @@ -12,76 +16,93 @@ from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated -#TODO -@swagger_auto_schema(method="get",responses=get_recuit_session_response) -@api_view(['GET']) + +# TODO +@swagger_auto_schema(method="get", responses=get_recuit_session_response) +@api_view(["GET"]) def get_recuit_session(request): session = get_object_or_404(Recruitment) session.check_process() serializer = RecruitSerializer(session) return Response(serializer.data, status=200) + class ResumeAPI(APIView): authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] - def get_object(self,applicant): - - return get_object_or_404(Resume,applicant=applicant) - - - @swagger_auto_schema(responses=get_resume_response,authentication_classes=[BasicAuthentication]) - def get(self,request): + def get_object(self, applicant): + + return get_object_or_404(Resume, applicant=applicant) + + @swagger_auto_schema( + responses=get_resume_response, authentication_classes=[BasicAuthentication] + ) + def get(self, request): if request.user.is_authenticated: resume = self.get_object(request.user) serializer = ResumeSerializer(resume) return Response(serializer.data, status=200) else: return Response(status=401) - - @swagger_auto_schema(request_body=ResumeRequestSerializer,authentication_classes=[BasicAuthentication]) - def post(self,request): + + @swagger_auto_schema( + request_body=ResumeRequestSerializer, + authentication_classes=[BasicAuthentication], + ) + def post(self, request): if request.user.is_authenticated: - request.data['applicant'] = request.user.id + request.data["applicant"] = request.user.id serializer = ResumeSerializer(data=request.data) if serializer.is_valid(): serializer.save() - return Response(serializer.data,status=200) + return Response(serializer.data, status=200) else: - return Response(serializer.errors,status=400) #지원서 수정하는데 잘못 save되면 응답 & status # + return Response( + serializer.errors, status=400 + ) # 지원서 수정하는데 잘못 save되면 응답 & status # else: return Response(status=401) - @swagger_auto_schema(request_body=ResumeSerializer,authentication_classes=[BasicAuthentication]) - def patch(self,request): + @swagger_auto_schema( + request_body=ResumeSerializer, authentication_classes=[BasicAuthentication] + ) + def patch(self, request): if request.user.is_authenticated: resume = self.get_object(request.user) serializer = ResumeSerializer(resume, data=request.data, partial=True) - #print(request.data) + # print(request.data) if serializer.is_valid(): serializer.save() - return Response(serializer.data,status=200) + return Response(serializer.data, status=200) else: - return Response(serializer.errors,status=400) #지원서 수정하는데 잘못 save되면 응답 & status # + return Response( + serializer.errors, status=400 + ) # 지원서 수정하는데 잘못 save되면 응답 & status # else: return Response(stauts=401) + @swagger_auto_schema(method="get", responses=get_interview_response) -@api_view(['GET']) +@api_view(["GET"]) def get_interview_time_list(reqeust): - times = InterviewTime.objects.all().order_by('time') - serializer = InterviewtimeSerializer(times,many=True) - return Response(serializer.data,status=200) + times = InterviewTime.objects.all().order_by("time") + serializer = InterviewtimeSerializer(times, many=True) + return Response(serializer.data, status=200) -@swagger_auto_schema(method="get", responses=get_result_response, authentication_classes=[BasicAuthentication]) +@swagger_auto_schema( + method="get", + responses=get_result_response, + authentication_classes=[BasicAuthentication], +) @permission_classes([IsAuthenticated]) @authentication_classes([BasicAuthentication]) -@api_view(['GET']) +@api_view(["GET"]) def get_result(request): if request.user.is_authenticated: - resume = get_object_or_404(Resume,applicant=request.user) + resume = get_object_or_404(Resume, applicant=request.user) serializer = ResultSerializer(resume) - return Response(serializer.data,status=200) + return Response(serializer.data, status=200) else: - return Response(status=401) \ No newline at end of file + return Response(status=401) diff --git a/app/cspc_web/settings.py b/app/cspc_web/settings.py index 905c243..ea68552 100644 --- a/app/cspc_web/settings.py +++ b/app/cspc_web/settings.py @@ -72,14 +72,14 @@ ] MIDDLEWARE = [ + "django.middleware.common.CommonMiddleware", + "corsheaders.middleware.CorsMiddleware", "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", - "corsheaders.middleware.CorsMiddleware", ] ROOT_URLCONF = "cspc_web.urls" diff --git a/app/cspc_web/urls.py b/app/cspc_web/urls.py index fd5224a..5c2e5a2 100644 --- a/app/cspc_web/urls.py +++ b/app/cspc_web/urls.py @@ -13,10 +13,11 @@ 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ + import os from django.contrib import admin from rest_framework import permissions -from django.urls import path, include,re_path +from django.urls import path, include, re_path from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework.authentication import SessionAuthentication, BasicAuthentication @@ -24,29 +25,35 @@ schema_view = get_schema_view( openapi.Info( title="Snippets API", - default_version='v1', + default_version="v1", description="Test description", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), - ), - url=os.environ.get('HOST'), + url=os.environ.get("HOST"), public=True, permission_classes=[permissions.AllowAny], - authentication_classes=[BasicAuthentication] + authentication_classes=[BasicAuthentication], ) urlpatterns = [ - path('accounts/', include('django.contrib.auth.urls')), - path('admin/', admin.site.urls), - path('api/apply/', include("apply.urls")), - path('api/user/', include('user.urls')), - re_path(r'^swagger(?P\.json|\.yaml)$', - schema_view.without_ui(cache_timeout=0), name='schema-json'), - re_path(r'^swagger/$', schema_view.with_ui('swagger', - cache_timeout=0), name='schema-swagger-ui'), - re_path(r'^redoc/$', schema_view.with_ui('redoc', - cache_timeout=0), name='schema-redoc'), + path("accounts/", include("django.contrib.auth.urls")), + path("admin/", admin.site.urls), + path("api/apply/", include("apply.urls")), + path("api/user/", include("user.urls")), + re_path( + r"^swagger(?P\.json|\.yaml)$", + schema_view.without_ui(cache_timeout=0), + name="schema-json", + ), + re_path( + r"^swagger/$", + schema_view.with_ui("swagger", cache_timeout=0), + name="schema-swagger-ui", + ), + re_path( + r"^redoc/$", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc" + ), ] diff --git a/app/cspc_web/wsgi.py b/app/cspc_web/wsgi.py index 5c69253..d061faf 100644 --- a/app/cspc_web/wsgi.py +++ b/app/cspc_web/wsgi.py @@ -11,6 +11,6 @@ from django.core.wsgi import get_wsgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cspc_web.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cspc_web.settings") application = get_wsgi_application() diff --git a/app/manage.py b/app/manage.py index 49079fa..7d8ecfa 100755 --- a/app/manage.py +++ b/app/manage.py @@ -6,7 +6,7 @@ def main(): """Run administrative tasks.""" - os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cspc_web.settings') + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cspc_web.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: @@ -18,5 +18,5 @@ def main(): execute_from_command_line(sys.argv) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/app/swagger_response.py b/app/swagger_response.py index 9d2f5b1..7fc493f 100644 --- a/app/swagger_response.py +++ b/app/swagger_response.py @@ -4,13 +4,19 @@ from apply.serializers import * check_id_response = openapi.Responses( - responses={200: "첫 지원자", 201: "기존 지원자", 500: "로그인 실패", 404: "request data 없음"}) + responses={ + 200: "첫 지원자", + 201: "기존 지원자", + 500: "로그인 실패", + 404: "request data 없음", + } +) get_master_info_response = openapi.Responses(responses={200: LabMasterSerializer()}) get_recuit_session_response = openapi.Responses( - responses={200: RecruitSerializer(), 404 : "Not found"} + responses={200: RecruitSerializer(), 404: "Not found"} ) get_resume_response = openapi.Responses( @@ -22,5 +28,5 @@ ) get_result_response = openapi.Responses( - responses={200: ResultSerializer(),404 : "Not found"} -) \ No newline at end of file + responses={200: ResultSerializer(), 404: "Not found"} +) diff --git a/app/user/admin.py b/app/user/admin.py index b654411..d15dbeb 100644 --- a/app/user/admin.py +++ b/app/user/admin.py @@ -5,6 +5,7 @@ from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError + class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" @@ -45,8 +46,7 @@ class UserChangeForm(forms.ModelForm): class Meta: model = Applicant - fields = ["student_id", "password", - "is_active"] + fields = ["student_id", "password", "is_active"] class UserAdmin(BaseUserAdmin): @@ -60,7 +60,6 @@ class UserAdmin(BaseUserAdmin): list_display = ["student_id"] fieldsets = [ (None, {"fields": ["student_id", "password"]}), - ] # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. @@ -69,7 +68,7 @@ class UserAdmin(BaseUserAdmin): None, { "classes": ["wide"], - "fields": ["student_id", "password1", "password2"], + "fields": ["student_id", "password1", "password2"], }, ), ] @@ -77,6 +76,7 @@ class UserAdmin(BaseUserAdmin): ordering = ["student_id"] filter_horizontal = [] + # Now register the new UserAdmin... admin.site.register(Applicant, UserAdmin) admin.site.register(LabMaster) diff --git a/app/user/backends.py b/app/user/backends.py index 4b3e3df..faadf97 100644 --- a/app/user/backends.py +++ b/app/user/backends.py @@ -1,6 +1,7 @@ from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend + class StudentIDBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() @@ -11,4 +12,4 @@ def authenticate(self, request, username=None, password=None, **kwargs): else: if user.check_password(password): return user - return None \ No newline at end of file + return None diff --git a/app/user/models.py b/app/user/models.py index 8bf9c6b..1ebdc22 100644 --- a/app/user/models.py +++ b/app/user/models.py @@ -1,7 +1,7 @@ from django.db import models from django.db.models.signals import post_init, post_save from django.dispatch import receiver -from django.contrib.auth.models import AbstractUser ,BaseUserManager +from django.contrib.auth.models import AbstractUser, BaseUserManager from django.contrib.auth.base_user import BaseUserManager @@ -13,7 +13,7 @@ def _create_user(self, student_id, password, **extra_fields): Creates and saves a User with the given email and password. """ if not student_id: - raise ValueError('The given student_id must be set') + raise ValueError("The given student_id must be set") user = self.model(student_id=student_id, **extra_fields) user.set_password(password) @@ -21,26 +21,29 @@ def _create_user(self, student_id, password, **extra_fields): return user def create_user(self, student_id, password=None, **extra_fields): - extra_fields.setdefault('is_superuser', False) + extra_fields.setdefault("is_superuser", False) return self._create_user(student_id, password, **extra_fields) def create_superuser(self, student_id, password, **extra_fields): - extra_fields.setdefault('is_superuser', True) - extra_fields.setdefault('is_staff', True) - if extra_fields.get('is_superuser') is not True: - raise ValueError('Superuser must have is_superuser=True.') + extra_fields.setdefault("is_superuser", True) + extra_fields.setdefault("is_staff", True) + if extra_fields.get("is_superuser") is not True: + raise ValueError("Superuser must have is_superuser=True.") return self._create_user(student_id, password, **extra_fields) + class Applicant(AbstractUser): - student_id = models.CharField(max_length=20,unique=True) + student_id = models.CharField(max_length=20, unique=True) username = None - USERNAME_FIELD = 'student_id' + USERNAME_FIELD = "student_id" REQUIRED_FIELDS = [] object = UserManager() + def __str__(self): return self.student_id + class LabMaster(models.Model): name = models.CharField(max_length=20) email = models.EmailField(max_length=30) @@ -49,7 +52,6 @@ class LabMaster(models.Model): def __str__(self): return self.name - # 랩짱 변경 시 기존 랩장 비활성화 diff --git a/app/user/serializers.py b/app/user/serializers.py index 3701c42..293a81a 100644 --- a/app/user/serializers.py +++ b/app/user/serializers.py @@ -2,12 +2,14 @@ from user.models import LabMaster, Applicant + class LabMasterSerializer(serializers.ModelSerializer): class Meta: model = LabMaster - fields = ('name','email','phone') + fields = ("name", "email", "phone") + class ApplicantSerializer(serializers.ModelSerializer): class Meta: model = Applicant - fields = ('student_id','password') \ No newline at end of file + fields = ("student_id", "password") diff --git a/app/user/urls.py b/app/user/urls.py index 79afa34..083d5fc 100644 --- a/app/user/urls.py +++ b/app/user/urls.py @@ -1,6 +1,7 @@ from django.urls import path from user.views import check_applicant, get_master_info + urlpatterns = [ - path('check-id',check_applicant), - path('master',get_master_info), + path("check-id/", check_applicant), + path("master/", get_master_info), ] diff --git a/app/user/views.py b/app/user/views.py index bf917fb..9702383 100644 --- a/app/user/views.py +++ b/app/user/views.py @@ -1,6 +1,6 @@ from rest_framework.decorators import api_view from django.shortcuts import get_object_or_404 -from user.models import Applicant , LabMaster +from user.models import Applicant, LabMaster from rest_framework.response import Response from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth import authenticate @@ -8,42 +8,46 @@ from drf_yasg.utils import swagger_auto_schema from swagger_response import * -@swagger_auto_schema(request_body=ApplicantSerializer, method='post', responses=check_id_response) -@api_view(['POST']) + +@swagger_auto_schema( + request_body=ApplicantSerializer, method="post", responses=check_id_response +) +@api_view(["POST"]) def check_applicant(request): try: - #request에서 이름, 패스워드 추출 - student_id = request.data['student_id'] - password = request.data['password'] - + # request에서 이름, 패스워드 추출 + student_id = request.data["student_id"] + password = request.data["password"] - user = authenticate(username=student_id,password=password) + user = authenticate(username=student_id, password=password) if user is None: - # 기존 지원자 로그인 성공 + # 기존 지원자 로그인 성공 if Applicant.objects.filter(student_id=student_id): return Response(status=500) # 새로운 지원자 else: recruit = Recruitment.objects.get() print(recruit.process) - if recruit.process != 'apply': + if recruit.process != "apply": return Response(status=405) - applicant = Applicant.object.create_user(student_id=student_id,password=password) - return Response(applicant.id,status=200) - - return Response(user.id,status=201) + applicant = Applicant.object.create_user( + student_id=student_id, password=password + ) + return Response(applicant.id, status=200) + + return Response(user.id, status=201) # request에서 이름, 패스워드 추출 실패 시 - except AttributeError: + except AttributeError: return Response(status=404) - - -@swagger_auto_schema(responses=get_master_info_response, method='get') -@api_view(['GET']) +@swagger_auto_schema(responses=get_master_info_response, method="get") +@api_view(["GET"]) def get_master_info(request): - master = get_object_or_404(LabMaster,is_active = True) + master = get_object_or_404(LabMaster, is_active=True) master_serializer = LabMasterSerializer(master) - return Response(master_serializer.data,status=200) + return Response(master_serializer.data, status=200) + + # Create your views here.