我正在尝试实现一个models.FileField(作为旁注模型.ImageField抱怨我没有Pillow,但是一旦解决这个问题我会尝试安装它)。当我使用MEDIA_ROOT并尝试从管理员上传文件时,我收到此错误:
/ admin / resume / project / 9 / change /
中的PermissionError[Errno 13]许可被拒绝:'/ resume'
请求方法:POST请求URL: http://127.0.0.1:8001/admin/resume/project/9/change/ Django版本: 2.0.3异常类型:PermissionError异常值:
[Errno 13]许可被拒绝:'/ resume'
例外位置: /home/kinkyboy/virtualenv/djangoresume/lib/python3.4/os.py in makedirs,第237行Python可执行文件: / home / kinkyboy / virtualenv / djangoresume / bin / python3 Python版本: 3.4.3 ..
这是代码的相关部分。
### project/settings.py
RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
DEBUG = RUNNING_DEVSERVER
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '/static')
]
MEDIA_ROOT = '/resume/'
MEDIA_URL = '/resume/'
### project/urls.py
..
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
..
### app/models.py
class Project(models.Model):
..
image = models.FileField(upload_to='img/',blank=True)
### app/index.html
<p>Use this below: {{proj.image.url}}</p>
<div class="item active" style="background-image: url('{% static '<use the image url>' %}');">
我的项目结构:
Project
├── project
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── __pycache__
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── resume
├── admin.py
├── apps.py
├── fixtures
├── __init__.py
├── migrations
├── models.py
├── __pycache__
├── static
│ └── resume
│ ├── img
│ ├── ...
├── templates
├── tests.py
└── views.py
编辑:这解决了我的问题
### project/settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, "resume/")
MEDIA_URL = '/' #this sets the relative path from /app for uploaded files
### app/models.py
image = models.FileField(upload_to='static/resume/img/',blank=True)
### app/index.html
<div class="item active" style="background-image: url('{{ proj.image.url }}');">
答案 0 :(得分:1)
根据您需要的documentation on image and file fields in the FAQ: