Im having trouble getting Django to grab my static files
Relevant Model:
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', auto_now_add=True)
image = models.FileField(upload_to='static/')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published Recently?'
settings.py:
STATIC_ROOT = '/Users/austinbailey/ENV/mysite/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'media'),
]
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
template tag:
<img src="{{ poll.image }}" alt="img">
what it shows as with inspect element:
<img src="media/android_pumpkins_fall_1.jpg" alt="img">
this is actually the correct path to the file, but for some reason it only displays the broken image file. I've been working on this for a while now, and I'm stumped. Thanks in advance!
------------------ UPDATE -------------------
I've messed with the structure and the settings in settings.py since the initial post in an attempt to resolve the issue on my own, but here is the structure as of now.
Project Structure:
-mysite (root)
-mysite
__init__.py
settings.py
urls.py
wsgi.py
-polls (app)
__init__.py
urls.py
models.py
views.py
forms.py
admin.py
-templates (html for admin site)
-migrations
-templates
-admin
base_site.html
-static
-media
android_computer_back.jpg
-2014
-04
-13
android_rose.jpg
-14
android_computer_android_studio.jpg
-static
-static-only
-admin ( base stuff for admin site )
-css
-js
-img
manage.py
db.sqlite3
Relevant Settings from settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(os.path.join(BASE_DIR), 'static', 'static-only')
STATIC_URL = '/static/'
MEDIA_URL = 'static/media/'
MEDIA_ROOT = os.path.join(os.path.join(BASE_DIR), 'static', 'media')
STATICFILES_DIRS = (
os.path.join(os.path.join(BASE_DIR), 'static', 'static'),
)
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
Updated Model:
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', auto_now_add=True)
image = models.ImageField(upload_to='%Y/%m/%d/')
Most Recent Image Tag:
<img src="{{ poll.image.url }}" alt="img" />
Which shows:
<img src="static/media/2014/04/14/android_computer_android_studio.jpg" alt="img" />
Database Settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
What is going on with your settings? They should look like this:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static-only')
STATIC_URL = '/static'
MEDIA_URL = '/static/media'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static', 'static'),
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
There is no need to call os functions twice on everything.
Okay. Please use the settings below:
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
MEDIA_ROOT = ''
MEDIA_URL = '/media/'
And call the image field name in templates like so:
<img src="{{ model_name.img_field_name.url }}" alt="I will work" />
What I've given you above will make you see uploaded files by user whiles working locally. Should you try deploying on in the cloud, somewhere like Heroku, the collectstatic and the bla bla bla things will be done for you automatically.
Lemme know if it doesn't work. Its just an exact snippet found in my current project.
So, an example will be like so:
<img src="{{ category.photo.url }}" alt="I will work" />
Okay so I figured out what the problem was and it of course turned out to be a very clumsy mistake.
I had put my urlpatterns for the media and static files in the wrong spot.
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
They were under the app's urls.py instead of the project's urls.py where the actual folder for the media and static files is located. With this change, the images were being displayed and everything is good now.
Thanks for all the help
Related
I have an issue with django. I recently bought an instance of a shared server and I wanted to move my django website from AWS to this server (which use Cpanel). All worked fine with AWS but when I switched to Cpanel all statics files were missing.
this is my settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = "/media/"
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
my project structure:
my_project
|-app/
|-...
|-views.py
|-db.sqlite3
|-manage.py
|-media/
|-my_project/
|-...
|-settings.py
|-static/
|-main_page/
|-js/
|-my-script.js
I add static files like this:
{% load static %}
<script src="{% static 'main_page/js/my-script.js' %}"></script>
This is the error:
GET http://my.domain.com/static/main_page/js/my-script.js net::ERR_ABORTED 404 (Not Found)
When I go to the URL of the file it understands it like one of my URLs:
I hope you will help me to solve this issue ;)
thanks.
you need to add the static & media files config in the urls.py , like this
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
the django docs : https://docs.djangoproject.com/en/3.1/howto/static-files/
I am using Django 3, and I have tried every solution available on the internet, but none of them worked for me.
When I set DEBUG=False, I am unable to display an image on the HTML page.
Here are my settings
-root_app
--main_app
---settings.py
---asgi.py
---urls.py
---wsgi.py
--sub_app
---admin.py
---urls.py
---views.py
---static
----style.css
---templates
----home.html
---media
----images
media path in settings.py
MEDIA_ROOT = os.path.join(BASE_DIR,'sub_app','media')
MEDIA_URL = '/media/'
Here what I have done to resolve it
add context_processor
django.template.context_processors.media'
add +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in url_patterns of urls.py of sub_app
I changed static storage to STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage', otherwise I got 500 error. Check this comment
But still, I am unable to display the image at home.html page.
When I click on image source using inspect element, I got this
/media/images/img.png
These settings resolved the issue
Media Path
MEDIA_ROOT = os.path.join(BASE_DIR, 'sub_app','media')
MEDIA_URL = '/media/'
Static Path
STATIC_ROOT = os.path.join(BASE_DIR, 'sub_app','static')
STATIC_URL = '/static/
Adding re_path line in urls.py of main_app
from django.conf.urls.static import static
from django.views.static import serve
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('sub_app.urls')),
re_path(r'^media/(?P<path>.*)$', serve, kwargs={'document_root': settings.MEDIA_ROOT})
]
Change this
MEDIA_ROOT = os.path.join(BASE_DIR,'sub_app','media')
to
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
in settings.py and use
{{MEDIA_URL}}images/image.png
inside your template.
An edit to Dr. Abhishek's answer: yes, you need the MEDIA_ROOT setting, but you need to append it into the STATICFILES_DIRS list also, which will look something like this:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = [
# ...
os.path.join(BASE_DIR, 'media'),
]
When you load the image, use a soft-encoded path like this:
{% load static %}
<!-- remember to change the file name/type! -->
<img src="{% static 'images/image.jpg' %}" alt="Image">
I'm new to programming, I'm trying to put up a mp3 file and player on a django web page the player is showing but, the song is not playing.
**models.py**
from django.db import models
from django.contrib.auth.models import User
class Song(models.Model):
name = models.CharField(max_length=125)
audio_file = models.FileField('media/')
**audio.html**
<!DOCTYPE html>
<html>
<body>
<audio controls>
<source src="JesusChrist.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>
**media folder**
JesusChrist.mp3
**Settings.py**
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'firegod/static/media')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_URL = '/media/'
This video is a great reference, and should spell everything out. He shows where files go when they are uploaded and how to access them in the templates.
Another problem you have is this:
# Sets STATIC_ROOT
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Sets STATIC_URL
STATIC_URL = '/static/'
# Overwrites STATIC_ROOT
STATIC_ROOT = os.path.join(BASE_DIR, 'media')
# Overwrites STATIC_URL
STATIC_URL = '/media/'
I believe what you want is:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
and then you should be able to find your file at
src="media/audio.mp3". If you need to, print the url of the uploaded file so you know where to find it.
I am about to dive into this, so I might be a little off, though I know the video linked above was very beneficial.
FIXED
This was my solution, in the main programs urls.py I had to add these lines.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have an model called Item within there I have an image field. I added an new item with an image to the database and tried loading it inside of my index template. However I dont get an image when I look at the console it says ("WEBSITENAME/site_media/items/image.jpg 404 (Not Found)")
I think the problem lies within the settings.py file but I cant figure out what exactly I did wrong here.
index.html template
{% load static %}
<div class="item" style="background-image: url('{{ item.img.url }}')">`
Model.py
class Item(models.Model):
name = models.CharField(max_length=200)
img = models.ImageField(upload_to='items', default='', blank=True, null=True)
def __str__(self):
return "%s" % (self.name)
Views.py
def index(request):
latestItems = Item.objects.all().order_by('-id')[:3][::-1]
return render(request, 'webshop/index.html', {'latestItems' :latestItems})
settings.py
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'site_media/')
MEDIA_URL = 'site_media/'
In your settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'
and read this document
With the directory root structure that you have shown, I think the above setting should work. Have not tested it though. Let me know if it works.
you have:
upload_to='items'
but:
{{ item.img.url }}
should that be?
{{ items.img.url }}
in settings.py:
PROJECT_ROOT = os.path.abspath(os.path.dirname(__ file __))
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, "static"),
)
I have my media_root path set to
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
MEDIA_URL = 'media/'
with my project structured as so
Project_Name/
media/
profiles/
App_Name
when I try to reference the images in my profiles/ directory, I get 404 no resource found errors.
src="{{ MEDIA_URL }}{{ result.photo }}">
This resolves to http://127.0.0.1:8000/media/profiles/image1.jpg cannot be found. Am I missing absolute path, I am using DJango 1.4, I do not have the media root set in my urls.py but I didn't with my STATIC_URL definitions and I am able to find my static resources?
This is the main path of your project
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT
In here, the system call your media folder path where uploaded images store
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'
In here are your static files where css/js/img/ ... store
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
Additional location for staticfiles
STATICFILES_DIRS = (
os.path.join(SITE_ROOT, 'staticfiles'),
)
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from project_name import settings
admin.autodiscover()
urlpatterns = patterns('',
.........
.........
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
Here is the answer
Images from media folder is not displaying django template