Retrieving images from Django from rest_framework - python

models.py:
from __future__ import unicode_literals
from django.db import models
class Photo(models.Model):
title = models.CharField(max_length=255, blank=True)
file = models.FileField()
uploaded_at = models.DateTimeField(auto_now_add=True)
serializers.py:
from rest_framework import serializers
from . models import Photo
class imageSerializer(serializers.ModelSerializer):
class Meta:
model = Photo
fields='__all__'
views.py:
from django.shortcuts import render,redirect
from django.http import JsonResponse
from django.views import View
import time
from rest_framework import generics
from .forms import PhotoForm
from .models import Photo
from django.http import HttpResponse
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework import status
from .serializers import imageSerializer
import requests
class DragAndDropUploadView(View):
def get(self, request):
photos_list = Photo.objects.all()
return render(self.request, 'UploadMulti/drag_and_drop_upload/index.html', {'photos': photos_list})
def post(self, request):
form = PhotoForm(self.request.POST, self.request.FILES)
if form.is_valid():
photo = form.save()
data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
else:
data = {'is_valid': False}
return JsonResponse(data)
def clear_database(request):
for photo in Photo.objects.all():
photo.file.delete()
photo.delete()
return redirect(request.POST.get('next'))
class ImagesList(APIView):
def get(self,request):
imagelist=Photo.objects.all()
serializer = imageSerializer(imagelist,many=True)
return Response(serializer.data)
def post(self):
pass
def backend(request):
response = requests.get('http://localhost:8000/images/')
api_values = response.json()
for values in api_values:
print(type(values['file']))
return render(request,"home.html",{'data':api_values})
when I print type of values.file which is the image data I am getting as therefore when sending it to frontend the image is not displayed
How to retrieve as image file from rest api?
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"id": 1,
"title": "",
"file": "think-twice-code-once.jpg",
"uploaded_at": "2019-11-27T12:34:32.270786Z"
}
]
Is there any other method to obtain images from rest framework and whether the image is stored as Image format ?

The issue is due to your configuration of FileField for this particular serializer. You need use_url to be True. So you can either change the UPLOADED_FILES_USE_URL setting or set use_url=True in imageSerializer as seen below.
class imageSerializer(serializers.ModelSerializer):
class Meta:
model = Photo
fields='__all__'
file = serializers.FileField(use_url=True)
Side note, imageSerializer should really be ImageSerializer to follow the python class naming guidelines.

Related

How to compare parameter passed through POST method with Django rest framework Model and generate custom response?

I am designing Basic Django rest framework based application, i need to compare external parameters passed through POST method in Postman with Coupon code in database and generate custom response like 'This code is redeemed/validate." or " This is invalid coupon/code."
Here is my Model.py file :
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
class Coupon(models.Model):
code = models.CharField(max_length=50, unique=True)
valid_from = models.DateTimeField()
valid_to = models.DateTimeField()
discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)])
active = models.BooleanField()
def __str__(self):
return self.code
here is my views.py file:
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Coupon
from .serializers import CouponSerializer
from rest_framework import viewsets
class CouponViewSet(viewsets.ModelViewSet):
queryset = Coupon.objects.all()
serializer_class = CouponSerializer
#api_view(['POST'])
def coupon_redeem(request):
if request.method =='POST':
serializer = CouponSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
here is my Serializer.py file
from rest_framework import serializers
from .models import Coupon
class CouponSerializer(serializers.ModelSerializer):
class Meta:
model = Coupon
fields = '__all__'
Please help if possible, Thank you.
IN Your post method u can filter the desired object like:
if serializer.is_valid():
coup=Coupon.objects.filter(code=serializer.data['code'],active=True).exists()
if(coup=="NULL"):
return Response("This is invalid coupon/code",status=status.HTTP_400_BAD_REQUEST)
else:
return Response("This is valid code",status=status.HTTP_200_OK)

