Fakultas Ilmu Komputer UI

Commit b2450ca3 authored by Muhammad Rafif Elfazri's avatar Muhammad Rafif Elfazri
Browse files

[REFACTOR] Refactor on Fasilitas List, Detail, and Update

parent a9db0dcc
from rest_framework import serializers
from .models import Lokasi, Kegiatan, KomentarKegiatan, FotoKegiatan
from .models import Lokasi, Fasilitas, Kegiatan, KomentarKegiatan, FotoKegiatan
import pytz
TIMEZONE_INDONESIA = {
......@@ -33,6 +33,59 @@ class LokasiSerializer(serializers.ModelSerializer):
}
class FasilitasSerializer(serializers.ModelSerializer):
class Meta:
model = Fasilitas
fields = ("id", "date_time", "deskripsi", "like",
"dislike", "rating", "tag", "disabilitas",
"jumlah", "image", "is_verified")
class FasilitasSerializerWrite(FasilitasSerializer):
class Meta:
model = FasilitasSerializer.Meta.model
fields = FasilitasSerializer.Meta.fields + ('lokasi', 'user')
extra_kwargs = {
'lokasi': {'required': True},
'user': {'required': True},
'tag': {"required": True},
'deskripsi':{"required": True},
'rating': {"required": True},
'disabilitas': {"required": True},
'jumlah': {"required": True},
}
class FasilitasSerializerRead(FasilitasSerializer):
place_id = serializers.CharField(source='lokasi.place_id', read_only=True)
creator = serializers.CharField(source='user.last_name', read_only=True)
creator_email = serializers.CharField(source='user.email', read_only=True)
date_time = serializers.SerializerMethodField()
image = serializers.SerializerMethodField()
like = serializers.SerializerMethodField()
dislike = serializers.SerializerMethodField()
def get_date_time(self, obj):
time = obj.date_time
return time.strftime("%d-%m-%Y %H:%M:%S")
def get_image(self, obj):
image = obj.image
return '/media/' + str(image)
def get_like(self, obj):
likes = obj.likes_set.count()
return likes
def get_dislike(self, obj):
dislike = obj.dislikes_set.count()
return dislike
class Meta:
model = FasilitasSerializer.Meta.model
fields = FasilitasSerializer.Meta.fields + ('place_id', 'creator', "creator_email")
class FotoKegiatanSerializer(serializers.ModelSerializer):
place_id = serializers.CharField(source='kegiatan.lokasi.place_id', read_only=True)
......
......@@ -8,7 +8,7 @@ from rest_framework.response import Response
from rest_framework import viewsets
from notification.utils import send_komentar_notification
from .serializers import LokasiSerializer
from .serializers import LokasiSerializer, FasilitasSerializerRead, FasilitasSerializerWrite
from .models import Lokasi, Fasilitas, Komentar, Likes, Dislikes
from .permissions import UserPermission
......@@ -56,31 +56,10 @@ def list_fasilitas(request, place_id):
try:
lokasi = Lokasi.objects.get(place_id=place_id)
list_fasilitas = Fasilitas.objects.filter(lokasi=lokasi)
return_json = {}
for fasilitas in list_fasilitas:
user = fasilitas.user
fasilitas.like = Likes.objects.filter(
fasilitas=fasilitas).count()
fasilitas.dislike = Dislikes.objects.filter(
fasilitas=fasilitas).count()
return_json[fasilitas.id] = {}
fasilitas_details = return_json[fasilitas.id]
fasilitas_details["id"] = fasilitas.id
fasilitas_details["creator_email"] = user.email
fasilitas_details["place_id"] = fasilitas.lokasi.place_id
fasilitas_details["deskripsi"] = fasilitas.deskripsi
fasilitas_details["creator"] = fasilitas.user.last_name
fasilitas_details["date_time"] = fasilitas.date_time.strftime(
TIME_FORMAT)
fasilitas_details["like"] = fasilitas.like
fasilitas_details["dislike"] = fasilitas.dislike
fasilitas_details["rating"] = fasilitas.rating
fasilitas_details["tag"] = fasilitas.tag
fasilitas_details["disabilitas"] = fasilitas.disabilitas
fasilitas_details["jumlah"] = fasilitas.jumlah
fasilitas_details["image"] = '/media/'+str(fasilitas.image)
fasilitas_details["is_verified"] = fasilitas.is_verified
return JsonResponse(return_json, status=HTTPStatus.OK)
serializer = FasilitasSerializerRead(list_fasilitas, many=True)
data_response = serializer.data
new_dict = {item['id']: dict(item) for item in data_response}
return JsonResponse(new_dict, status=HTTPStatus.OK)
except Exception as error:
return JsonResponse({'response': str(error)}, status=HTTPStatus.NOT_FOUND)
......@@ -128,28 +107,8 @@ def add_fasilitas(request, place_id):
def detail_fasilitas(request, place_id, id):
try:
fasilitas = Fasilitas.objects.get(lokasi__place_id=place_id, id=id)
user = fasilitas.user
fasilitas.like = Likes.objects.filter(fasilitas=fasilitas).count()
fasilitas.dislike = Dislikes.objects.filter(
fasilitas=fasilitas).count()
return_json = {"id": fasilitas.id,
"place_id": fasilitas.lokasi.place_id,
"deskripsi": fasilitas.deskripsi,
"creator": user.last_name,
"creator_email": user.email,
"date_time": fasilitas.date_time.strftime(TIME_FORMAT),
"like": fasilitas.like,
"dislike": fasilitas.dislike,
"rating": fasilitas.rating,
"tag": fasilitas.tag,
"disabilitas": fasilitas.disabilitas,
"jumlah": fasilitas.jumlah,
"image": '/media/' + str(fasilitas.image),
"is_verified": fasilitas.is_verified}
return JsonResponse(return_json, status=HTTPStatus.OK)
except KeyError as missing_key:
return JsonResponse({'response': missing_key_message(str(missing_key))},
status=HTTPStatus.BAD_REQUEST)
serializer = FasilitasSerializerRead(fasilitas, many=False)
return JsonResponse(serializer.data, status=HTTPStatus.OK)
except Exception as error:
return JsonResponse({'response': str(error)}, status=HTTPStatus.NOT_FOUND)
......@@ -161,35 +120,15 @@ def update_fasilitas(request, place_id, id):
try:
fasilitas = Fasilitas.objects.get(lokasi__place_id=place_id, id=id)
user_creator = fasilitas.user
desc = fasilitas.deskripsi
tag = fasilitas.tag
jumlah = fasilitas.jumlah
image = fasilitas.image
disabilitas = fasilitas.disabilitas
if user_creator == request.user:
if 'deskripsi' in request.data.keys():
desc = request.data['deskripsi']
if 'tag' in request.data.keys():
tag = request.data['tag'].split()
if 'jumlah' in request.data.keys():
jumlah = request.data['jumlah']
if 'image' in request.data.keys():
image = request.data['image']
if 'disabilitas' in request.data.keys():
disabilitas = request.data['disabilitas']
fasilitas.deskripsi = desc
fasilitas.tag = tag
fasilitas.jumlah = jumlah
fasilitas.image = image
fasilitas.disabilitas = disabilitas
fasilitas.save()
data = request.data.dict()
serializer = FasilitasSerializerWrite(fasilitas, data=data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return JsonResponse({'response': '{} in fasilitas edited'.format(str(request.data.keys())), },
status=HTTPStatus.ACCEPTED)
return JsonResponse({'response': 'Authentication failed'},
status=HTTPStatus.UNAUTHORIZED)
except KeyError as missing_key:
return JsonResponse({'response': missing_key_message(str(missing_key))},
status=HTTPStatus.BAD_REQUEST)
except Exception as error:
return JsonResponse({'response': str(error)}, status=HTTPStatus.NOT_FOUND)
......@@ -231,6 +170,7 @@ def update_like_fasilitas(request, place_id, id, operation):
except KeyError as missing_key:
return JsonResponse({'response': missing_key_message(str(missing_key))}, status=HTTPStatus.BAD_REQUEST)
except Exception as error:
print(str(error))
return JsonResponse({'response': str(error)}, status=HTTPStatus.NOT_FOUND)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment