简体   繁体   中英

Image watermark in model view set in Django RestFrameWork

I am developing a simple django rest framework application using model viewset. First i input image, name and other details and save to postgresql as well as update in google sheets. So i am trying to put watermark of input image in model view set without using any html file. I have gone through watermark package in python but can't grasp it. So can anyone help me in adding watermark of input image using model view set .

This is my views.py

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser
from .models import Article
from .serializers import ArticleSerializer
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework import mixins
from rest_framework.authentication import TokenAuthentication, BasicAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from django.shortcuts import get_object_or_404
# Create your views here.
from PIL import Image
from rest_framework.decorators import action
from rest_framework.response import Response

import gspread
from oauth2client.service_account import ServiceAccountCredentials
from django.http import HttpResponse, Http404

scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('Review-4016be63eaa5.json', scope)
client = gspread.authorize(creds)

# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("review").sheet1





class ArticleViewSet(viewsets.ModelViewSet):
    serializer_class = ArticleSerializer
    queryset = Article.objects.all()

    def create(self, request):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            #print(serializer.data)
            serializer.save()



            print(serializer.data)

            t = list()
            for k, v in serializer.data.items():
                t.append(v)
            print(t)
            list_of_hashes = sheet.get_all_values()
            print(list_of_hashes)
            sheet.insert_row(t, len(list_of_hashes)+1)

            #Account.objects.create_user(**serializer.validated_data)
            return Response(
                serializer.data, status=status.HTTP_201_CREATED
            )

        return Response({
            'status': 'Bad request',
            'message': 'Account could not be created with received data.'
        }, status=status.HTTP_400_BAD_REQUEST)

def update(self, request, pk=None):
    article = Article.objects.get(pk=pk)
    serializer = ArticleSerializer(article, data=request.data)
    if serializer.is_valid():
        serializer.save()
        print(serializer.data)
        c=sheet.col_values(1)
        t = list()
        for k, v in serializer.data.items():
            t.append(v)
        rownum=1
        print(c)
        print(t)
        r=str(t[0])
        if r in c:
            print("inside r", r)
            rownum = c.index(r)+1

        sheet.delete_rows(rownum)
        sheet.insert_row(t, rownum)

        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def destroy(self, request, *args, **kwargs):
    try:
        instance = self.get_object()
        print(instance.id)
        print(type(instance.id))
        c = sheet.col_values(1)

        rownum = 2
        print(c)
        print(type(instance))
        r=str(instance.id)
        if r in c:
            print("inside r", r)
            rownum = c.index(r) + 1

            sheet.delete_rows(rownum)

        self.perform_destroy(instance)
    except Http404:
        pass
    return Response(status=status.HTTP_204_NO_CONTENT)

This is my Models.py

from django.db import models

# Create your models here.

class Article(models.Model):
    name = models.CharField(max_length=100)
    gender = models.CharField(max_length=100)
    age = models.IntegerField()
    image = models.ImageField()
    date=models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.id)


You should try Image.paste() method

image = Image.open('image.jpg')
watermark = Image.open('watermark.png')
image.paste(watermark, (x, y), watermark)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM