我如何在django中存储我在枕头上编辑的图片并上传给用户



我正试图制作一个可以在贺卡中打印用户姓名的网站,但我遇到了问题

我正试图将图片保存在我的数据库中,但当你在底部中看到我的代码时,我看不到它保存在数据库中

这是我的观点.py

from django.shortcuts import render
from .models import Name
from django.shortcuts import redirect
from PIL import Image,ImageDraw , ImageFont
# Create your views here.
def Home(request):
name_input = str(request.POST.get('user_name'))
img = Image.open("C:\Users\kmm\Desktop\my_django_stuff\Eid_G\files\covers\mypic.png")
d = ImageDraw.Draw(img)
fnt = ImageFont.truetype('C:\Users\kmm\Desktop\fonts\staticCairo-Bold.ttf',40)
message = name_input
d.text((540,1020),message, font=fnt, fill=(237, 185, 117),anchor="ms")
saved_i = img.save(name_input+'.png')
save_in_model = Name(massenger_name=name_input,image=saved_i)
save_in_model.save()
return render(request , 'index.html')

这是我的模型.py

from django.db import models
# Create your models here.
class Name(models.Model):
massenger_name = models.CharField(max_length=255,null=True,blank=True)
action_time = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='images/',blank=True,null=True)
def __str__(self):
return str(self.massenger_name)

这是我的index.html

<!DOCTYPE html>
<html lang="en" dir="rtl">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
{% load static %}
<link rel="stylesheet" href="{% static 'CSS/style.css' %}">
</head>
<body>
<div id="form">
<form class="row" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="">
<input type="textarea" class="form-control" placeholder="أكتب أسمك (مثلا/أخوكم عبدالله العتيبي)" id="text_name" name="user_name" required>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary mb-3" id="button">حمل الصورة</button>
</div>
</form>
{{ Name.Image }}
</div>
</body>
</html>

您需要将文件名添加到

image = models.ImageField(upload_to='images/',blank=True,null=True)

像这段代码

def upload_file_name_path(instance, filename_ext):
ext = filename_ext.split('.')[-1]
return f'images/{URL_SAFE(instance.name)}-{randint(1000, 10000)}.{ext}'
class Name(models.Model):
massenger_name = models.CharField(max_length=255,null=True,blank=True)
action_time = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to=upload_file_name_path,blank=True,null=True)
def __str__(self):
return str(self.massenger_name)

相关内容

  • 没有找到相关文章

最新更新