How to store different data from JSON to different fields in django/python

I'm sending a request with POSTMAN to my server, and getting JSON with such function
__get_json__ it work well.
Here it is by the way.
def __get_json__(request):
try:
if request.method == 'POST':
data = request.body.decode('utf-8')
json_data = json.loads(data)
json_response("OK")
return json_data
else:
return error_response(406, "Request was not a json or POST type")
except ValueError:
return exception_error(500, "Server Issue")
and after here i'm returning in the function register_user
def register_user(request):
user_jsonify_data = __get_json__(request)
I wanna to store my data to different fields, for example i have such JSON
{
"name": "Tenders",
"id": "2135324123",
"set": "set"
}
How can i split it correctly?
pip install djangorestframework
add rest_framework to settings.INSTALLED_APPS
Example:
# models.py
from django.db import models
class User(models.Model):
id = models.CharField(max_length=30, primary_key=True)
name = models.CharField(max_length=30)
set = models.CharField(max_length=30)
# serializers.py
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
# views.py
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import UserSerializer
class RegisterView(APIView):
serializer_class = UserSerializer
def post(self, request, format=None):
serializer = self.serializer_class(request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)

how do i get the filename of a duplicated saved file on django models?

When i upload a file with the same name the second one is uploaded with a different name like this:
First file: file.txt
Second file: file1YlQx18.txt
I want to get the name of the second file on a views.py
because when i get the filename by method POST i just have file.txt
I'm using Django Rest Framework serializers
viewsets.py
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
class CreateOnlyViewSet(mixins.CreateModelMixin, GenericViewSet):
def pos_create(self, request):
pass
def dispatch(self, request, *args, **kwargs):
r = super(CreateOnlyViewSet, self).dispatch(request, *args, **kwargs)
if r.status_code == 200 or r.status_code == 201:
return self.pos_create(request)
serializers.py
from rest_framework import serializers
from .models import MyModel
class CareerSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'
views.py
from rest_framework.views import APIView
from models import MyModel
from .serializers import MyModelSerializer
from .viewsets import CreateOnlyViewSet
class MyModelViewSet(CreateOnlyViewSet):
model = MyModel
serializer_class = MyModelSerializer
def pos_create(self, request):
serialized = MymodelSerializer(data=request.POST)
#get name of the second file

DRF AttributeError type object 'QuerySet' has no attribute 'nom'

I'm making my first DRF api I get a strange AttributeError that I don't understand. When I try to access to my data using a GET request, I get this error:
Got AttributeError when attempting to get a value for field nom on
serializer ExpediteurSerializer. The serializer field might be named
incorrectly and not match any attribute or key on the type instance.
Original exception text was: type object 'QuerySet' has no attribute
'nom'.
I guess I've done something unexpected in my serializers.py file.. Here follows some snippets of my code.
models.py
from django.db import models
# Create your models here.
class Expediteur(models.Model):
nom = models.CharField(max_length=50)
prenom = models.CharField(max_length=100)
adresse = models.CharField(max_length=200)
tel = models.IntegerField()
views.py
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.response import Response
from polls.serializers import ExpediteurSerializer, DestinataireSerializer, LettrePrioSerializer, TypeLettreRecoSerializer, LettreRecoSerializer, TimbrePrioSerializer, TimbreRecoSerializer
from polls.models import Expediteur, Destinataire, LettrePrio, TypeLettreReco, LettreReco, TimbrePrio, TimbreReco
from rest_framework import status, HTTP_HEADER_ENCODING
from django.shortcuts import render, get_object_or_404
import json
import datetime
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth import login
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
from django.utils.timezone import get_current_timezone
# Create your views here.
class ExpeViewSet(APIView):
serializer_class = ExpediteurSerializer
def get(self, request):
queryset = Expediteur.objects.all()
serializer = ExpediteurSerializer(queryset)
return Response(serializer.data)
def post(self, request):
serializer = self.serializer_class(data=request.DATA)
return Response(status=status.HTTP_201_CREATED)
serializers.py
from rest_framework import serializers
from polls.models import Expediteur, Destinataire, LettrePrio, TypeLettreReco, LettreReco, TimbrePrio, TimbreReco
class ExpediteurSerializer(serializers.Serializer):
nom = serializers.CharField(required=True, allow_blank=False, max_length=50)
prenom = serializers.CharField(required=True, allow_blank=False, max_length=100)
adresse = serializers.CharField(required=True, allow_blank=False, max_length=200)
tel = serializers.IntegerField(required=True)
def create(self, validated_data):
return Expediteur.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.nom = validated_data.get('nom', instance.nom)
instance.prenom = validated_data.get('prenom', instance.prenom)
instance.adresse = validated_data.get('adresse', insatnce.adresse)
instance.tel = validated_data.get('tel', instance.tel)
instance.save()
return instance
I think you are missing the many flag in you view, like so:
ExpediteurSerializer(queryset, many=True)
In general you could simplify your code very much by fully utilizing DRF.
First, make ExpediteurSerializer a ModelSerializer according to the documentation.
Then you can also get rid of the create and update method, DRF takes care of all of that for you. And I strongly recommend you to look at ModelViewSets, they make your life very easy.

