SilentDev
SilentDev

Reputation: 22767

DjangoRestFramework - How to pass a serializer form to the frontend?

I'm using the DjangoRestFramework. I have a UserSerialzer in my serializers.py file:

from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('username', 'password', 'email', )

This is my urls.py file:

urlpatterns = [
    url(r'^$', views.HomePageView.as_view()),
    url(r'^users$', views.user_list.as_view()),
    url(r'^users/(?P<pk>[0-9]+)$', views.user_detail.as_view()),
]

and this is my views.py file:

class HomePageView(TemplateView):
    template_name = "home.html"

    def get_context_data(self, **kwargs):
            context = super(HomePageView, self).get_context_data(**kwargs)
            # context['users'] = User.objects.all()
            return context

class user_list(APIView):
    """
    List all users, or create a new user.
    """
    serializer_class = UserSerializer

    def get(self, request):
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)

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

class user_detail(APIView):
    """
    Get, update or delete a specific user.
    """
    serializer_class = UserSerializer
    def get_object(self, pk):
        try:
            return User.objects.get(pk=pk)
        except User.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

    def get(self, request, pk):
        user = self.get_object(pk)
        serializer = UserSerializer(user)
        return Response(serializer.data)

    def put(self, request, pk):
        user = self.get_object(pk)
        serializer = UserSerializer(user, data=request.DATA)
        if serialzier.is_valid():
            serializier.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        user = self.get_object(pk)
        user.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

When I go to 127.0.0.1:8000/users, DjangoRestFramework has the API page which shows a list of users (JSON objects) and it also has a form which has "username", "password" and "email". This form seems to be validating correctly (checks if the email is a real email, and checks if username is unique and less than 30 characters). Is there a way for me to pass this form to the frontend when a user goes to 127.0.0.1:8000 (calling HomePageView)?

I'm in the process of using AngularJS on the frontend (not sure if this information helps or not).

Upvotes: 2

Views: 2079

Answers (1)

Zoe Steinkamp
Zoe Steinkamp

Reputation: 149

Well here are a few things I think we might need to point out. Django forms are normally what you would use to create a new user, with a post request just like you are trying to do through DRF. Now you can do this through DRF, but thats not really what it is for, django forms would be more appropriate for what you are doing. Unless of course you are building an API that you want API users to be able to use to create new users on your platform, in which case continue onward. I am linking a tutorial I used when I first started using DRF with Angular, maybe you will find it helpful.

http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html

Upvotes: 1

Related Questions