我正在尝试通过Ajax上传图像。图像可以很好地上传,但会在MEDIA_ROOT
值和upload_to
的{{1}}参数之间的“无”文件夹中传送。
我当前的设置如下:
ImageField
在我的应用程序的models.py中:
MEDIA_ROOT = (os.path.join(BASE_DIR, 'static', 'media'))
和
image = models.ImageField(blank=True, null=True, upload_to=get_image_path)
当我上传图片时,它会转到def get_image_path(instance, filename):
return os.path.join(connection.tenant.schema_name, 'img', 'devices', filename)
,而不是static/media/None/(tenant.schema_name)/img/devices
(在图片中,static/media/(tenant.schema_name)/img/devices
是“ ars”)
表格如下:
tenant.schema_name
保存段:
class DeviceForm(ModelForm):
class Meta:
model = Device
fields = ['name', 'model', 'serial', 'location', 'note', 'image', 'page', 'address']
是否缺少我的配置?任何帮助将不胜感激
编辑:以下是整个 if request.method == 'POST':
post_data = request.POST.dict()
form = DeviceForm(post_data, request.FILES)
if not form.is_valid():
return JsonResponse({"message": "Form is invalid"}, status=400)
obj = form.save()
return JsonResponse(obj.to_dict(), safe=False)
:
settings.py
我使用了以下答案建议的配置,但是在import os
from django.utils.translation import ugettext_lazy
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = (key)
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
if DEBUG:
ALLOWED_HOSTS = ['*'] # Allow any host during debug mode
else:
ALLOWED_HOSTS = []
# Application definition
SHARED_APPS = [
'tenant_schemas',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 'cloud_admin',
'cloud_core',
]
TENANT_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'cloud_core.users',
'cloud_data',
'cloud_apps.dashboard',
'cloud_apps.device',
'cloud_apps.device_pages.kr',
# 'cloud_apps',
]
INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'ArsCloud.middleware.TenantSelectionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'ArsCloud.middleware.LoginRequiredMiddleware',
]
ROOT_URLCONF = 'ArsCloud.urls_public'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, "templates"),
os.path.join(BASE_DIR, "cloud_core", "templates"),
os.path.join(BASE_DIR, "cloud_admin", "templates"),
os.path.join(BASE_DIR, "cloud_data", "templates"),
os.path.join(BASE_DIR, "cloud_apps", "dashboard", "templates"),
os.path.join(BASE_DIR, "cloud_apps", "device", "templates"),
os.path.join(BASE_DIR, "cloud_apps", "device-pages", "templates"),
os.path.join(BASE_DIR, "cloud_apps", "device-pages", "kr", "templates"),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'cloud_core.context_processors.tenant'
],
},
},
]
WSGI_APPLICATION = 'ArsCloud.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
(database)
}
DATABASE_ROUTERS = (
'tenant_schemas.routers.TenantSyncRouter',
)
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Language support
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale/')
]
LANGUAGES = (
(u'ja', ugettext_lazy('Japanese')),
(u'en', ugettext_lazy('English'))
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
# STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static"),
# ]
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static', 'static_dirs'),
)
MEDIA_ROOT = (os.path.join(BASE_DIR, 'static', 'media'))
MEDIA_URL = '/static/media/'
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGIN_EXEMPT_URLS = [
"upload_device_data"
]
TENANT_MODEL = 'cloud_core.Tenant'
DEFAULT_FILE_STORAGE = 'tenant_schemas.storage.TenantFileSystemStorage'
PUBLIC_SCHEMA_URLCONF = 'ArsCloud.urls_public'
ADMIN_SCHEMA_URLCONF = 'ArsCloud.urls_admin'
TENANT_SCHEMA_URLCONF = 'ArsCloud.urls_tenant'
ARSUSER_SCHEMA = "ars"
POST_TOKEN_KEY = {'key': (key), 'iv': "Salt for hashing"}
DUMMY_DB_PATH = os.path.join(BASE_DIR, 'falsedb')
DUMMY_DB_FILE = os.path.join(DUMMY_DB_PATH, 'config.json')
和MEDIA_ROOT
参数之间我仍然有一个“ None”文件夹
答案 0 :(得分:1)
您应该在settings.py文件中定义媒体目录。您要从网站上载的图像和文件,存储在媒体目录中。
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static', 'static_dirs'),
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
MEDIA_URL = '/media/'
您的项目中需要静态目录。树目录如下:
static -
|-static_root
|-static_dirs
|-media
请创建以下4个目录: static , static_root , static_dirs , media
答案 1 :(得分:-1)
在整个项目目录中的同一级别(与manage.py相同的级别)中,将媒体和静态文件创建为文件夹,然后尝试:
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
media和static文件夹用于两个完全不同的事物,并且绝对不能将media嵌套在static中。媒体文件夹用于存储用户上传的内容,您定义的MEDIA_ROOT
是用户上传的内容上传到的位置(通过upload_to=.....
设置了MEDIA_ROOT中的子文件夹)。静态文件夹和(和子文件夹)包含您定义为网站一部分的内容(例如css,js)。
我也会做一个小的更改(不需要request.POST.dict()
):
if request.method == 'POST':
form = DeviceForm(request.POST, request.FILES)