1

I am just starting to learn python and django rest framework. I am creating the sample apis in django. I am having a problem where i need to set the validation error messages.

For example email is requied or email already exists

Here is my code:

Serializer Class:

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        #fields = ['id','title','author','date']
        fields = '__all__'

views.py

def post(self,request):
        serializer = ArticleSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.error,status = status.HTTP_400_BAD_REQUEST)

Model:

class Article(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    date = models.DateTimeField(auto_now_add = True)


    def _str_(self):
        #self.fields['email'].required = False
        return self.title 

Error is:

'ArticleSerializer' object has no attribute 'error'

2 Answers 2

2

You don't need to handle the validation manually:

def post(self, request):
    serializer = ArticleSerializer(data=request.data)
    serializer.is_valid(raise_exception=True):
    serializer.save()
    return Response(serializer.data, status=status.HTTP_201_CREATED)

This will raise an Exception, but the exception will be handled by DRF (as long as you're using it correctly) and will return a 400 status code with the error messages as expected.

Also, this view does more or less exactly the same as a CreateAPIView, you'd probably be better off using that than reinventing the wheel.

Sign up to request clarification or add additional context in comments.

Comments

1

Try using serializer.errors (plural) instead of serializer.error.

That will avoid the error you're getting and it will return the HTTP error you're expecting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.