我以这种方式为我的一个模特设置了一个Imagefield:
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
points = models.IntegerField(default=0)
avatar = models.ImageField(upload_to=user_directory_path, default='/defaultavatar.jpg')
这是我对media root和url的设置:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT= os.path.join(BASE_DIR,'site_media/media/')
MEDIA_URL='/media/'
STATIC_ROOT=os.path.join(BASE_DIR,'site_media/static/')
STATIC_URL = '/static/'
STATICFILES_DIRS =[
os.path.join(BASE_DIR,'static')
]
当我创建个人资料时,我可以访问defalutavatar.jpg
但是当我通过管理页面上传另一个图片并尝试打开图片时,它会显示404 Not Found
(尽管图像是在MEDIA_ROOT中创建的)
DEBUG是假的(如果你想建议urlpattern += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
)
答案 0 :(得分:0)
<VirtualHost *:8000>
ServerAdmin ykh@dreamgo.tech
ServerName 192.168.1.102
DocumentRoot /home/dreamgo/dreamgo_official_site
Alias /static /home/dreamgo/dreamgo_official_site/static
<Directory /home/dreamgo/dreamgo_official_site/static>
Require all granted
</Directory>
Alias /media /home/dreamgo/dreamgo_official_site/media
<Directory /home/dreamgo/dreamgo_official_site/media>
Require all granted
</Directory>
<Directory /home/dreamgo/dreamgo_official_site/dreamgo_official_site>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess 192.168.1.102 python-path=/home/dreamgo/dreamgo_official_site python-home=/home/dreamgo/dreamgo_official_site/environment
WSGIProcessGroup 192.168.1.102
WSGIScriptAlias / /home/dreamgo/dreamgo_official_site/dreamgo_official_site/wsgi.py
</VirtualHost>