def post(self, request): # Create serializers with request.DATA serializer = self.serializer_class(data=request.DATA) profile_serializer_class = self.get_profile_serializer_class() profile_serializer = profile_serializer_class(data=request.DATA) if serializer.is_valid() and profile_serializer.is_valid(): # Change the password key to password1 so that RESTRegistrationView # can accept the data serializer.data['password1'] = serializer.data.pop('password') # TODO: Make this customizable backend via settings. # Call RESTRegistrationView().register to create new Django User # and UserProfile models data = serializer.data.copy() data.update(profile_serializer.data) RESTRegistrationView = get_registration_backend() user = RESTRegistrationView().register(request, **data) # Return REST Token object with OK HTTP status token, created = self.token_model.objects.get_or_create(user=user) result = UserDetailsSerializer(serializer.data).data result.update(self.token_serializer(token).data) # Return the User object with Created HTTP status return Response(result, status=status.HTTP_201_CREATED) else: return Response({ 'user': serializer.errors, 'profile': profile_serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
class CommentSerializer(SimplifiedCommentSerializer): author = UserDetailsSerializer(read_only=True) post = SimplifiedPostSerializer(read_only=True) class Meta: model = Comment fields = ['id', 'title', 'content', 'created_at', 'updated_at', 'post', 'author']
class CourseSerializer(TaggitSerializer, serializers.HyperlinkedModelSerializer): instructor = UserDetailsSerializer(read_only=True) category = CategorySerializer() read_only_fields = ["instructor"] tags = NewTagListSerializerField() class Meta: model = Course read_only_fields = ['pk'] # exclude = ('slug', "students") fields = ('pk', 'instructor', 'category', 'title', 'overview', 'intro_video', 'difficulty_level', 'learning_goals', 'prerequisites', 'tags', 'price') def create(self, validated_data): category_data = validated_data.pop('category') category_list = list(Category.objects.values_list("name", flat=True)) if category_data['name'] not in category_list: raise serializers.ValidationError( f"category value is invalid. Category name must one of these: {category_list}" ) else: category = Category.objects.get(name=category_data['name']) course = Course.objects.create(**validated_data, category_id=category.id) return course
def post(self, request): # Create serializers with request.DATA serializer = self.serializer_class(data=request.DATA) profile_serializer_class = self.get_profile_serializer_class() profile_serializer = profile_serializer_class(data=request.DATA) if serializer.is_valid() and profile_serializer.is_valid(): # Change the password key to password1 so that RESTRegistrationView # can accept the data serializer.data['password1'] = serializer.data.pop('password') # TODO: Make this customizable backend via settings. # Call RESTRegistrationView().register to create new Django User # and UserProfile models data = serializer.data.copy() data.update(profile_serializer.data) RESTRegistrationView = get_registration_backend() RESTRegistrationView().register(request, **data) # Return the User object with Created HTTP status return Response(UserDetailsSerializer(serializer.data).data, status=status.HTTP_201_CREATED) else: return Response( { 'user': serializer.errors, 'profile': profile_serializer.errors }, status=status.HTTP_400_BAD_REQUEST)
class AnswerSerializer(serializers.HyperlinkedModelSerializer): user = UserDetailsSerializer(read_only=True) questions = AnsweredQuestionSerializer(many=True, source='answered_questions') selected_options = OptionSerializer(many=True, read_only=True) timestamp = serializers.DateTimeField(read_only=True, allow_null=True) class Meta: model = models.Answer fields = [ 'user', 'selected_options', 'questions', 'timestamp', ] def create(self, validated_data): selected_options = [] for question in validated_data['answered_questions']: for option in question['options']: selected_options.append(option['id']) answer = models.Answer.objects.create( task=validated_data['task'], user=validated_data['user'], ) answer.selected_options.set(selected_options) return answer
class TaskSerializer(serializers.ModelSerializer): users = UserDetailsSerializer(read_only=True, many=True) class Meta: model = Task fields = ('id', 'title', 'deadline', 'todo_list', 'users')
class RatingSerializer(serializers.ModelSerializer): rating = serializers.DecimalField(max_digits=3, decimal_places=2, min_value=0, max_value=5, write_only=True) owner_data = UserDetailsSerializer(read_only=True, source='owner') rating_value = serializers.FloatField(read_only=True, source='rating') class Meta: model = Rating fields = ('pk', 'owner', 'rating', 'comment', 'service', 'owner_data', 'modified', 'rating_value') extra_kwargs = { 'owner': { 'required': False, 'write_only': True }, 'service': { 'write_only': True }, 'modified': { 'read_only': True }, }
class TaskSerializer(serializers.HyperlinkedModelSerializer): questions = QuestionSerializer(many=True) og_image_link = serializers.URLField(read_only=True) user = UserDetailsSerializer(read_only=True) warning_message = serializers.SerializerMethodField(read_only=True) def create(self, validated_data): questions = validated_data.pop('questions') task = models.Task.objects.create(**validated_data) for question in questions: q = models.Question.objects.create(title=question['title'], task=task) for option in question['options']: models.Option.objects.create(title=option['title'], question=q) return task def validate_website_link(self, website_link): return convert_url(website_link) def validate(self, attrs): website_link = attrs.get('website_link') if website_link: try: self._og = OpenGraph(url=website_link) except requests.exceptions.ConnectionError as e: L.warning(e) raise serializers.ValidationError( {'website_link': f'Connection error for {website_link}'}) attrs.update({ 'og_image_link': self._og.image, 'website_link': self._og.RESOLVED_URL or website_link }) return super().validate(attrs) def get_warning_message(self, obj): warning_msg = '' if hasattr(self, '_og'): # from validate only og = self._og if og.X_FRAME_OPTIONS: # Website doesn't allow us to be viewed warning_msg = f'Website has strict X-Frame-Options: {og.X_FRAME_OPTIONS}' return warning_msg class Meta: model = models.Task fields = [ 'id', 'title', 'description', 'user', 'og_image_link', 'website_link', 'reward_per_click', 'reward_usd_per_click', 'spend_daily', 'time_duration', 'questions', 'warning_message', ]
class TokenSerializer(serializers.ModelSerializer): user = UserDetailsSerializer(many=False, read_only=True) # this is add by myself. class Meta: model = TokenModel fields = ('key', 'user')
class TokenSerializer(serializers.ModelSerializer): """ Serializer for Token model, i.e. what gets returned on login """ user = UserDetailsSerializer(many=False, read_only=True) class Meta: model = TokenModel fields = ('user', )
class TopicSerializer(serializers.ModelSerializer): author = UserDetailsSerializer(read_only=True) class Meta: model = Topic fields = '__all__' read_only_fields = ( 'urlname', 'author', )
class TopicSerializer(serializers.ModelSerializer): """A basic serializer for the `Topic` model.""" author = UserDetailsSerializer(read_only=True) class Meta: model = Topic fields = [ 'id', 'title', 'author', 'description', 'url_name', 'created_at', 'updated_at' ]
def get(self, request): # Create serializers with request.user and profile user_profile_model = get_user_profile_model() if user_profile_model: profile_serializer_class = self.get_profile_serializer_class() serializer = profile_serializer_class(request.user.get_profile()) else: serializer = UserDetailsSerializer(request.user) # Send the Return the User and its profile model with OK HTTP status return Response(serializer.data, status=status.HTTP_200_OK)
class PostSerializer(serializers.ModelSerializer): author = UserDetailsSerializer(read_only=True) topic = TopicDetailSerializer(read_only=True) class Meta: model = Post fields = '__all__' read_only_fields = ( 'author', 'topic', )
class PostSerializer(serializers.ModelSerializer): """A basic serializer for the `Post` model.""" author = UserDetailsSerializer(read_only=True) topic = serializers.ReadOnlyField(source='topic.title') class Meta: model = Post fields = [ 'id', 'title', 'topic', 'content', 'created_at', 'updated_at', 'author' ]
def test_user_can_access(self): ''' Authenticated users can retrieve from here. ''' user = User.objects.create_user(username='******', email='*****@*****.**') client = APIClient() client.force_authenticate(user=user) url = reverse('rest_user_details') response = client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) serializer = UserDetailsSerializer(user) self.assertEqual(response.data, serializer.data)
def test_retrieve_user_details(self): """Test that user can retrive their own information""" login = self.client.login(email='*****@*****.**', password='******') res = self.client.get(get_user_detail_url(4)) user = get_user_model().objects.get(pk=4) serializer = UserDetailsSerializer(user) self.assertTrue(login) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) self.assertEqual(res.data['email'], '*****@*****.**')
class TokenSerializer(serializers.Serializer): """ Serializer for Knox library authentication authentication. """ token = serializers.CharField() user = UserDetailsSerializer() def create(self, validated_data): """TODO:Implement abstract create method""" pass def update(self, instance, validated_data): """TODO:Implement abstract update method""" pass
def test_get_user_profile(self): view = UserDetailsView() user = mixer.blend(User) path = reverse_lazy("rest_auth:rest_user_details") request = self.factory.get(path) request.user = user response = view.dispatch(request) serializer = UserDetailsSerializer(user) assert response.status_code == status.HTTP_200_OK assert response.data["id"] == serializer.data["pk"]
class TopicSerializer(SimplifiedTopicSerializer): author = UserDetailsSerializer(read_only=True) posts = SerializerMethodField() def get_posts(self, instance): from posts.serializers import SimplifiedPostSerializer posts = Post.objects.filter(topic=instance.urlname)[:4] return SimplifiedPostSerializer(posts, read_only=True, many=True).data class Meta: model = Topic fields = [ 'created_at', 'updated_at', 'name', 'title', 'author', 'description', 'urlname', 'posts' ]
class CommentSerializer(serializers.ModelSerializer): """A basic serializer for the `Comment` model.""" author = UserDetailsSerializer(read_only=True) post = serializers.ReadOnlyField(source='post.title') class Meta: model = Comment fields = [ 'id', 'title', 'content', 'created_at', 'updated_at', 'post', 'author', ]
class PostSerializer(SimplifiedPostSerializer): author = UserDetailsSerializer(read_only=True) topic = SimplifiedTopicSerializer(read_only=True) comments = SerializerMethodField() def get_comments(self, instance): from comments.serializers import SimplifiedCommentSerializer comments = Comment.objects.filter(post=instance.id)[:4] return SimplifiedCommentSerializer(comments, read_only=True, many=True).data class Meta: model = Post fields = [ 'id', 'title', 'content', 'created_at', 'updated_at', 'topic', 'author', 'comments' ]
class TaskSerializer(serializers.HyperlinkedModelSerializer): questions = QuestionSerializer(many=True) og_image_link = serializers.URLField(read_only=True) user = UserDetailsSerializer(read_only=True) tx_hash = serializers.CharField(source='initial_tx_hash', required=False) type = serializers.CharField(read_only=True) reward_per_click = MoneyField(max_digits=11, decimal_places=5) reward_usd_per_click = MoneyField(max_digits=11, decimal_places=5, read_only=True) remaining_balance = MoneyField(max_digits=9, decimal_places=3, read_only=True) initial_budget = MoneyField(max_digits=9, decimal_places=3, required=False) class Meta: model = models.Task fields = [ 'id', 'title', 'description', 'chain', 'user', 'og_image_link', 'uuid', 'website_link', 'website_image', 'contract_address', 'reward_per_click', 'reward_usd_per_click', 'time_duration', 'questions', 'warning_message', 'is_active', 'remaining_balance', 'initial_budget', 'tx_hash', 'type', ] read_only_fields = [ 'user', 'og_image_link', 'remaining_balance', 'website_image', 'warning_message', 'is_active', ] def create(self, validated_data): validated_data['is_active_web3'] = False questions = validated_data.pop('questions') task = super(TaskSerializer, self).create(validated_data) for question in questions: q = models.Question.objects.create(title=question['title'], task=task) for option in question['options']: models.Option.objects.create(title=option['title'], question=q, is_correct=option.get( 'is_correct', False)) if task.initial_tx_hash: tasks.update_task_is_active_balance.delay( task_id=task.id, wait_for_tx=str(task.initial_tx_hash)) else: tasks.update_task_is_active_balance.delay(task_id=task.id, should_be_active=True, retry=10) tasks.create_task_screenshot.delay(task.id) return task def validate_website_link(self, website_link): return convert_url(website_link) def validate_questions(self, questions): for question in questions: # Validate number of correct options is max one correct_question_sum = sum([ option.get('is_correct', False) for option in question.get('options', []) ]) if not correct_question_sum <= 1: raise serializers.ValidationError({ 'question': f"Question {question.get('title', '')} has {correct_question_sum} correct questions." }) return questions def validate(self, attrs): website_link = attrs.get('website_link') if website_link: try: og = OpenGraph(url=website_link) except requests.exceptions.ConnectionError as e: L.warning(e) raise serializers.ValidationError( {'website_link': f'Connection error for {website_link}'}) if og.response.status_code != status.HTTP_200_OK: message = f'Website {website_link} responded with status code: {og.response.status_code}' L.warning(message) # raise serializers.ValidationError({'website_link': f'{message}. Has to be 200'}) attrs.update({ 'og_image_link': og.image, 'website_link': og.RESOLVED_URL or website_link, }) if og.X_FRAME_OPTIONS: attrs.update({ 'warning_message': f'Website has strict X-Frame-Options: {og.X_FRAME_OPTIONS}', }) return super().validate(attrs)
class KnoxSerializer(serializers.Serializer): """ Serializer for Knox authentication. """ token = serializers.CharField() user = UserDetailsSerializer()
class TokenSerializer(serializers.ModelSerializer): user = UserDetailsSerializer() class Meta: model = TokenModel fields = ['key', 'user']
from rest_auth.serializers import UserDetailsSerializer
class CustomTokenSerializer(serializers.ModelSerializer): user = UserDetailsSerializer(read_only=True) class Meta: model = TokenModel fields = '__all__'