gpt4 book ai didi

python - 如何为django应用程序设置图片上传根目录

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:00 24 4
gpt4 key购买 nike

我无法为上传的图片设置根文件夹。上传图片在名为 api 的 django 应用程序中。

View 在图像上返回此链接: http://www.example.com/media/4a273bdf-564d-4dec-b657-43db27f04042.jpeg

但是,当我继续该链接时,出现错误,因为图像不在那里。

我在settings.py中设置:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAdminUser',
],
'PAGE_SIZE': 1
}

MEDIA_ROOT = os.path.join(BASE_DIR,STATIC_ROOT,'media')
MEDIA_URL = '/media/'

我在 api/models.py 中写了这个:

from django.db import models
import uuid

def scramble_uploaded_filename(instance, filename):
extension = filename.split(".")[-1]
return "{}.{}".format(uuid.uuid4(), extension)

def filename(instance, filename):
return filename

# Create your models here.
class UploadImage(models.Model):
image = models.ImageField("Uploaded image",upload_to=scramble_uploaded_filename)
captcha_type = models.IntegerField("Image type")

View .py

from rest_framework import viewsets
from api.models import UploadImage
from api.serializers import UploadedImageSerializer
from rest_framework import authentication, permissions
from rest_framework.parsers import MultiPartParser,FormParser
import MySQLdb

class FileUploadViewSet(viewsets.ModelViewSet):
#create queryset view
permission_classes = (permissions.IsAuthenticated,)
queryset = UploadImage.objects.filter(id=1,user='auth.User')
serializer_class = UploadedImageSerializer
parser_classes = (MultiPartParser, FormParser,)

序列化器.py

from rest_framework import serializers
from api.models import UploadImage # Import our UploadedImage model

class UploadedImageSerializer(serializers.ModelSerializer):
# current_user = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = UploadImage
fields = ('id', 'image','captcha_type','created','user','result') #

有什么想法吗?

最佳答案

嗨,m8,你所要做的就是编辑 urls.py 添加这几行,它应该可以工作。

from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
url(r'^admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

关于python - 如何为django应用程序设置图片上传根目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45016199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com