Karan
Karan

Reputation: 1118

How to implement validation error messages in django rest

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'

Upvotes: 1

Views: 227

Answers (2)

arthursribeiro
arthursribeiro

Reputation: 336

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.

Upvotes: 1

Tom Carrick
Tom Carrick

Reputation: 6616

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.

Upvotes: 2

Related Questions