In Django Rest Framework I did the seriailizers, viewsets and routers approach. Whenever I POST with an intentional error in the API view of django rest framework it throws an Integrity Error. Is there a way to try and catch the errors like if there is no errors in the data just proceed to save however if there are errors throw a JSON Response with the list of errors like:
[{'section':'This field can not be blank', 'first_name':'This field can not be blank', 'middle_name':'This field can not be blank', 'last_name':'This field can not be blank'}]
models.py
from django.db import models
# Create your models here.
# class AuditTable(models.Model):
# date_created = models.DateTimeField(auto_now_add=True)
# test_field = models.CharField(max_length=50, null=True, blank=True)
class Section(models.Model):
name = models.CharField(max_length=50, default=None)
def __str__(self):
return self.name
class Student(models.Model):
section = models.ForeignKey(Section, default=None)
first_name = models.CharField(max_length=50, default=None)
middle_name = models.CharField(max_length=50, default=None)
last_name = models.CharField(max_length=50, default=None)
def __str__(self):
full_name = "%s %s %s" % (self.first_name, self.middle_name, self.last_name)
return full_name
serializers.py
from rest_framework import serializers
from rest_framework.response import Response
from . models import *
class SectionSerializer(serializers.ModelSerializer):
class Meta:
model = Section
fields = ('name', )
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ('section', 'first_name', 'middle_name', 'last_name' )
viewsets.py
from rest_framework import viewsets
from . serializers import *
from . models import *
class SectionViewSet(viewsets.ModelViewSet):
queryset = Section.objects.all()
serializer_class = SectionSerializer
class StudentViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
routers.py
from rest_framework import routers
from . viewsets import *
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'students', StudentViewSet)
router.register(r'sections', SectionViewSet)
urls.py
from django.conf.urls import include, url
from . import views
from . routers import router
urlpatterns = [
url(r'^$', views.index, name='testing_sample_index' ),
url(r'^restful-form/$', views.web_service_form, name='testing_sample_web_service' ),
url(r'^api/', include(router.urls)),
]