def validate(self, data): participants = data.get('participants', None) print(participants) if data.get('is_chat'): if len(participants) != 2: raise BadRequestError( 'Number of participants must be equal 2.') else: if len(participants) < 2: raise BadRequestError( 'Number of participants must be greater then 2.') return super().validate(data)
def get_queryset(self): if self.action == 'list': post_id = self.request.query_params.get('post_id', None) photo_id = self.request.query_params.get('photo_id', None) if post_id: try: post_id = int(post_id) except ValueError: raise BadRequestError('Input a number.') post = get_object_or_404(Post, id=post_id) return post.comments elif photo_id: try: photo_id = int(photo_id) except ValueError: raise BadRequestError('Input a number.') photo = get_object_or_404(Photo, id=photo_id) return photo.comments else: raise BadRequestError('You need to input a query parameter post or photo id in your request.') return super().get_queryset()
def create(self, validated_data): password = validated_data.pop('password', None) activation_type = validated_data.get('activation_type', None) if activation_type != 'email' and activation_type != 'phone': raise BadRequestError('Wrong activation type.') try: slug = ContactCounter.objects.get(id=1).counter + 1 except ContactCounter.DoesNotExist: counter = ContactCounter.objects.create() slug = 1 user = Contact.objects.create( slug=f'id{slug}', **validated_data, ) user.set_password(password) user.save() return user
def friend_manipulation(sender_id, receiver_id, add=True): try: sender_contact = Contact.objects.prefetch_related( Prefetch('my_page', to_attr='sender_page') ).get(id=sender_id) receiver_contact = Contact.objects.prefetch_related( Prefetch('my_page', to_attr='receiver_page') ).get(id=receiver_id) except Contact.DoesNotExist: raise BadRequestError('User not found.') if add: sender_contact.sender_page.friends.add(receiver_contact) receiver_contact.receiver_page.friends.add(sender_contact) else: sender_contact.sender_page.friends.remove(receiver_contact) receiver_contact.receiver_page.friends.remove(sender_contact) sender_contact.sender_page.save() receiver_contact.receiver_page.save()
def validate(self, data): if data.get('code', None): return super().validate(data) return BadRequestError('You need a code.')
def validate(self, attrs): data = self.context['request'].data if data.get('text', None) or data.get('image', None): return super().validate(attrs) else: raise BadRequestError('You need either image or text.')