Django不提供用户在heroku上传的媒体文件

时间:2016-08-07 20:23:42

标签: django heroku

我已经尝试了一切,但不知怎的,我看不到用户上传的图片。我已经在heroku上部署了代码,每个静态文件都正在加载。用户甚至会纠正图像的路径,但不知何故服务器显示错误,找不到图像。

Settings.py
 # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
#STATICFILES_DIRS = (
#    os.path.join(PROJECT_ROOT, 'static'),
#)

STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)

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

Models.py
#this is for photos upload by user
class You(models.Model):
    user = models.ForeignKey(User,null=True)
    name=models.CharField(max_length=30,blank=True,default='pictures/videos')
    docfile = models.FileField(upload_to='documents/%Y/%m/%d', null=True,blank=True)

    def __unicode__(self):
        return self.user.username

#Views.py(To upload files)
@login_required
def upload(request):

    if request.method == 'POST':

        newdoc = You(docfile = request.FILES['file'],user=request.user)
        newdoc.save()
        msg='dee'
            # Redirect to the document list after POST
        return HttpResponse(json.dumps({'message': msg}))

    else:
        form = DocumentForm()



    # Render list page with the documents and the form
    return render(request,'mat_upload.html',{'form':form})

Template(gallery.html)
{% for document in documents %}
<img class="img-responsive" src="{{MEDIA_URL}}/media/{{ document.docfile }}" alt="hiiii" style="max-width: 100%;
    height: 250px;" />
{% endfor %}

@login_required
def gallery(request):
    documents =  You.objects.filter(user=request.user)

    return render(request,'gallery.html',{'documents': documents,})
Urls.py
from django.conf.urls import include, url

from django.contrib import admin

from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import RedirectView
admin.autodiscover()

import harpoons.views


urlpatterns = [

    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('harp.urls')),
    url(r'^password_reset_recover/', include('password_reset.urls')),
    url(r'^accounts/', include('allauth.urls')),




]

1 个答案:

答案 0 :(得分:7)

您无法在Heroku上本地保存用户上传的文件。文件系统是短暂的,并且不会在dyno重启或者并发dynos之间持续存在。你需要将它们上传到更永久的地方;一个受欢迎的选择是亚马逊S3,并且有很多库会为你做这件事。