Commit a6c8c546 authored by cermak's avatar cermak
Browse files

REST api for adding logs

parent 04049d95
from django.contrib.auth.models import User
from django.db.models import Q
from app.models import Proposals, Publication
from app.models import Proposals, Publication, Log, Usage, Resource
from rest_framework import generics, permissions, serializers
from rest_framework.response import Response
......@@ -86,3 +86,42 @@ class PublicationsList(generics.ListAPIView):
permission_classes = []
serializer_class = PublicationSerializer
queryset = Publication.objects.all()
class UsageSerializer(serializers.ModelSerializer):
resource = serializers.CharField()
class Meta:
model = Usage
fields =('resource', 'amount')
class LogSerializer(serializers.ModelSerializer):
usage_set = UsageSerializer(many=True)
proposal = serializers.CharField()
class Meta:
model = Log
fields = (
'start', 'end', 'instrument', 'localcontact', 'creator', 'proposal', 'usage_set'
write_only_fields = ['usage_set']
read_only_fields = ['creator']
def validate(self, attrs):
attrs['creator'] = self.context['request']
return attrs
def create(self, validated_data):
used_data = validated_data.pop('usage_set')
proposal = validated_data.pop('proposal')
validated_data['proposal'] = Proposals.objects.get(pid=proposal)
log = super().create(validated_data)
for u in used_data:
resource = u.pop('resource')
u['resource'] = Resource.objects.get(name=resource)
Usage.objects.create(log=log, **u)
return log
class LogCreate(generics.CreateAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = LogSerializer
......@@ -12,7 +12,7 @@ from django.contrib.auth import views as auth_views
import app.forms
import app.views as views
from import MyProposalList, PublicationsList
from import MyProposalList, PublicationsList, LogCreate
# Uncomment the next lines to enable the admin:
from django.contrib import admin
......@@ -178,4 +178,5 @@ urlpatterns += (
urlpatterns += [
path('rest/activeproposals/', MyProposalList.as_view()),
path('rest/publications/', PublicationsList.as_view()),
path('rest/createlog/', LogCreate.as_view()),
\ No newline at end of file
Markdown is supported
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