将类变量从Models.py传递到另一个.py文件进行处理

时间:2019-05-22 03:04:13

标签: django python-3.x django-models python-imaging-library

注意:我是django / python初学者

我目前在models.py中有一个User类,该类允许用户将图像上传到我的应用程序。允许上载的表单和模板对此提供了支持。这部分工作正常。问题是我正在模型中的文件字段中接收图像,但是我需要将此图像放入我的EnhanceImage.py文件中。到达那里后,我可以使用此脚本中的代码对其进行处理,以使用Pillow创建增强版本。

我应该如何设置与现在不同的设置?我的目标是将User类中的图像变量添加到EnhanceImage.py文件中以进行增强。我想将其放入EnhanceImage.py文件的UserUploadedImage变量中

我已经尝试了几乎所有可以在网上找到的将变量传递给新文件的解决方案。

Models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from stdimage.models import StdImageField


class User(models.Model):
    name = models.CharField(max_length=100)
    content = models.CharField(max_length=50, default='something')
    email = models.EmailField(blank=True)
    password = models.CharField(max_length=50)
    image = StdImageField(upload_to='images/', variations={'thumbnail': {'width': 640, 'height': 480}}, default='default.jpg')

    def __str__(self):
        return self.name

ImageEnhance.py

此文件的目标是获取UserUploadedImage并使用枕头覆盖内容。

from PIL import Image, ImageEnhance, ImageFont, ImageDraw

UserUploadedImage = I need the user uploaded image here!

foreground = Image.open("path/to/Image_to_overlay.jpg")

draw = ImageDraw.Draw(UserUploadedImage)

draw.rectangle([(-11, 420), (640, 515)], fill=(255,255,255), outline=(0,0,0))

UserUploadedImage.paste(foreground, (300, 385), foreground)
...
#more code below that isn't important for my question

Forms.py

from django.forms import ModelForm
from django import forms
from .models import User

class UserForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ['name', 'email', 'content', 'image']

Views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import User
from django.views.generic import ListView, CreateView # new
from django.urls import reverse_lazy #new
from .forms import UserForm # new


def home(request):
    context = {
        'users': User.objects.all()
    }
    return render(request, 'main/home.html', context)


class CreateUploadView(CreateView): # new
    model = User
    form_class = UserForm
    template_name = 'main/photoupload.html'
    success_url = reverse_lazy('home')

0 个答案:

没有答案