def post(self, request, format=None): print("Creating new profile") serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def register_user(request): token_generator = AppTokenGenerator() data = {'username':request.data["userName"], 'password':request.data["password"], 'email':request.data["email"]} user_serializer = UserSerializer(data=data) if user_serializer.is_valid(): user = user_serializer.save() data = {'user_id':user.id,'first_name':request.data["firstName"], 'last_name':request.data["lastName"], 'email':request.data["email"], 'birth_date':None, 'country':None} profile_serializer = ProfileSerializer(data=data) if profile_serializer.is_valid(): profile_serializer.save() else: logger.error(profile_serializer.errors) login(request, user) logger.info("Preparing email...") FRONTEND_URL = settings.FRONTEND_URL BACKEND_URL = settings.BACKEND_URL # token = get_random_string(length=32) token = token_generator.make_token(user) verify_link = FRONTEND_URL + 'verify-email/' + token subject, from_email, to = 'Verify your email', settings.EMAIL_HOST_USER, request.data["email"] html_content = render_to_string('verify_email.html', {'verify_link': verify_link, 'base_url': FRONTEND_URL, 'backend_url': BACKEND_URL}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to, '*****@*****.**']) msg.attach_alternative(html_content, "text/html") msg.send() logger.info("Verification email sent") return Response({'user': user_serializer.data}) else: logger.error(user_serializer.errors)
def put(self, request, pk, format=None): profile = self.get_object(pk) # Partial = True allows a Patch. django-rest-framework.org/api-guide/serializers/#partial-updates serializer = ProfileSerializer(profile, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create_profile(user, *args, **kwargs): if Profile.objects.filter(user=user).exists(): pass else: # Will this work with other OAuth services, or do we need to look at kwargs['backend'] and get the data appropriately from kwargs? data = {'user_id':user.id,'first_name': kwargs['details']['first_name'], 'last_name': kwargs['details']['last_name'], 'email': kwargs['details']['email'], 'birth_date':None, 'country':None} profile_serializer = ProfileSerializer(data=data) if profile_serializer.is_valid(): profile_serializer.save()
class CommentSerializer(serializers.ModelSerializer): author = ProfileSerializer(required=False) createdAt = serializers.SerializerMethodField(method_name='get_created_at') updatedAt = serializers.SerializerMethodField(method_name='get_updated_at') post_slug = serializers.SerializerMethodField() class Meta: model = Comment fields = ('id', 'author', 'body', 'createdAt', 'updatedAt', 'post_slug') def create(self, validated_data): print('hello') post = self.context['post'] author = User.objects.get(username=self.context['author']) return Comment.objects.create(author=author.profile, post=post, **validated_data) def get_created_at(self, instance): return instance.created_at.isoformat() def get_updated_at(self, instance): return instance.updated_at.isoformat() def get_post_slug(self, instance): return instance.post.slug
def test_retrieve_profile_owner(self): """Test retrieving a profile by owner is successful""" res = self.client.get(ME_URL) serializer = ProfileSerializer(self.profile) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
class PitchTopicSerializer(serializers.Serializer): id = serializers.IntegerField(source="pk", read_only=True) name = serializers.CharField(max_length=150, trim_whitespace=True) slide_deck_url = serializers.URLField(max_length=500, allow_null=True, required=False) date_created = serializers.DateTimeField(read_only=True) audio_files = serializers.SerializerMethodField('get_audio_files') profile = ProfileSerializer(read_only=True) profile_id = serializers.IntegerField(write_only=True) # In rare cases where none of the existing relational styles fit the representation you need, you can implement a completely custom relational field, that describes exactly how the output representation should be generated from the model instance def to_representation(self, instance): representation = super(PitchTopicSerializer, self).to_representation(instance) representation['date_created'] = instance.date_created.strftime("%B %d, %Y at %I:%M%p") return representation def get_audio_files(self, obj): return AudioSerializer(self.context.get('audio_files'), many=True).data def create(self, validated_data): """ Create and return a new 'PitchTopic' instance, given the validated data """ return PitchTopic.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) # instance.slide_deck_url = validated_data.get('slide_deck_url', instance.slide_deck_url) instance.save() # Change the key on S3 # need to change key on s3 because pitch topic name is in the key #s3_client = boto3.resource('s3') #s3_client.Object('vrwarebucket', validated_data.get('name')+'.wav').copy_from(CopySource='vrwarebucket/'+old_instance_key) #s3_client.Object('vrwarebucket', old_instance_key).delete() return instance
def test_update_profile_owner(self): """Test updating a profile by owner is successful""" payload = { 'first_name': 'Test', 'last_name': 'User' } res = self.client.patch(ME_URL, data=payload) self.profile.refresh_from_db() serializer = ProfileSerializer(self.profile) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
class ChatSerializer(serializers.ModelSerializer): participants = ProfileSerializer(many=True, required=False) def create(self, validated_data): chat = Chat.objects.create() usernames = (self.context['request'].data)['usernames'] if not usernames: usernames = [] for user in usernames: profile = Profile.objects.get(user=User.objects.get(username=user)) chat.participants.add(profile) profile.chat_rooms.add(chat) profile.save() chat.save() return chat class Meta: model = Chat fields = ('pk', 'messages', 'participants',) read_only = ('pk',)
def register_user(request): print("Creating a new user") print(request.data) data = {'username':request.data["userName"], 'password':request.data["password"], 'email':request.data["email"]} serializer = UserSerializer(data=data) if serializer.is_valid(): print("Valid") user = serializer.save() # have to create profile data and link it to user data = {'user':user, 'first_name':None, 'last_name':None, 'email':request.data["email"], 'birth_date':None, 'country':None} serializer = ProfileSerializer(data=data) if serializer.is_valid(): print("Profile data is valid") serializer.save() else: print("Profile data is not valid") print(serializer.errors) #profile = Profile(user=user, first_name=None, last_name=None, email=request.data["email"], birth_date=None, country=None) return Response({'user': serializer.data}) print("data not valid") print(serializer.errors)
def get(self, request, pk, format=None): profile = self.get_object(pk) serializer = ProfileSerializer(profile) return Response(serializer.data)
def get(self, request, format=None): profiles = models.Profile.objects.all() serializer = ProfileSerializer(profiles, many=True) return Response(serializer.data)
def get(self, request, format=None): logged_in_profile = self.get_object(request) serializer = ProfileSerializer(logged_in_profile) return Response(serializer.data)
class PostSerializer(serializers.ModelSerializer): author = ProfileSerializer(read_only=True) body = serializers.CharField(required=True) description = serializers.CharField(required=False) slug = serializers.SlugField(required=False) title = serializers.CharField(required=True) favorited = serializers.SerializerMethodField() favoritesCount = serializers.SerializerMethodField( method_name='get_favorites_count') upvoted = serializers.SerializerMethodField() upvotesCount = serializers.SerializerMethodField( method_name='get_upvotes_count') downvoted = serializers.SerializerMethodField() downvotesCount = serializers.SerializerMethodField( method_name='get_downvotes_count') commentsCount = serializers.SerializerMethodField( method_name='get_comments_count') tagList = TagRelatedField(many=True, required=False, source='tags') # define methods for these fields createdAt = serializers.SerializerMethodField(method_name='get_created_at') updatedAt = serializers.SerializerMethodField(method_name='get_updated_at') class Meta: model = Post fields = ('author', 'body', 'createdAt', 'description', 'favorited', 'favoritesCount', 'slug', 'tagList', 'title', 'updatedAt', 'upvoted', 'upvotesCount', 'downvoted', 'downvotesCount', 'commentsCount') def create(self, validated_data): author = self.context.get('author', None) tags = validated_data.pop('tags', []) user = User.objects.get(username=author) post = Post.objects.create(author=user.profile, **validated_data) for tag in tags: post.tags.add(tag) return post def get_created_at(self, instance): return instance.created_at.isoformat() def get_favorited(self, instance): request = self.context.get('request', None) if request is None: return False if not request.user.is_authenticated: return False return request.user.profile.has_favorited(instance) def get_favorites_count(self, instance): return instance.favorited_by.count() def get_upvoted(self, instance): request = self.context.get('request', None) if request is None: return False if not request.user.is_authenticated: return False return request.user.profile.has_upvoted(instance) def get_upvotes_count(self, instance): return instance.upvoted_by.count() def get_downvoted(self, instance): request = self.context.get('request', None) if request is None: return False if not request.user.is_authenticated: return False return request.user.profile.has_downvoted(instance) def get_downvotes_count(self, instance): return instance.downvoted_by.count() def get_updated_at(self, instance): return instance.updated_at.isoformat() def get_comments_count(self, instance): return instance.comments.count()
class AudioSerializer(serializers.Serializer): class Meta: # Django inserts the date automatically for us (auto_now_add), so we don't want to pass it in to serialzier when writing read_only_fields = ['date_recorded'] # Define the fields that get serialized/deserialized id = serializers.IntegerField(source="pk", read_only=True) #name = serializers.CharField(max_length=10, required=False) #audio_file = serializers.FileField(required=False) s3_url = serializers.URLField(max_length=500, allow_blank=False, required=False) # In DRF, CharField corresponds to both CharField and TextField transcript = serializers.CharField(default='') #pitch_topic = serializers.CharField(max_length=150, allow_blank=False, required=True) profile = ProfileSerializer(read_only=True) #pitch_topic = PitchTopicSerializer(read_only=True) metrics = MetricsSerializer(read_only=True) # https://www.vhinandrich.com/blog/saving-foreign-key-id-django-rest-framework-serializer profile_id = serializers.IntegerField(write_only=True) pitch_topic_id = serializers.IntegerField(write_only=True) metrics_id = serializers.IntegerField(write_only=True) date_recorded = serializers.DateTimeField(read_only=True) # reverse relationship notes = NoteSerializer(source='note_set',read_only=True, many=True) def create(self, validated_data): """ Create and return a new 'Audio' instance, given the validated data """ return Audio.objects.create(**validated_data) def update(self, instance, validated_data): old_instance_key = instance.name+'.wav' instance.name = validated_data.get('name', instance.name) instance.s3_url = S3_URL + validated_data.get('name')+'.wav' # Change the key on S3 # s3_client = boto3.resource('s3') # s3_client.Object('vrwarebucket', validated_data.get('name')+'.wav').copy_from(CopySource='vrwarebucket/'+old_instance_key) # s3_client.Object('vrwarebucket', old_instance_key).delete() instance.save() return instance # In rare cases where none of the existing relational styles fit the representation you need, you can implement a completely custom relational field, that describes exactly how the output representation should be generated from the model instance def to_representation(self, instance): representation = super(AudioSerializer, self).to_representation(instance) representation['date_recorded'] = instance.date_recorded.strftime("%Y-%m-%d") # representation['date_recorded'] = instance.date_recorded.strftime("%B %d, %Y at %I:%M%p") # December 19, 2020 at 5:20AM return representation # object level validation def validate(self, data): return data def validate_name(self, value): return value def validate_s3_url(self, value): return value def validate_date_recorded(self, value): return value
class UserSerializer(serializers.ModelSerializer): # Add profile fields to JSON profile = ProfileSerializer() class Meta: model = User fields = '__all__' def create(self, validated_data): """ Create and return a new User instance, given the validated data. """ profile_data = validated_data.pop('profile') user = super(UserSerializer, self).create(validated_data) user.date_joined = datetime.today() user.set_password(validated_data['password']) user.save() profile = Profile( user=user, cba_username=profile_data.get('cba_username').strip(), cba_user_token=profile_data.get('cba_user_token').strip()) profile.save() return user def update(self, instance, validated_data): """ Update and return an existing User instance, given the validated data. """ user = self.context['user'] instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.email = validated_data.get('email', instance.email) if user.is_superuser: instance.groups = validated_data.get('groups', instance.groups) instance.user_permissions = validated_data.get( 'user_permissions', instance.user_permissions) instance.is_active = validated_data.get('is_active', instance.is_active) instance.is_staff = validated_data.get('is_staff', instance.is_staff) instance.is_superuser = validated_data.get('is_superuser', instance.is_superuser) # TODO: How to hook into this from ProfileSerializer without having to call it here? try: profile = Profile.objects.get(user=instance.id) except ObjectDoesNotExist: profile = Profile.objects.create(user=instance, **validated_data['profile']) profile.cba_username = validated_data['profile'].get('cba_username') profile.cba_user_token = validated_data['profile'].get( 'cba_user_token') profile.save() instance.save() return instance