How to manage media files on Windows? - django

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.

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

Related

Django not rendering static image files localted in MEDIA directory

im relatively new to Django. I have an app where I specify MEDIA_URL and MEDIA_ROOT in settings.py file in project root. My pared down project structure looks like this:
/
../files
../files/media
../files/media/logo.png
../solid/settings.py
../solid/urls.py
/web/templates (contains all my HTML)
inside settings I have
MEDIA_ROOT = BASE_DIR / 'files'
MEDIA_URL = '/media/'
DEFAULT_FILE_STORAGE = BASE_DIR /'files'
in my template web/template/index.html I'm trying to reference it
<img src="{{% MEDIA_ROOT %}}/images/ourlogo.png" class="" alt="Logo" height="40">
In solid/urls.py I have:
urlpatterns = [
path('admin/', admin.site.urls),
path('',web_views.index,name="index"),
######################################################
path('login/',login_page,name="login"),
path('logout/',log_out,name="logot"),
path('register/',register,name="register"),
#######################################################
path('upload/',web_views.upload,name="upload"),
path('list/',web_views.list_uploads,name="list"),
path('details/<int:oid>', web_views.view_download,name='view_download'),
path('download/<str:filename>', web_views.download_file,name='download_file'),
#######################################################
path('paypal/', include("paypal.standard.ipn.urls")),
path('payment/',web_views.upgrade,name="payment"),
path('paypal-cancel/', PaypalCancelView.as_view(), name='paypal-cancel'),
path('paypal-return/', PaypalReturnView.as_view(), name='paypal-return'),
#######################################################
]+static('s/',document_root=settings.MEDIA_ROOT)
the image is not rendering.
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS =[
os.path.join(BASE_DIR,'project_name/static')
]
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
project_name/urls.py
add this two lines with urlspatterns
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
if want to get the image from database
<img src="{{ img.photo_2.url }}" alt="" class="img-fluid">
here "img" is the dictionary key name. photo_2 is the database field name. and to show the image you have put the .url after that.
static image
<link href="{% static 'img/favicon.png' %}" rel="icon">

Django image not showing up in template (not URLs issue)