Handling JSON Post request in Django rest framework

I want to create model entity in database using POST request. GET is working fine but POST is not being triggered. views.py is as follows:
<code>
from django.shortcuts import render
from rest_framework import viewsets, generics
from server_app.serializers import DataSerializer
from server_app.models import DataModel
from rest_framework.views import APIView
from rest_framework.parsers import JSONParser
from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from server_app.serializers import DataSerializer
import logging
import json
from django.http import HttpResponse
from django.views.generic import View
class MyView(View):
def get(self, request, *args, **kwargs):
return HttpResponse('This is GET request')
def post(self, request, *args, **kwargs):
return HttpResponse('This is POST request')
class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
logger = logging.getLogger(__name__)
#csrf_exempt
def DataModel_list(request):
if request.method == 'GET':
logger.error("GET DATA SERVER")
queryset = DataModel.objects.all()
serializer_class = DataSerializer(queryset, many=True)
#return HttpResponse(json.dumps(serializer_class.data),content_type="application/json")
return JSONResponse(serializer_class.data)
elif request.method == 'POST':
logger.error("POST DATA SERVER")
json_data = JSONParser().parse(request)
serializer_class = DataSerializer(data=json_data)
if serializer_class.is_valid():
serializer_class.save()
return JSONResponse(serializer_class.data, status=201)
return JSONResponse(serializer_class.errors, status=400)
</code>
And following is my urls.py
<code>
from django.conf.urls import patterns, include, url
from rest_framework import routers
from django.contrib import admin
from server_app import views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^getDataModel/$', views.DataModel_list),
url(r'^admin/', include(admin.site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
</code>
And serializers.py
<code>
from rest_framework import serializers
from server_app.models import DataModel
class DataSerializer(serializers.ModelSerializer):
class Meta:
model = DataModel
fields = ('first_name', 'last_name', 'chapter', 'category', 'email', 'mantinada')
</code>
models.py
<code>
from django.db import models
# Create your models here.
class DataModel(models.Model):
first_name = models.CharField(max_length = 200)
last_name = models.CharField(max_length = 200)
chapter = models.CharField(max_length = 200)
category = models.CharField(max_length = 200)
email = models.CharField(max_length = 200)
mantinada = models.CharField(max_length = 200)
</code>
I have put logger in GET and POST requests. When I access url for GET I can see the results and logger consoles but for POSt request, i am not getting any logger information. Can anyone please tell me what I am missing?
Thanks in advance.
There was nothing wrong at the django server end. I was calling wrongly from the android-client side because the keys in the android json object were different from fields in models. Correcting the keys have solved the problem.

Categories

Resources