def createEvent(request): # product = Product.objects.get(id=pk) serializer = EventSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data)
def test_restaurants_endpoint(self): """Test that the endpoint only returns events with restaurant categories""" event1 = Event.objects.create(name='Restaurante', description='Desc 1', winery=self.winery, price=0.0) EventOccurrence.objects.create(start='2030-05-31T20:00:00', end='2030-05-31T23:00:00', vacancies=50, event=event1) event2 = Event.objects.create(name='Evento 1', description='Desc 1', winery=self.winery, price=0.0) EventOccurrence.objects.create(start='2030-05-31T20:00:00', end='2030-05-31T23:00:00', vacancies=50, event=event2) event1.categories.add(self.category_restaurant) event2.categories.add(self.category1) event2.categories.add(self.category2) res = self.client.get(reverse('restaurant-list'), ) serializer1 = EventSerializer(event1) serializer2 = EventSerializer(event2) self.assertIn(serializer1.data, res.data) self.assertNotIn(serializer2.data, res.data)
def put(self, request, eid, format=None): event = self.get_objects(eid) serializer = EventSerializer(event, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request): decoded_token = decode_token(request.META) token = get_token(request.META) serializer = EventSerializer(data=request.data) if serializer.is_valid(): client = CalendarDBClient() event_id = client.add_event(token, serializer.data) st = SchedulingTask(task_type='schedule', status='pending', event_id=event_id, start_time=None, tentative_time=None, initiator_id=decoded_token['user_id'], result='needs_action') re = st.save()[0] re_s = EventSerializer(re.to_dict()) return Response(re_s.data, status=status.HTTP_201_CREATED) return Response( { 'data': serializer.errors, 'message': 'Event could not be created with the given data.' }, status=status.HTTP_400_BAD_REQUEST)
def test_events_endpoints_exclude_restaurants(self): """Test returning events without restaurant category""" event1 = Event.objects.create(name='Evento 1', description='Desc 1', winery=self.winery, price=0.0) EventOccurrence.objects.create(start='2030-05-31T20:00:00', end='2030-05-31T23:00:00', vacancies=50, event=event1) event2 = Event.objects.create(name='Restaurante', description='Desc 1', winery=self.winery, price=0.0) EventOccurrence.objects.create(start='2030-05-31T20:00:00', end='2030-05-31T23:00:00', vacancies=50, event=event2) event1.categories.add(self.category1) event1.categories.add(self.category2) event2.categories.add(self.category_restaurant) res = self.client.get('/api/events/') serializer1 = EventSerializer(event1) serializer2 = EventSerializer(event2) self.assertIn(serializer1.data, res.data) self.assertNotIn(serializer2.data, res.data)
def test_event_creation_with_invalid_tag(self): data = self.valid_data['one_schedule_no_to_date'] tag1 = Tag.objects.create(name='test tag') data['tags'] = [{"name": tag1.name}, {"name": "bad_tag_name"}] serializer = EventSerializer(data=data) self.assertFalse(serializer.is_valid()) self.assertEqual(set(serializer.errors.keys()), set(['tags']))
def test_get_winery_events(self): event = Event.objects.create(name='Event from winery', description='Should be shown', winery=self.winery, price=0.0) other_winery = Winery.objects.create( name='Other Winery', description='test', website='test.com', ) event_from_other_winery = Event.objects.create( name='Other Winery Event', description='Should not be shown', winery=other_winery, price=0.0) EventOccurrence.objects.create(start='2036-10-31T20:00:00', end='2036-10-31T23:00:00', vacancies=50, event=event) EventOccurrence.objects.create(start='2036-10-31T20:00:00', end='2036-10-31T23:00:00', vacancies=50, event=event_from_other_winery) res = self.client.get( reverse('winery-events', kwargs={'pk': self.winery.id}), ) serializer_event = EventSerializer(event) serializer_event_from_other_winery = EventSerializer( event_from_other_winery) self.assertIn(serializer_event.data, res.data) self.assertNotIn(serializer_event_from_other_winery.data, res.data)
def test_filter_events_categories(self): """Test returning events with category specified""" event1 = Event.objects.create(name='Event buscado', description='Desc 1', winery=self.winery, price=0.0) event2 = Event.objects.create(name='Evento 2', description='Desc 2', winery=self.winery, price=0.0) EventOccurrence.objects.create(start='2036-10-31T20:00:00', end='2036-10-31T23:00:00', vacancies=50, event=event1) EventOccurrence.objects.create(start='2030-05-31T20:00:00', end='2030-05-31T23:00:00', vacancies=50, event=event2) event1.categories.add(self.category1) res = self.client.get( reverse("event-list"), {'category': 'Tour'} # Exact match ) serializer1 = EventSerializer(event1) serializer2 = EventSerializer(event2) self.assertIn(serializer1.data, res.data) self.assertNotIn(serializer2.data, res.data)
def create(self, request): decoded_token = decode_token(request.META) serializer = EventSerializer(data=request.data) if serializer.is_valid(): event = Event() data = serializer.data data['calendar_id'] = -1 data['created'] = now() data['updated'] = now() data['user_id'] = decoded_token['user_id'] inserted = event.insert_event(data) result = {} if inserted.get('inserted', 0) == 1: e = EventSerializer(event.get_event_with_pk( inserted['generated_keys'][0]), many=True) if len(e.data) > 0: result = e.data[0] event.close() return Response(result, status=status.HTTP_201_CREATED) return Response(serializer.errors)
def test_filter_events_before_date(self): """Test returning events with a date no superior than the specified""" event1 = Event.objects.create(name='Event buscado', description='Desc 1', winery=self.winery, price=0.0) event2 = Event.objects.create(name='Evento 2', description='Desc 2', winery=self.winery, price=0.0) EventOccurrence.objects.create(start='2036-10-31T20:00:00', end='2036-10-31T23:00:00', vacancies=50, event=event1) EventOccurrence.objects.create(start='2030-05-31T20:00:00', end='2030-05-31T23:00:00', vacancies=50, event=event2) res = self.client.get(reverse("event-list"), {'start_before': '2031-05-31'}) serializer1 = EventSerializer(event1) serializer2 = EventSerializer(event2) self.assertNotIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data)
def test_invalid_schedule(self): self.client.force_login(self.winery_user) data = self.invalid_data['empty_schedule'] serializer = EventSerializer(data=data) self.assertFalse(serializer.is_valid()) response = self.client.post(reverse("event-list"), data=data, content_type="application/json") self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def put(self, request, event_id, format=None): event = Event.objects.get(id=event_id) event_serializer = EventSerializer(event, data=request.data) if event_serializer.is_valid(): event_serializer.save() return Response('') return Response(event_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request): data = {} user = request.user # data['user'] = user # on liste les droits de l'utilisateur pour chaque projet data['permissions'] = {} data['rank'] = {} for project in Project.objects.all(): data['permissions'][project.slug] = Authorization.has_permission( user, 'can_view_project', project) try: rank = Authorization.objects.get(project=project, user=user).level rank = AuthorizationSerializer(rank).data except Exception: if user.is_superuser: usertype = choices.ADMIN else: usertype = choices.LOGGED_USER serializer_rank = UserLevelPermission.objects.get( user_type_id=usertype) rank = UserLevelPermissionSerializer(serializer_rank).data data['rank'][project.slug] = rank project_authorized = Authorization.objects.filter(user=user).filter( level__rank__lte=2).values_list('project__pk', flat=True) serialized_projects = ProjectDetailedSerializer(Project.objects.filter( Q(pk__in=project_authorized) | Q(creator=user)).order_by('-created_on'), many=True) all_events = Event.objects.filter(user=user).order_by('-created_on') serialized_events = EventSerializer(all_events[0:5], many=True) feature_events = Event.objects.filter( user=user, object_type='feature').order_by('-created_on') serialized_feature_events = EventSerializer(feature_events[0:5], many=True) comment_events = Event.objects.filter( user=user, object_type='comment').order_by('-created_on') serialized_comment_events = EventSerializer(comment_events[0:5], many=True) data['projects'] = serialized_projects.data data['events'] = serialized_events.data data['features'] = serialized_feature_events.data data['comments'] = serialized_comment_events.data data['title'] = "Mon compte" return Response(data=data, status=status.HTTP_200_OK)
def get(self, request): context = {} user = request.user # context['user'] = user # on liste les droits de l'utilisateur pour chaque projet context['permissions'] = {} context['rank'] = {} for project in Project.objects.all(): context['permissions'][ project.slug] = Authorization.has_permission( user, 'can_view_project', project) try: rank = Authorization.objects.get(project=project, user=user).level except Exception: if user.is_superuser: usertype = choices.ADMIN else: usertype = choices.LOGGED_USER rank = UserLevelPermission.objects.get(user_type_id=usertype) context['rank'][project.slug] = rank project_authorized = Authorization.objects.filter(user=user).filter( level__rank__lte=2).values_list('project__pk', flat=True) serilized_projects = ProjectDetailedSerializer(Project.objects.filter( Q(pk__in=project_authorized) | Q(creator=user)).order_by('-created_on'), many=True) all_events = Event.objects.filter(user=user).order_by('-created_on') serialized_events = EventSerializer(all_events[0:5], many=True) feature_events = Event.objects.filter( user=user, object_type='feature').order_by('-created_on') serialized_feature_events = EventSerializer(feature_events[0:5], many=True) comment_events = Event.objects.filter( user=user, object_type='comment').order_by('-created_on') serialized_comment_events = EventSerializer(comment_events[0:5], many=True) context['projects'] = serilized_projects.data context['events'] = serialized_events.data context['features'] = serialized_feature_events.data context['comments'] = serialized_comment_events.data return render(request, 'geocontrib/my_account.html', context)
def post(self, request, format=None): app_key = request.data['app_key'] if not self.app_key_valid(app_key): #check validity of the application key return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) serializer = EventSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response("OK")
def event(self, request, pk): """ Function to create the sensor if not existing and save the event in the database. """ response = {} # Let's try to retrive the sensor or create. try: sensor = Sensor.objects.get(external_id=pk) except Sensor.DoesNotExist as e: logger.info( f"{e} - Error getting Sensor, we will create sensor. ") # If we don't have a sensor, we create sensor = Sensor.objects\ .create( external_id=pk ) # Now create the event if 'key' in request.data and 'value' in request.data and 'unit' in request.data: event = Event.objects.create( key=request.data['key'], unit=request.data['unit'], value=request.data['value'], sensor=sensor ) response['message'] = "Created event" serializer = EventSerializer(event, many=False) response['data'] = serializer.data return Response(response, status=status.HTTP_201_CREATED) else: response["message"] = "Required key, value, unit." return Response(response, status.HTTP_400_BAD_REQUEST)
def test_get_collection(self): self.response = self.client.get(self.url, {'page': 1}) self.events = Event.objects.all() self.serializer = EventSerializer(self.events, many=True) self.assertEqual(self.response.data.get('results'), self.serializer.data) self.assertEqual(self.response.status_code, 200)
def test_event_creation_endpoint_with_different_schedules( self, data_key, expected_occurrences_count): self.client.force_login(self.winery_user) data = self.valid_data[data_key] serializer = EventSerializer(data=data) self.assertTrue(serializer.is_valid()) response = self.client.post(reverse("event-list"), data=data, content_type="application/json") self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(set(response.json().keys()), set(["url"])) db_event = Event.objects.first() self.assertEqual(db_event.name, data["name"]) self.assertEqual(expected_occurrences_count, len(db_event.occurrences.all()))
class QuestionSerializer(serializers.ModelSerializer): event = EventSerializer() status = serializers.SerializerMethodField('get_uqj_status') is_author = serializers.SerializerMethodField('get_is_author') class Meta: model = Question fields = [ 'id', 'title', 'text', 'max_submission_allowed', 'time_created', 'time_modified', 'author', 'category', 'difficulty', 'is_verified', 'token_value', 'success_rate', 'type_name', 'event', 'is_sample', 'category_name', 'parent_category_name', 'course_name', 'event_name', 'author_name', 'is_open', 'is_exam', 'is_exam_and_open', 'status', 'full_category_name', 'is_author' ] def get_uqj_status(self, obj): request = self.context.get('request', None) if request is None: return '' return request.user.question_junctions.get(question__pk=obj.id).status def get_is_author(self, obj): request = self.context.get('request', None) if request is None: return False return request.user == obj.author
def get(self, request, slug, feature_type_slug, feature_id): user = request.user feature = self.get_object() project = feature.project linked_features = FeatureLink.handy.related(feature.feature_id) serialized_link = FeatureLinkSerializer(linked_features, many=True) events = Event.objects.filter( feature_id=feature.feature_id).order_by('created_on') serialized_events = EventSerializer(events, many=True) context = self.get_context_data(feature_id=feature_id) context['feature'] = feature context['feature_data'] = feature.custom_fields_as_list context['linked_features'] = serialized_link.data context['permissions'] = Authorization.all_permissions( user, project, feature) context['events'] = serialized_events.data context['attachments'] = Attachment.objects.filter( project=project, feature_id=feature.feature_id, object_type='feature') context['comment_form'] = CommentForm() context['project'] = project return render(request, 'geocontrib/feature/feature_detail.html', context)
def create(self, request): fields = json.loads(request.body) creator = self.request.user.m_user venue = Venue.objects.get(pk=fields['venue']) # parse the posted string date into a datetime object date = datetime.datetime.strptime(fields['date'], "%Y-%m-%d").date() desc = None if "desc" not in fields else fields['desc'] # create and save a new event using post fields new_event = Event.objects.create(creator=creator, name=fields['name'], has_image=fields['has_image'], desc=desc, venue=venue, date=date) # add the creator the the list of attendees and save new_event.attending.add(creator) new_event.save() # create a new action for the stream Action.objects.create(user=creator, event=new_event) # serialize and return the event serializer = EventSerializer(new_event) return Response(serializer.data)
def fetch_events(): logger.info('Starting cron script... This may take some time...') for location in Location.objects.all(): events = EventsFetcher.get_items(location) for event in events: serializer = EventSerializer(data=event) if serializer.is_valid(): serializer.save() else: logger.error(serializer.errors) logger.info('Finished cron script...')
def event(self, request, *args, **kwargs): try: event = self.get_object().citizenactqrcode.treasure_hunt.event serializer = EventSerializer(event) return Response(serializer.data, status=status.HTTP_200_OK) except ObjectDoesNotExist: return Response(status=status.HTTP_204_NO_CONTENT)
def get(self, request, slug, feature_type_slug, feature_id): user = request.user feature = self.get_object() project = feature.project layers = Layer.objects.filter(project=project) serialized_layers = LayerSerializer(layers, many=True) linked_features = FeatureLink.objects.filter( feature_from=feature.feature_id ) serialized_link = FeatureLinkSerializer(linked_features, many=True) events = Event.objects.filter(feature_id=feature.feature_id).order_by('created_on') serialized_events = EventSerializer(events, many=True) context = { 'feature': feature, 'feature_data': feature.custom_fields_as_list, 'feature_types': FeatureType.objects.filter(project=project), 'feature_type': feature.feature_type, 'linked_features': serialized_link.data, 'project': project, 'permissions': Authorization.all_permissions(user, project, feature), 'comments': Comment.objects.filter(project=project, feature_id=feature.feature_id), 'attachments': Attachment.objects.filter( project=project, feature_id=feature.feature_id, object_type='feature'), 'events': serialized_events.data, 'comment_form': CommentForm(), 'layers': serialized_layers.data, } return render(request, 'geocontrib/feature/feature_detail.html', context)
def events(self, request): event = Event() serializer = EventSerializer(event.list_all_events_for_training(), many=True) event.close() return Response(serializer.data, status=status.HTTP_200_OK)
def get(self, request, format=None): queryset = Event.objects.filter( participants=request.user.moreuserdata).order_by( 'end_date_time', 'start_date_time') serializer = EventSerializer(queryset, context={'request': request}, many=True) return Response(serializer.data)
def get(self, request, uuid): organizer = self.get_object(uuid) events = organizer.events.order_by('created') first_event = EventSerializer(events.first()) last_event = EventSerializer(events.last()) venue_count = Venue.objects.filter(events__organizer__uuid=uuid).\ annotate(event_count=Count('events')).\ values('event_count', 'name', 'uuid') data = { 'first_event': first_event.data, 'last_event': last_event.data, 'total_events': events.count(), 'venue_count': list(venue_count) } return Response(data)
def test_filter_events_multiple_tags(self): """Test returning events with tags specified""" event1 = Event.objects.create(name='Wanted Event', description='Should be shown', winery=self.winery, price=0.0) event2 = Event.objects.create(name='Also Wanted', description='Should be shown', winery=self.winery, price=0.0) event3 = Event.objects.create(name='Unwanted', description='Shouldnt be shown', winery=self.winery, price=0.0) EventOccurrence.objects.create(start='2036-10-31T20:00:00', end='2036-10-31T23:00:00', vacancies=50, event=event1) EventOccurrence.objects.create(start='2030-05-31T20:00:00', end='2030-05-31T23:00:00', vacancies=50, event=event2) EventOccurrence.objects.create(start='2030-05-31T20:00:00', end='2030-05-31T23:00:00', vacancies=50, event=event3) # Wanted Event tags event1.tags.add(Tag.objects.create(name='tag1')) event1.tags.add(Tag.objects.create(name='tag3')) event2.tags.add(Tag.objects.create(name='tag2')) # Unwanted Event tag) event3.tags.add(Tag.objects.create(name='tag3')) res = self.client.get( '/api/events/?tag=tag1&tag=tag2' # looks for events with any of this tags ) serializer1 = EventSerializer(event1) serializer2 = EventSerializer(event2) serializer3 = EventSerializer(event3) # Check that wanted events are in the response self.assertIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data) # Check that unwanted event is not in response data self.assertNotIn(serializer3.data, res.data)
def retrieve(self, request, pk=None): serializer = EventSerializer(self.get_object()) if 'userId' in request.query_params: s_dict = dict(serializer.data) s_dict['progress'] = Event.objects.get( id=serializer.data['id']).progress( request.query_params['userId']) return Response(s_dict, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_200_OK)
def test_event_creation_with_tags(self): self.client.force_login(self.winery_user) data = self.valid_data['one_schedule_no_to_date'] tag1 = Tag.objects.create(name='test tag') tag2 = Tag.objects.create(name='other tag') data['tags'] = [{"name": tag1.name}, {"name": tag2.name}] serializer = EventSerializer(data=data) self.assertTrue(serializer.is_valid()) response = self.client.post(reverse("event-list"), data=data, content_type="application/json") self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(set(response.json().keys()), set(["url"])) db_event = Event.objects.first() self.assertEqual(db_event.name, data["name"]) tag_list = [tag.name for tag in db_event.tags.all()] self.assertEqual(set(tag_list), set(['test tag', 'other tag']))