How to manage media files on Windows?

206 views Asked by At

I want to get media files for Django when developing application. But they just don't set up. This is my settings:

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR

STATICFILES_DIRS = (
    STATIC_ROOT + '\\projectpackage\\static\\',
)

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR + '\\projectpackage\\media\\'

Templatetag:

<img class="img-responsive" src="{{ project.image.url }}" alt="">

Urls:

urlpatterns = [    
    url(r'^profile/', include(profile.urls)),
    url(r'', include(authentication.urls)),
    url(r'^project/', include(project.urls)),
    url(r'^admin/', include(admin.site.urls)),

    url(r'^', 'views.index', name='index'),


    url(r'^markdown/', include('django_bootstrap_markdown.urls')),

]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(STATIC_URL, document_root=STATIC_ROOT)
urlpatterns += static(MEDIA_URL, document_root=MEDIA_ROOT)

I can't see my mistake, because I've tried every other advices in other questions. And everything works bizzare. Static files are running good, media uploading to media/prj_img, but when I try to show image at template I've got such strange result:

<img class="img-responsive" src="/media/C%3A/Development/projectdirectory/projectpackage/media/prj_img/wallhaven-131_od9FWLX.jpg" alt="">

How could I fix this media error? This is strange, because everything looks right. Why there are full path in url?

Edit:

BASE_DIR

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

Also I've figured out that I've got wrong upload_to and changed it to prj_img. Now I've got following link:

<img class="img-responsive" src="/media/prj_img/wallhaven-24700.jpg" alt="">

But still it's not displating.

1

There are 1 answers

1
sobolevn On BEST ANSWER

I have a lot of comments on your code.

STATIC_ROOT location is not appropriate. With your settings collectstatic command will put everything in your project's directory. Change it like so:

STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')

But take care, that this folder is accessable (both permissions and django-settings) in production.

Use os.path.join to join folders:

STATICFILES_DIRS = (
    os.path.join(STATIC_ROOT, 'projectpackage', 'static')
)

This url pattern must be the last one and contain $:

url(r'^$', views.index, name='index'), # do not pass strings

These two url patterns do the same (docs):

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(STATIC_URL, document_root=STATIC_ROOT)

Moreover, you do not need them. Just ensure, that INSTALLED_APPS setting contains 'django.contrib.staticfiles'.