Django: How to fetch id in class based views? - python-3.x

views.py
from paitent.mixini import HttpResponseMixin,SerializeMixin
from paitent.models import Paitent_Details
class PaitentCRUDCBV(View, HttpResponseMixin, SerializeMixin):
def get(self, id, *args, **kwargs):
paitent = Paitent_Details.objects.get(id=id)
json_data = self.render_to_serialize([paitent,])
return self.render_to_http_response(json_data)
urls.py
urlpatterns = [
url(r'^api/json',views.PaitentCRUDCBV.as_view()),
]
My requirement is based on id i have to fetch particular row form data base,from Frontend side i am passing id in url like:(url: "http://127.0.0.1:8000/api/json/?id=2").But i am not finding id inside my class ,don't know where i am doing wrong. please help me.

You can use query_params in view:
def get(self, request):
id = self.request.query_params.get('id')
....
You can get more information from documentation

1)I have edited your following code, you have to pass *request* in your function,
2)Inside the function calling request.query_params.get, you will get parameters value from the url
from paitent.mixini import HttpResponseMixin,SerializeMixin
from paitent.models import Paitent_Details
class PaitentCRUDCBV(View, HttpResponseMixin, SerializeMixin):
def get(self, request, *args, **kwargs):
id=self.request.query_params.get('id')
paitent = Paitent_Details.objects.get(id=id)
json_data = self.render_to_serialize([paitent,])
return self.render_to_http_response(json_data)

Related

DRF's not calling post() method when receiving POST request

I have a viewset like this:
class MyViewSet(CreateAPIView, RetrieveModelMixin, ListModelMixin, GenericViewSet):
queryset = MyModel.objects.all()
serializer_class = MySerializer
def post(self, request, *args, **kwargs):
import pdb; pdb.set_trace()
class MySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MyModel
fields = ['id', 'field1', 'field2'] #only field1 is required in the model
The GET requests for list, and retrieve works perfectly. When I make a POST request, sending the field1 I get a status 201 and a new record is added to the database, so it works too.
But my method MyViewSet.post() that should overwrite the same one from generics.CreateAPIView never gets called.
Not only that, but I've tried to add the pdb.set_trace(), literally inside the generics.CreateAPIView.post() and in the CreateModelMixin.create() functions and neither stopped once I made the POST request.
So something else is handling this POST request and inserting into the DB, I just don't know what. And how can I overwrite it, so I can customize what should be done with a post request?
PS.: Also, I don't think it's a routing problem, my urls.py:
from rest_framework import routers
from myapp.views import MyViewSet, AnotherViewSet
router = routers.DefaultRouter()
router.register(r'route_one', MyViewSet)
router.register(r'route_two', AnotherViewSet)
I think you need to use the exact class in order to use POST api.
class MyView(CreateModelMixin, ListModelMixin, generics.GenericAPIView):
queryset = MyModel.objects.all()
serializer_class = MySerializer
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
In urls.py
from django.urls import path
from .views import MyView
urlpatterns = [
path('route_one', MyView.as_view(), name="my_view_detail")
]

how do i wrtite django fbv to class based view

I have two user types a and b i need to write the below fbv into class based Logoutview(auth.view) how do i write the below fbv to cbv
views.py
#login_required
def logout(request):
if request.user.usertype_a:
logout(request)
return redirect(reverse('user_a_login'))
else:
logout(request)
return redirect(reverse('user_b_login'))
Give this a try
from django.views import View
class LogOutView(View):
def get(self, request, *args, **kwargs):
logout(request)
if request.user.usertype_a:
return redirect(reverse('user_a_login'))
return redirect(reverse('user_b_login'))
Or you can Use LogoutView and override its dispatch method for custom redirections
Try to add this to your urls.py:
from django.contrib.auth import views as auth_views
path('logout/', auth_views.LogoutView.as_view(), name='logout'),

how to add a method to a class template view

happy new year everyone...I am new to django and i am working on a project a resume page i need help with the contact me section, i want to do something i seen in a video https://www.youtube.com/watch?v=w4ilq6Zk-08. The book i used to learn only uses class to view templates. below is my code
from django.views.generic import TemplateView
from django.shortcuts import render
# Create your views here.
class ProfilePageView(TemplateView):
template_name = 'femi_profile.html'
def contact(request):
if request.method == "POST":
name = request.POST['name']
email = request.POST['email']
subject = request.POST['subject']
message = request.POST['message']
return render(request, 'femi_profile.html', {'contact_name': name})
else:
return render(request, 'femi_profile.html', {})
After reading the django documentation https://docs.djangoproject.com/en/3.1/topics/class-based-views/intro/ once more and trying different lines of code i finally got that run and i am not asking why is it runing? i figured out how to go about this.
find the correct code below
from django.views.generic import TemplateView
from django.shortcuts import render
# Create your views here.
class ProfilePageView(TemplateView):
template_name = 'femi_profile.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name, {})
def post(self, request, *args, **kwargs):
if request.method == "POST":
name = request.POST['name']
email = request.POST['email']
subject = request.POST['subject']
message = request.POST['message']
return render(request, self.template_name, {'contact_name': name})

Django RestFramework call the Api by the Field

