django ajax 처리
Template
<form action="." method="post">
<input id="point" name="point">
<button type="button" class="btn btn-primary" onclick="pointSave()">저장</button>
</form>
<script>
function pointSave() {
let point = $('#point').val();
$.ajax({
url: '.',
type: 'POST',
data: {
'point': point, 'csrfmiddlewaretoken': ''
},
dataType: 'json',
success: function(data) { // view의 context를 data로 받음
alert(data.message);
opener.parent.location.reload(); // 새로고침
window.close(); // 새로 열린 창닫기
},
error: function(data) {
alert(data.message);
}
});
}
</script>
View
class PointChargeView(AdminRequireMixin, generic.View):
def get(self, request, pk):
user = User.objects.get(id=pk)
context = {'user': user}
return render(request, 'help/admin/point_charge.html', context)
def post(self, request, pk):
path = request.path
context = {}
try:
with transaction.atomic():
if 'discharge' in path:
point = (-1) * int(request.POST.get('point'))
else:
point = int(request.POST.get('point'))
user = Profile.objects.get(user_id=pk)
user.rest_point += int(point)
user.save_point += int(point)
if user.rest_point < 0:
raise FloatingPointError
user.save(update_fields=['save_point', 'rest_point'])
point_history = PointHistory(user_id=pk,
charge_point=point,
remain_point=user.rest_point
)
point_history.save()
context['message'] = '처리되었습니다.'
except ValueError:
context['message'] = '문제가 발생하였습니다.'
# messages.error(request, '문제가 발생하였습니다.')
except FloatingPointError:
context['message'] = '포인트가 부족합니다.'
# messages.error(request, '포인트가 부족합니다.')
return HttpResponse(json.dumps(context), content_type="application/json")
→ HttpReponse(content, [content_type]) : json타입으로 context를 보냄