Django-将图像作为 BLOB 上传到 MySQL 数据库

时间:2021-02-01 07:21:26

标签: python mysql django

我正在创建一个电子商店,我有一个管理仪表板,我可以在其中添加新产品到数据库中。目前我直接将产品图片存储为文件,phpmyadmin 正在将其转换为 BLOB。但这不是执行此操作的有效方法。所以我编写了一个 HTML 页面,我可以将图像发送到后端,然后将其上传到数据库。

我使用 Django Forms 注册一个新产品如下

Forms.py

class Upload_New_Product_Form(forms.Form):
    product_id = forms.IntegerField()
    name = forms.CharField(max_length=50)
    price = forms.DecimalField(max_digits=7, decimal_places=2)
    image = forms.ImageField()

products.html

<form method="POST" action="{% url 'upload_new_product' %}">
   {% csrf_token %}
   <div class="input-group">
     {{product_form}}
     </div>
     <br>
      <button type="submit" class="makeChangebtn btn-primary">Submit changes</button>
 </form>

views.py

def Upload_New_Product_View(request):
    if request.method == 'POST':

        _id = request.POST['product_id']
        name = request.POST['name']
        price = request.POST['price']
        image = request.POST['image']
        print(image)
        new_product = Product.objects.create(id=_id,name=name,price=price,image=image)
        new_product.save()

当我从 POST 请求在我的 views.py 中打印图像时,我只得到图像的名称。 检索图像然后将其转换为二进制以最终将其存储在数据库中的正确方法是什么?

0 个答案:

没有答案
相关问题