currently i pass the parameter 'id' in the url and i call the API by id however i would like to call API by the parameter.here is views.py`
class post_list(APIView):
def get(self,request,format=None):
post_resource=PostResource()
dataset=Dataset()
post = Post.objects.all()
serializer = PostSerializer(post, many=True)
a=[]
for row in post:
a.append(row)
return Response(serializer.data)
def post(self,request,format =None):
serializer = PostSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)
class post_detail(APIView):
def get_object(self, pk):
try:
return Post.objects.get(pk=pk)
except Post.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
post = self.get_object(pk)
serializer = PostSerializer(post)
return Response(serializer.data)
def put(self, request, pk, format=None):
snippet = self.get_object(pk)
serializer = PostSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
post = self.get_object(pk)
post.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
this is the result when i pass the id in the url`
when i pass the id in the url it's show only the that particular id result however i need view if i pass the other field instead of the id it's show the result based on that.so my question is what should i have to change in the views.py and Urls.py. this is urls.py file`
from django.conf.urls import url
from api import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^post/$', views.post_list.as_view()),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail.as_view()),
]
urlpatterns=format_suffix_patterns(urlpatterns)
This is my serializer.py file`
from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
#fields=('ProductName','Score')
fields ='__all__'
`
You should change your url so that it accepts string:
url(r'^post/(?P<pname>[a-zA-Z0-9]+)/$', views.post_detail.as_view())
and then change your get_object method like this:
def get_object(self, pname):
try:
return Post.objects.get(pname=pname)
except Post.DoesNotExist:
raise Http404
But you will issues if pname is not unique, because it will complain that you have more than one such Post.
Hope it helps!

How does one properly create a customized Swagger Schema in the Django Rest Framework?

I am having trouble creating a customizable swagger schema in the Django Rest Framework. I have read pages of documentation, but have not found a clear cut example on how to generate swagger annotations in python.
I am aware that swagger/schema documentation is readily generated when using ViewSets in Django. However, I am solely using APIViews and want to write a customized schema. I have tried creating a CoreAPI schema but am unaware of how to implement it. I am enclosing some of my sample code and some screenshots as well. The screen shots go from what I have to what I want.
Sample code:
urls.py
from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from Views import SampleView as sv
from rest_framework_swagger.views import get_swagger_view
from rest_framework.documentation import include_docs_urls
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.schemas import get_schema_view
schema_view enter code here= get_swagger_view(
title='Sample API')
urlpatterns = [
url(r'^sample/$', pv.SampleList.as_view()),
url(r'^sample/(?P<id>[a-f\d]{24})/$', sv.SampleDetail.as_view()),
url('^schema/$', schema_view),
]
urlpatterns = format_suffix_patterns(urlpatterns)
views.py
from rest_framework.views import APIView
from Manager.SampleManager import SampleManager as sm
_sampleManager = sm()
class SampleList(APIView):
"""
get:
Return a list of all the existing samples.
post:
Create a new sample.
"""
def get(self, request, format=None):
return _sampleManager.getAll()
def post(self, request, format=None):
return _sampleManager.create( request)
class SampleDetail(APIView):
"""
get:
Get a sample.
put:
Update a sample.
delete:
Delete a sample.
"""
def get(self, request, id, format =None):
return _sampleManager.getById( id)
def put(self, request, id, format =None):
return _sampleManager.update( request, id)
def delete(self, request, id, format =None):
return _sampleManager.deleteById( id)
Serializers.py
from rest_framework_mongoengine.serializers import DocumentSerializer
from .modles import Sample, SampleInner
from Serializers.SampleInnerSerializer import SampleInnerSerializer
class SampleSerializer(DocumentSerializer):
other = SampleInnerSerializer(many=True)
class Meta:
model = Sample
fields = '__all__'
def create(self, validated_data):
samples = validated_data.pop('other')
created_instance = super(SampleSerializer, self).create(validated_data)
for sample_data in samples:
created_instance.other.append(SampleInner(**sample_data))
created_instance.save()
return created_instance
def update(self, instance, validated_data):
samples = validated_data.pop('other')
updated_instance = super(SampleSerializer, self).update(instance, validated_data)
for sample_data in samples:
updated_instance.other.append(SampleInner(**sample_data))
updated_instance.save()
return updated_instance
Schema.py
import coreapi
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import renderers, response
schema = coreapi.Document(
title='Sample API',
content={
'sample': coreapi.Link(
url='/sample/',
action='post',
fields=[
coreapi.Field(
name='from',
required=True,
location='query',
description='City name or airport code.'
),
coreapi.Field(
name='to',
required=True,
location='query',
description='City name or airport code.'
),
coreapi.Field(
name='date',
required=True,
location='query',
description='Flight date in "YYYY-MM-DD" format.'
)
],
description='Create partner'
)
}
)
#api_view()
#renderer_classes([renderers.CoreJSONRenderer])
def schema_view(request):
return response.Response(schema)
There is two solution for you in this senario, One "go with the GenricApiView" Two "Create Custom row Schema"
let's go with
-- >solution one.
urls.py
schema_view = get_swagger_view(title='Test All API')
urlpatterns = [
path('swagger2/', schema_view),
]
view.py
class LoginAPIView(generics.GenericAPIView):
serializer_class = LoginSerializer
permission_classes = [permissions.AllowAny]
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.data, status=status.HTTP_200_OK)
Result
--> Solution two:
urls.py
configuration is same as before
views.py
class BlacklistTokenAdding(APIView):
permission_classes = [permissions.AllowAny]
schema = ManualSchema(fields=[
coreapi.Field(
"first_field",
required=True,
location="body",
schema=coreschema.String()
),
coreapi.Field(
"second_field",
required=True,
location="body",
schema=coreschema.String()
),
])
def post(self, request, format='json'):
try:
refresh_token = request.data["refresh_token"]
token = RefreshToken(refresh_token)
token.blacklist()
return Response(status=status.HTTP_200_OK)
except Exception as e:
return Response(status=status.HTTP_400_BAD_REQUEST)
//Note the first_field & second_field is to demonstration you can add here as much field as you want.
Result

Resources