1

Beginner alert. I am using ListCreateAPIView for listing and creating purposes. Whenever I create through an api it returns responses in json format.

{"id":16,"title":"yyyyyyyy","destination_place":[1]}

But if there are errors like duplicate slug or title it returns errors like this

IntegrityError at /api/holidays/
duplicate key value violates unique constraint "holidays_holiday_slug_key"
DETAIL:  Key (slug)=(yyyyyyyy) already exists.

Is there any way to return these errors in json format. My views

class HolidayList(ListCreateAPIView):
    queryset = Holiday.objects.all()
    serializer_class = HolidaySerializer
    permission_classes = [IsAdminUser, IsAuthenticated]

Model

class Holiday(models.Model):
   title = models.CharField(verbose_name=_("Title"), max_length=255)
   slug = models.SlugField(unique=True)
   destination_place = models.ManyToManyField(to='places.Place',related_name='destination_place',null=True,blank=True)
2
  • Please post Holiday model. Commented Nov 13, 2017 at 7:57
  • Holiday Model added. Commented Nov 13, 2017 at 8:00

1 Answer 1

1

In HolidaySerializer, add UniqueValidator on slug field.

Example:

from rest_framework.validators import UniqueValidator

class HolidaySerializer(serializers.ModelSerializer):
    slug = serializers.SlugField(
             max_length=255,
             validators=[UniqueValidator(queryset=Holiday.objects.all())])

    class Meta:
        model = Holiday
        fields = ('id', 'title', 'slug', 'destination_place', )

This will return back the unique constraint error in the JSON format.

You can customize the message. Look at the docs.

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

2 Comments

Thanks it works. Is there any way to return json errors for all serializers.
If the serializer is not valid, it will return back the error it encountered. If something that you wished the serializer to encounter, then you can override validate method in the serializer.

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.