Discussion:
Retrieve ID from url route in GET
Benjamin SOULAS
2018-08-14 09:16:02 UTC
Permalink
Hi everyone, I am relatively new to DRF,

I try to implement an API in which I use pymongo to insert my data in DB,
but without the ORM. I have implemented a View as follows:

import traceback

from api.EmsSerializer.ProductSerializer import ProductSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


class ProductRecordView(APIView):
"""
A class based view for creating and fetching product records
"""
def get(self, request):
"""

"""
print(*args)
print(**kwargs)
print(request)


def post(self, request):
"""

@brief
"""
try:
# JSON data retrieval
wData = request.data

# Serializer instanciation
wSerializer = ProductSerializer()
# Validation checkings: @TODO

# Product creation
wCreatedProductDict = wSerializer.Create(aData=wData)

# response return
print("VIEWS: wCreatedproduct")
print(wCreatedProductDict)
return Response(wCreatedProductDict, status=status.HTTP_201_CREATED)

except Exception:
traceback.print_exc()

return Response(status=status.HTTP_400_BAD_REQUEST)


And the object I use is Product:

# coding: utf-8


class Product(object):

def __init__(self, aActiveComm, aName, aImg, aSettings, aSourceId, aCommStatus, aActivated, aZoneId, aChannels,
aServices, aSettingStatus, aCommSettings, aHistory, aLandmark, aUsageId, aCreationDate, aType,
aCabinetId, aDescription):
self._id = None
self.activeComm = aActiveComm
self.name = aName
self.img = aImg
self.settings = aSettings
self.sourceId = aSourceId
self.commStatus = aCommStatus
self.activated = aActivated
self.zoneId = aZoneId
self.channels = aChannels
self.services = aServices
self.settingStatus = aSettingStatus
self.commSettings = aCommSettings
self.history = aHistory
self.landmark = aLandmark
self.usageId = aUsageId
self.creationDate = aCreationDate
self.type = aType
self.cabinetId = aCabinetId
self.description = aDescription

def ToDict(self):
"""
ToDict
@brief: Return object in dict format
:return: Dict
"""
return self.__dict__


Here is my url.py

from django.conf.urls import url
from django.contrib import admin
from django.urls import path
from api import views

urlpatterns = [
url('admin/', admin.site.urls),
url('api/products/', views.ProductRecordView.as_view()),
url(r'^api/products/(?P<product_id>\d+)$', views.ProductRecordView.as_view()),
]



In POST request, it work like a charm, But if I want to try a GET request,
I don't even know how to get the ID defined in the url

Maybe it is trivial, but I really need help ...

Kind regards
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Benjamin SOULAS
2018-08-14 11:51:08 UTC
Permalink
To be more precise, I Don't need the ORM part (including Models) but only
the front which handle data received, Maybe the APIView I use does not work
If no Models has been used? Which could explain that I cannot retreive the
ID of the path which should be linked to the Models (in which I should have
defined the given ID?)

I really need answers ....

Kind Regards
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
gordon
2018-08-14 12:03:11 UTC
Permalink
Good morning Benjamin. This is a Django problem. You should read the Django
getting started tutorial. But your url params are available in the views.
Try adding *args and **kwargs in the get a post method definition. On my
cell so can't give direct links
Post by Benjamin SOULAS
To be more precise, I Don't need the ORM part (including Models) but only
the front which handle data received, Maybe the APIView I use does not work
If no Models has been used? Which could explain that I cannot retreive the
ID of the path which should be linked to the Models (in which I should have
defined the given ID?)
I really need answers ....
Kind Regards
--
You received this message because you are subscribed to the Google Groups
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an
For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Benjamin SOULAS
2018-08-14 12:29:01 UTC
Permalink
Hi !

But I saw in the groups that if you don't use the ORM part and, just like
me, you need only the front part, you cannot use views such as APIView
because it seems to be hardly linked to the Models. Because I use my own
models that does not inheritate from django models), the APIView cannot
handle this.

And for the record, because I dont have too much time, I did not implement
tests so hard to see where in args or kwargs the id is located, even when I
analyzed the django request library

So I implement my own view:

@api_view(["GET", "POST"])
def ProductDetail(aRequest, pk):
"""

@brief Retrieve a products or create a new product.
"""
if aRequest.method == 'GET':
print("GET METHOD")
print(pk)



elif aRequest.method == 'POST':
print("POST METHOD")
try:
# JSON data retrieval
wData = aRequest.data

# Serializer instanciation
wSerializer = ProductSerializer()
# Validation checkings: @TODO

# Product creation
wCreatedProductDict = wSerializer.Create(aData=wData)

# response return
print("VIEWS: wCreatedproduct")
print(wCreatedProductDict)
return Response(wCreatedProductDict, status=status.HTTP_201_CREATED)

except Exception:
traceback.print_exc()

return Response(status=status.HTTP_400_BAD_REQUEST)


Now it works much better, but indeed I have to write my own serializer.

BUT ! I there is a trick to retreive the Id defined in the path in an
APIView, do not hesitate to tell me :)

King regards,

Benjamin.
Post by gordon
Good morning Benjamin. This is a Django problem. You should read the
Django getting started tutorial. But your url params are available in the
views. Try adding *args and **kwargs in the get a post method definition.
On my cell so can't give direct links
Post by Benjamin SOULAS
To be more precise, I Don't need the ORM part (including Models) but only
the front which handle data received, Maybe the APIView I use does not work
If no Models has been used? Which could explain that I cannot retreive the
ID of the path which should be linked to the Models (in which I should have
defined the given ID?)
I really need answers ....
Kind Regards
--
You received this message because you are subscribed to the Google Groups
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an
.
For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Continue reading on narkive:
Loading...