2017-09-04 90 views
0

心中已經樹立了ImageField的爲我這樣的車型之一:Django的媒體

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') 

,這是我對媒體的根和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

當DEBUG是假的,Django的再處理媒體文件和靜態文件,您可以通過Apache或別的東西 – Ykh

+0

@Ykh可以根據需要服務器的媒體文件和靜態文件你給我一個提示。我正在使用共享主機,並且是全新的服務器資料。 –

+0

你想把你的項目投入生產嗎?其實@ – Ykh

回答

0
<VirtualHost *:8000> 
    ServerAdmin [email protected] 
    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>