I've added the neccessary elements to the URLs.py.
The image is NOT stored in the database, it's just a background image.
The source of the img folder is 'storiesapp/static/storiesapp/img'
Settings.py (i've been trying different things as shown)
STATIC_URL = '/storiesapp/static/storiesapp/'
STATIC_ROOT = os.path.join(BASE_DIR, "/static/")
STATICFILES_DIRS = [
"/storiesapp/static/storiesapp/img/",
"/static/storiesapp/img/",
"/storiesapp/img/",
"/img/",
]
STATICFILES_FINDERS =[
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# full path where all images are stored - os.path will create the directory regardless of the operating system
MEDIA_URL = '/media/'
#
.URLs.py
from django.conf import settings
from django.conf.urls.static import static
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
.
I'm trying all of the following
<link rel="apple-touch-icon" sizes="76x76" href="./assets/img/image.png">
<img src="static/storiesapp/img/image.png">
<img class='img-responsive' src="{{ MEDIA.URL }}{{ image.png }}" />
The answer is "<img src="{% static 'storiesapp/img/image.png' %}"/>".
It was the wrong syntax.
I was able to come to this solution because I realized that my CSS templates, which I can see are working, are also using the static folder so it couldn't be a problem with the way anything is set up.

Django doesn't load images from media

I've set things for the setting and the URLs as follow but it doesn't load the images from media directory:
settings.py:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, '/media/')
urls.py:
urlpatterns = [
path('create/', views.image_create, name='create'),
path('detail/<int:id>/<slug:slug>/', views.image_detail, name='detail'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
this is the link generated for the page: https://127.0.0.1:8000/images/detail/1/django-and-duke/
and the link for the image: https://127.0.0.1:8000/media/images/2020/08/02/django-and-duke.jpg
I have another app named accounts and if I add the base URL of account to the first of this media URLs it works! but I know they are separated from each other.
if you need other parts of code please tell me.
Remove the slashes in os.path.join(BASE_DIR, '/media/')
If any argument to os.path.join begins with a slash / it will overwrite all previous arguments. You're currently setting MEDIA_ROOT to be /media/
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Static url goes after the regular page url

My static files only load on index page, but when navigating to another page like: examle_url/page, it returns a 404 error since it loads it like that: http://127.0.0.1:8000/categories/default/static/js/main.js, see the static loads after page
settings.py
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root/')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '/static/base'),
)
urls.py "all my urls are in main directory and then i import views from apps"
urlpatterns = [
path('admin/', admin.site.urls),
path('profile/', profile, name="profile"),
path('', index, name="index"),
path('category/', category, name="category"),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If it matters my load static files are all in theme.html file and is then extended in all other html files.
Any help will be greatly appreciated, thanks in advance!
You should prepend the STATIC_URL setting [Django-doc] with a slash:
# settings.py
# …
# with a leading slash
STATIC_URL = '/static/'
# …
If you do not do that, then the url will look like static/js/main.js. If the path does not start with a slash, then that is relative to path the current URL, and thus if the page is /categories/default, it will look at /categories/default/static/js/main.js.

serving static files django development

I know a million people have asked this, and I've read and read but still cannot get this to work (I think that says something about the documentation cough cough).
ONE. CSS:
Here are my settings:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'))
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static")
STATIC_ROOT = '/static/'
STATIC_URL = '/static/'
also relevant:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'blog',
)
My templates are serving up just fine, while my css is not. its located in static/originaltheme.css
I've tried both:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}originaltheme.css">
and
<link rel="stylesheet" type="text/css" href="/static/originaltheme.css">
TWO. Also, is there a way to get hardcoded urls to display? for example, lets say the content of a blog post has a hardcoded url to /static/img1.jpg, how can I do that? All of the documention points to {{ static_url }}, but im guessing that that wont get evaluated when returned from a text field of a database...
is there something to do with my urls?
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'nickswebsite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', 'blog.views.index'),
url(r'^blog/view/(?P<slug>[^\.]+)',
'blog.views.view_post',
name='view_blog_post'),
url(r'^blog/category/(?P<slug>[^\.]+)',
'blog.views.view_category',
name='view_blog_category'),
url(r'^admin/', include(admin.site.urls)),
)
EDIT:
I tried doing this is in the urls:
urlpatterns = patterns('',
url(r'^$', 'blog.views.index'),
url(r'^blog/view/(?P<slug>[^\.]+)',
'blog.views.view_post',
name='view_blog_post'),
url(r'^blog/category/(?P<slug>[^\.]+)',
'blog.views.view_category',
name='view_blog_category'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=setting.STATIC_ROOT)
urlpatterns += staticfiles_urlpatterns()
but im getting a "settings" undefined error. I tried to import settings and im still getting an error.
Edit
Okay, the documentation for serving static off development server is HORRIBLE. Whoever wrote it should really rewrite it. This guy is the only person in the entire world who seems to explain this clearly: http://agiliq.com/blog/2013/03/serving-static-files-in-django/#servee
You DO need these in the settings.py (why arent they included in the initial installaion??? what genius...):
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
You do NOT need these:
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static")
STATIC_ROOT = '/static/'
You do NOT need:
manage.py collectstatic
http://agiliq.com/blog/2013/03/serving-static-files-in-django/#servee:
Points to be noted
We did not make any changes to any of the static settings provided by Django to us. We left the static settings as they were in default settings.py provided by Django.
You don't need any change in your urls.py for serving your static files in development. You don't need to add staticfiles_urlpatterns(). Many a times, I got confused with this.
You do not need python manage.py collectstatic for serving static files in development.
I also fought against this particular problem. And finally came up with this blog post
Actually you don't need collectstatic , STATICFILES_FINDER and django.contrib.staticfiles. They are all related. Read the blog post
I added these lines to the bottom of my url.py:
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
And this in my settings.py:
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Did you use:
./manage.py collectstatic
Also your STATIC_ROOT should be absolute path to the directory static files should be collected to:
STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, "static"))
This is what I did for Django 2.0 using the above answers. So you'll want a system that makes deployment easy.
settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Serve Static in Development
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATICFILES_DIRS = [os.path.join(BASE_DIR, "appName/static/appName")]
# Serve static in production
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then made a directory ~/documentRoot/appName/static/appName/ and copied my png into it. Then in my template:
<head>
<bootstrap,jquery,etc...>
{% load staticfiles %}
</head>
<body>
<img class="mb-4" src="{% static "myImage.png" %}" alt="" width="72" height="72">
</body>
Then when you want to deploy you just run collectstatic and they'll be served in one spot. Each time you add an app, add to that list of static dirs.