简体   繁体   English

想要在 Python Django 中保存图像 URL

[英]Want to save image URL in Python Django

This is my model这是我的 model

class MenuOptions(models.Model):
    name = models.CharField(max_length=500, null=False)
    description = models.CharField(max_length=500, null=True)
    image_url = models.CharField(max_length=1000, null=True)

This is my form这是我的表格

class MenuOptionsForm(forms.ModelForm):
    class Meta:
        model = MenuOptions
        fields = ['name', 'description']

And this is my view这是我的观点

        if request.method == 'POST':
            form = MenuOptionsForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('menu-options')

        else:
            form = MenuOptionsForm()

I want to have the custom image field using Django form so that I can use that in the template to upload the image on S3/Google storage.我想拥有使用 Django 表单的自定义图像字段,以便我可以在模板中使用它来将图像上传到 S3/Google 存储。 I know how to upload the image on the bucket, and after uploading the image to the storage I want to save only the image_url to the DB, not the image.我知道如何将图像上传到存储桶上,并且在将图像上传到存储后,我只想将 image_url 保存到数据库,而不是图像。 So it can not be an image_filed in the Django model it has to be a string.所以它不能是 Django model 中的 image_filed 它必须是一个字符串。

Try changing the models.CharField in to a models.URLField尝试将models.CharField更改为models.URLField

#settings.py

import os

AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_REGION = os.environ.get('AWS_DEFAULT_REGION')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_BUCKET')
AWS_QUERYSTRING_AUTH = False
AWS_DEFAULT_ACL = None

# models.py

from django_s3_storage.storage import S3Storage
from app.settings import AWS_STORAGE_BUCKET_NAME

storage = S3Storage(aws_s3_bucket_name=AWS_STORAGE_BUCKET_NAME)

class MenuOptions(models.Model):
    name = models.CharField(max_length=500, null=False)
    description = models.CharField(max_length=500, null=True)
    image = models.ImageField(max_length=1000, null=True,storage=storage)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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