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.
Related
I followed the procedures to setup staticfiles but I'm not getting what i want
when I add an image to the section background it gives a wrong path "staticfiles/css/assets/img/oilcarriage.jpg"
instead of "staticfiles/assets/img/oilcarriage.jpg"
here's the path to the image:
i would be really grateful if you can help me now :)
You have to join the path so use the following STATICFILES_DIRS = (os.path.join(BASE_DIR, 'staticfiles'),)
Here you go static file config in settings.py file
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
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">
This worked fine everytime used to do django websites but this time it is giving me an error.
Settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'portfolio/static/')
]
STATIC_ROOT = os.path.join(BASE_DIR , 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I have a profile.jpg in my directory Portfolio-Project/Portfolio/static/profile.jpg. It should collectstatic from here and paste the staticfiles in Portfolio-project/static as mentioned in my code. but it is giving ,me some error.
Error After using the command "Python manage.py collectstatic"
django.core.exceptions.SuspiciousFileOperation: The joined path
(C:\Users\Kiran\Desktop\portfolio-project\portfolio\static\Profile.jpg) is
located outside of the base path component
(C:\Users\Kiran\Desktop\portfolio- project\portfolio\static\)
Please Help.
Thanks
In your line:
os.path.join(BASE_DIR, 'portfolio/static/')
Delete the last slash:
os.path.join(BASE_DIR, 'portfolio/static')
Anyway, this is the ideal:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
I recently faced this error but it‘s actually simple:
Chances are you downloaded a Template, here is the solution:
First you have to check your css file for stuff like relative links
For example your CSS might be referencing a file outside your django project itself.
e.g. backround:url('...\image\Profile.jpg') this actually worked for me
Note:
The key fact is just to check your CSS or (maybe js) file first if it‘s a referencing file that you‘re not using or file that is referring to something that is not in your django project directory.
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
I am new to django ! When I use the command python manage.py collectstatic I get this error
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
But I can successfully run the server .
My static files declarations are :
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('assets', os.path.join(PROJECT_DIR, '../static')),
)
and debug is set to true
DEBUG = True
How can I fix this? Else am missing any installation packages ?
Try this,
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
Look at https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-STATIC_ROOT
You must have to give path in STATIC_ROOT in settings.py where all your static files are collected as for example:-
STATIC_ROOT = "app-root/repo/wsgi/static"
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('assets', 'app-root/repo/wsgi/openshift/static'),
)
you can create 'static' folder in any subfolder and have required files in it.
In settings.py add the following lines of code:
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
After running
python manage.py collectstatic
a new static folder will be created in your parent App folder
well had this error as well. I fixed:
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
else:
STATIC_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'assest')
STATICFILES_DIR = [
os.path.join(BASE_DIR, 'static')
]
I had to put STATIC_ROOT and STATIC_URL above the STATICFILES_DIRS declaration.
STATIC_ROOT = "/var/www/YourSiteFolder/static/"
STATIC_URL = '/static/'
look at https://docs.djangoproject.com/en/1.11/howto/static-files/#deployment
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
This works for me
if you want to load static files rather than admin panel files or getting errors while loading webpage static files like CSS js etc
I suggest you change the folder name of 'static' to 'staticfiles'
and then add this code in your settings.py
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'staticfiles'),
)
then after run python manage.py collectstatic
Then the problem will be fixed