简体   繁体   中英

Want to save image URL in Python Django

This is my 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. 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. So it can not be an image_filed in the Django model it has to be a string.

Try changing the models.CharField in to a 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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