0

I am trying to build a GET and POST method to get and save some objects. I have views.py like this

class QuestionList(generics.ListAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

class QuestionSave(generics.CreateAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

Then I have url conf, urls.py like this

urlpatterns = [
    url(r'^questions/$',views.QuestionList.as_view())
    ]

In my understanding, we have to have a generic class with CreateApiView for POST methods and ListApiView for GET method and so I have created classes like that. My question is, how should I configure them so that on POST QuestionSave will be called and on GET QuestionList will be called?

1
  • why not QuestionList(generics.ListAPIView, generics.CreateAPIView)? Commented Jul 26, 2018 at 11:37

2 Answers 2

3

Use ListCreateAPIView. It provides get and post method handlers for a view.

Refer: Django Rest Framework

class QuestionView(generics.ListCreateAPIView)
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the answer and it worked but now I am getting 'this field is required' error. Can you help me on this one as well?
Sure. Post the code for your model's serializer and model
The error for 'this field is required' is raised when you're not sending a particular field in post request, but it is required in your model or serializer.
2

Simple!:

class QuestionList(generics.ListAPIView, generics.CreateAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

Comments

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.