python - How to support all REST operations for an endpoint in django rest framework -
i have subscription model looks this
class subscription(models.model): name = models.charfield(max_length=100) quantity = models.integerfield(max_length=20) stripe_id = models.charfield(max_length=100) user = models.foreignkey(user)
i create endpoint allows post, patch, delete, get
so did following things
views.py
class subscriptiondetail(viewsets.modelviewset): serializer_class = subscriptionserializer permission_classes = (isauthenticated,) queryset = subscription.objects.all()
serializers.py
class subscriptionserializer(serializers.modelserializer): class meta: model = subscription fields = ('name','quantity', 'stripe_id') def update(self, instance, validated_data): print "in update" #how write create , delete?
urls.py
subscription = subscriptiondetail.as_view({ 'patch': 'update' }) url(r'^rest-auth/subscription/$', subscription, name='something'),
questions
- using above when send
patch
request, error. how can fix this?
expected view subscriptiondetail called url keyword argument named "pk". fix url conf, or set
.lookup_field
attribute on view correctly.
- while sending patch request send 'email' field not on subscription model. possible do? need
email
field inpost (create)
operation know user subscription belongs to.
the easiest way way.
keep models class same
views.py
from rest_framework import viewsets #impost serializer , model class subscription class subscriptionviewset(viewsets.modelviewset): serializer_class = subscriptionserializer def get_queryset(self): queryset = subscription.objects.all() #if need subscription name name = self.request.query_params.get('name', none) if name not none: queryset = queryset.filter(name=name) return queryset
serializers.py
class subscriptionserializer(serializers.modelserializer): class meta: model = subscription fields = ('name','quantity', 'stripe_id') # django handle get, delete,patch, update .... # customization can use def update or def create ... whatever need # def create(self, validated_data): # can handle email here # , subscription= subscription (name=validated_data['name'],vendor=validated_data['quantity']...) # subscription.save() # save whatever want
urls.py
#use router handle django.conf.urls import patterns, include, url rest_framework import routers #import classes router = routers.defaultrouter() router.register(r'subscription', views.subscriptionviewset,base_name='subscription') urlpatterns = patterns('', url(r'^', include(router.urls)), )
Comments
Post a Comment