Как я генерирую qr-код в django rest framework api
я хочу сделать сканируемый qr-код api
генерировать qr код и поместить текст внутри qr кода (предложения)
ответ в формате изображения
models.py
....
qr_code = models.ImageField(upload_to='qr_codes', blank=True)
...
models.py
class ModelName(models.model):
....
qr_code = models.ImageField(upload_to='qr_codes', blank=True)
...
def save(self, *args, **kwargs):
qrcode_img = qrcode.make("FLAT50") # FLAT50 is offer name, you can set your model's any field name using self.field_name
canvas = Image.new('RGB', (290, 290), 'white')
canvas.paste(qrcode_img)
fname = f'qr_code-{self.coupon_code}.png'
buffer = BytesIO()
canvas.save(buffer,'PNG')
self.qr_code.save(fname, File(buffer), save=False)
canvas.close()
super().save(*args, **kwargs)
serializers.py
class QRCodeSerializer(serializers.ModelSerializer):
class Meta:
model = ModelName
fields = ['..','..','qr_code','..']
views.py
class QRCodeAPIView(APIView):
serializer_class = QRCodeSerializer
def post(self, request):
serializer = QRCodeSerializer(data=request.data, context={'request': request})
if serializer.is_valid():
serializer.save()
return Response({
'status' : True,
'message' : 'Success',
'Data' : serializer.data},
status=status.HTTP_201_CREATED)
else :
return Response({
'status' : False,
'message' : "Error"},
status = status.HTTP_400_BAD_REQUEST)
urls.py
url(r'^add_data', QRCodeAPIView.as_view(), name='Create Data And Get QR'),
response
{
"status": true,
"message": "Success",
"Data": {
"id": 1,
...
...
"qr_code": "http://192.168.1.24:8000/media/qr_codes/qr_code-FLAT50.png",
...
}
}