I want to create boiler-plate forms for my django models using the rest framework.
Documentation shows it using the APIView: http://www.django-rest-framework.org/topics/html-and-forms/#rendering-forms.
But I want to use the ModelViewSet in order to avoid defining custom action methods.
Is this possible? Can you share an example?
Here is what I tried. My model:
class Person(AbstractUser):
pass
My serializer:
class PersonSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Person
fields = ('first_name', 'last_name', 'email', 'groups')
My view:
class PersonViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows persons to be viewed or edited.
"""
queryset = Person.objects.all().order_by('-date_joined')
serializer_class = PersonSerializer
renderer_classes = [TemplateHTMLRenderer]
template_name = 'common/rest_create.html'
And here is my url:
url(r'person_create_api/$', PersonViewSet.as_view({'get': 'create'}), name='person-create-api'),
And the error I get:
IntegrityError at /school/person_create_api/
duplicate key value violates unique constraint "school_person_username_key"
DETAIL: Key (username)=() already exists.
When I add the username
field to the serializer fields, I get:
HTTP/1.0 400 Bad Request
Date: Tue, 20 Sep 2016 17:00:22 GMT
Server: WSGIServer/0.2 CPython/3.5.1+
X-Frame-Options: SAMEORIGIN
Vary: Cookie
Allow: GET, HEAD, OPTIONS
Content-Type: text/html; charset=utf-8
I am using django 1.9 and latest DRF 3.4.6.