我正在尝试将图像保存到媒体根文件夹,该文件夹已在媒体文件夹中命名为图片。这是我的代码,我希望每当我的函数制作屏幕截图时,都应将屏幕截图保存在媒体根文件夹中。
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404,render,redirect
import time
import random
from django.db import models
import pyautogui
import sys
from shots.models import pictures
from .models import pictures
from shots.forms.forms import DocumentForm
def button(request):
import pyautogui
myScreenshot = pyautogui.screenshot()
storage=pictures.pictures2
myScreenshot.save(storage)
return render(request,'index.html')
def output(request):
return HttpResponse("""Hello, world. You're at the polls index.
your Screenshot should start now""")
这是我的 models.py :
from django.db import models
import random
class pictures(models.Model):
pub_date = models.DateTimeField('date published')
pictures2 = models.ImageField(upload_to='pictures')
答案 0 :(得分:0)
您会发现this answer有帮助。
FileField
和ImageField
的文件是相对于settings.MEDIA_ROOT
上传的,并且应该可以通过附加到settings.MEDIA_URL
的相同相对文件名来访问。
话虽如此,如果您命名settings.MEDIA_ROOT = 'pictures'
并告诉模型到upload_to='pictures'
,那么django上载的文件最终将位于:
**/pictures/pictures/myScreenshot.png**
import pyautogui
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from .models import pictures
def button(request):
myScreenshot = pyautogui.screenshot()
"""
The path and filename are relative o where you execute this script.
"""
filename = settings.MEDIA_ROOT+'pictures/myScreenshot.png'
myScreenshot.save(filename)
return render(request,'index.html')
您的models.py
:
from django.db import models
import random
class pictures(models.Model):
pub_date = models.DateTimeField('date published')
pictures2 = models.ImageField(upload_to='pictures')