Fakultas Ilmu Komputer UI

Commit 67f2e354 authored by Muhammad Rafif Elfazri's avatar Muhammad Rafif Elfazri
Browse files

[REFACTOR] Refactor Create Fasilitas API by using unique_toegther constraint and serializer

parent 6eb4241a
Pipeline #80518 passed with stages
in 8 minutes and 43 seconds
# Generated by Django 3.1.7 on 2021-06-01 05:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('informasi_fasilitas', '0019_auto_20210527_2251'),
]
operations = [
migrations.AlterField(
model_name='kegiatan',
name='zona_waktu',
field=models.CharField(choices=[('WIB', 'WIB'), ('WITA', 'WITA'), ('WIT', 'WIT')], default='WIB', max_length=4),
),
migrations.AlterUniqueTogether(
name='fasilitas',
unique_together={('lokasi', 'tag')},
),
]
......@@ -79,6 +79,9 @@ class Fasilitas(models.Model):
image = models.ImageField(upload_to="fasilitas/", null=True, default=None)
is_verified = models.BooleanField(default=False)
class Meta:
unique_together = ('lokasi', 'tag')
class Kegiatan(models.Model):
objects = models.Manager()
......
from http import HTTPStatus
from django.http import JsonResponse
from django.db.utils import IntegrityError
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.exceptions import ValidationError
from notification.utils import send_komentar_notification
from .serializers import LokasiSerializer, FasilitasSerializerRead, FasilitasSerializerWrite
......@@ -70,34 +72,28 @@ def list_fasilitas(request, place_id):
def add_fasilitas(request, place_id):
try:
lokasi = Lokasi.objects.get(place_id=place_id)
deskripsi = request.POST['deskripsi']
rating = request.POST['rating']
tag = request.POST['tag']
disabilitas = request.POST['disabilitas']
jumlah = request.POST['jumlah']
image = ""
if Fasilitas.objects.filter(lokasi=lokasi.pk, tag=tag).count() > 0:
return JsonResponse({'response': 'fasilitas already exist'},
status=HTTPStatus.OK)
if tag == "":
return JsonResponse({'response': 'tag cannot be null'},
status=HTTPStatus.BAD_REQUEST)
if 'image' in request.FILES.keys():
image = request.FILES['image']
fasilitas = Fasilitas.objects.create(lokasi=lokasi,
user=request.user,
deskripsi=deskripsi,
rating=rating,
tag=tag,
disabilitas=disabilitas,
jumlah=jumlah,
image=image)
user = request.user
data = request.data.dict()
data.update({"lokasi": lokasi.id, "user": user.id})
serializer = FasilitasSerializerWrite(data=data)
serializer.is_valid(raise_exception=True)
fasilitas = serializer.save()
return JsonResponse({'response': 'fasilitas added', 'id': fasilitas.id},
status=HTTPStatus.CREATED)
except KeyError as missing_key:
return JsonResponse({'response': missing_key_message(str(missing_key))},
status=HTTPStatus.BAD_REQUEST)
except Exception as error:
except ValidationError as error:
error_detail = error.get_full_details()
if 'non_field_errors' in error_detail:
return JsonResponse({'response': 'fasilitas already exist'},
status=HTTPStatus.OK)
if "tag" in error_detail:
if error_detail["tag"][0]["code"] == 'invalid_choice':
return JsonResponse({'response': 'tag cannot be null'},
status=HTTPStatus.BAD_REQUEST)
else:
return JsonResponse({'response': "Bad Request. 'tag' key is needed"},
status=HTTPStatus.BAD_REQUEST)
raise error
except Lokasi.DoesNotExist as error:
return JsonResponse({'response': str(error)}, status=HTTPStatus.NOT_FOUND)
......@@ -170,7 +166,6 @@ 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