Lior
Lior

Reputation: 109

How to send parameter in AJAX (rest-api) using django?

I utilities rest-api in django, and I don't succeed to send a "GET" parameter through ajax:

In rest-api app in django I have in the urls.py:

urlpatterns = patterns('',
    url(r'^titles/(?P<author_id>\d+)/$', login_required(views.TitlesViewSet.as_view()) ),
)

In views.py I wrote:

class TitlesViewSetViewSet(ListCreateAPIView):
     serializer_class = TitleSerializer

     def get_queryset(self):
         aouther_id = self.request.GET.get('aouther_id', None)
         return Title.objects.filter(auther = auther_id)

when the code insert to the get_queryset above it doesn't recognize any GET parameter and the aouther_id is set to None.

Does anybody know what I should do?

Upvotes: 0

Views: 382

Answers (2)

Lior
Lior

Reputation: 109

you should replace a line of the auther_id setting to:

auther_id=self.kwargs['auther_id']

update: I now see jbub answer... thanks man! I just discovered it...

Upvotes: 1

jbub
jbub

Reputation: 2665

First, you have a typo in urls, you are using author_id and in view you are trying to get the aouther_id key. Second, you are trying to get the value from the query parameters, but you are not actually using them. Third, you are using named url parameters and those are being stored in the kwargs property of your class based view.

You can access them this way:

class TitlesViewSetViewSet(ListCreateAPIView):
    serializer_class = TitleSerializer

    def get_queryset(self):
        # try printing self.kwargs here, to see the contents
        return Title.objects.filter(author_id=self.kwargs.get('author_id'))

Upvotes: 2

Related Questions