# webmaster.view
class NoticeView(APIView):
def post(self, request):
request.data['user'] = request.user.id
notice_serializer = NoticeSerializer(data=request.data)
if notice_serializer.is_valid():
notice_serializer.save()
return Response({"message" : "๊ณต์ง์ฌํญ ์์ฑ์ ์ฑ๊ณตํ๋ค๋ถ!"}, status=status.HTTP_200_OK)
else:
print(notice_serializer.errors)
return Response({"message" : "๊ณต์ง์ฌํญ ์์ฑ์ ์คํจํ๋ค๋ถ..."}, status=status.HTTP_400_BAD_REQUEST)
# webmaster.test
class NoticeTest(APITestCase):
@classmethod
def setUpTestData(cls):
cls.user_data = {'username' : 'heejeong', 'password': '1234'}
cls.notice_data = {'title' : '์๋
' , 'content' : '๋ฐ๊ฐ์ต๋๋ค'}
cls.user = UserModel.objects.create_user('heejeong', '1234')
def setUp(self):
self.access_token = self.client.post(reverse('token_obtain_pair'), self.user_data).data['access']
# ๊ณต์ง์ฌํญ ๋ชฉ๋ก ์กฐํ API
def test_list_notice(self):
response = self.client.get(reverse('webmaster:list_notice'), self.data)
self.assertEqual(response.status_code,200)
# ๊ณต์ง์ฌํญ ์์ฑํ๊ธฐ API
def test_post_notice(self):
response = self.client.post(
path = reverse("webmaster:notice"),
data = self.notice_data,
HTTP_AUTHORIZATION = f"Bearer {self.access_token}"
)
self.assertEqual(response.status_code, 200)
AttributeError: This QueryDict instance is immutable
This QueryDict instance is immutable
def post(self, request):
'''
๊ธฐ์กด์ฝ๋
request.data['user'] = request.user.id
notice_serializer = NoticeSerializer(data=request.data)
'''
print(request.data) # ํ
์คํธ์ฝ๋ ์์์ QueryDict์ธ request.data์์ ์ฌ์ฉํ ์ ์๋ ๋ฉ์๋ ํ์ธ
request_data_copy = request.data.copy() # mutable ํ ๋์
๋๋ฆฌ๋ก ์นดํผํ๋ ๋ฉ์๋
request_data_copy['user'] = request.user.id
notice_serializer = NoticeSerializer(data=request_data_copy)
...
์๋ต
def post(self):
notice_serializer = NoticeSerializer(data=request.data)
if notice_serializer.is_valid():
notice_serializer.save(user=self.request.user)
return Response({"message" : "๊ณต์ง์ฌํญ ์์ฑ์ ์ฑ๊ณตํ๋ค๋ถ!"}, status=status.HTTP_200_OK)
else:
print(notice_serializer.errors)
return Response({"message" : "๊ณต์ง์ฌํญ ์์ฑ์ ์คํจํ๋ค๋ถ..."}, status=status.HTTP_400_BAD_REQUEST)