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"),
)
Related
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 have a form with a ImageField() in it I've already set the media URL and directory and such in setting.py and url.py and on submit everything works perfectly, but suddenly now every time I try submit my form it fails and says in python terminal :
[17/Feb/2018 14:40:08] "POST /form/ HTTP/1.1" 200 37885
Not Found: /media/
I didn't modify either setting.py or the url.py (see code below):
setting.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
url.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
model.py
class Model_A(models.Model):
name = models.CharField(max_length=200, verbose_name="Name (as in NRIC)")
def upload_photo_dir(self, filename):
path = 'hiring/employees/photo/{}'.format(filename)
return path
photo = models.ImageField(upload_to=upload_photo_dir)
view.py
def application_form_view(request):
form = Model_AForm(request.POST or None, request.FILES or None)
if form.is_valid():
inst = form.save(commit=False)
inst.save()
context = {'form': form}
return render(request, 'form.html', context=context)
html
<form method="POST" enctype="multipart/form-data" id="application_form" name="application_form">
<label>name :</label>
{{ form.name}}
<label>Photo:</label>
{{ form.photo }}
</form>
Change below constants in Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media/'
Ensure that DEBUG is True if you running on port and not at server. Keep False at web server (nginix,apache etc).
Verify below statements in urls.py
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
As you have mentioned hiring/employees/photo/ path in your model file field this must be present in your root folder.
`hiring/employees/photo/` #Must be created at root of your project with permissions of 755.
And yes as denis said, media folder is also need to be there at root. with this path.
I'm new to Django and Python.I want to display a link to my files stored in my static folder.Here is the required code from settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = "/media/"
When I access these files through my admin I get the following url displayed in my browser:
http://127.0.0.1:8000/media/filename.pdf
Hence what I tried is to give a link to the file in my HTML code :
File
But instead of displaying http://127.0.0.1:8000/media/filename.pdf it just displays /media/filename.pdf which results in an error.
Adding localhost:8000/ before {{instance.docFile.url}} also didn't work.
Why isn't this working?What is the correct way to display link to my files?
Let me know if anything else is required.Thank you.
in your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in your settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
Then in your template
File
If you want know refer the docs Manage static files
The error is coming because your file is not stored in media.it is stored in static but your database store media URL. change your MEDIA_ROOT (given below) and try to upload one more time
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Don't put slash
:
File
Please see the Django setting MEDIA_ROOT documentation to better understand what your trying to do.
First MEDIA_ROOT and STATIC_ROOT must have different values.
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'
See static files documentation for more details.
Second, You need to add these settings to your base urls.py.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If you want to use {{ MEDIA_URL }} in your templates, add 'django.template.context_processors.media' in the 'context_processors' option of TEMPLATES in settings.py.
At the top of your HTML page add {% load static %} then to display your media:
<img src="{{ MEDIA_URL }}{{ docFile }}" alt="test">
Please take your time with the Django Documentation, trust me it will help and also checkout the File upload settings
I'm trying to display picture from the model, but it doesn't show anything. I uploaded the image using the admin panel and I can see the picture in the uploads folder. But when I try to display it in the templates, it doesn't show anything. I don't have anything is the settings file related to it such as media root, media url, because I'm not sure what to put for them
Here is the template where I'm trying to show it
<img src="{% url 'getDocProfilePicture' doctor.id %}">
Here is the models.py
class Doctor(models.Model):
name = models.CharField(max_length=30)
specialization = models.ForeignKey(Specialization)
clinic = models.ForeignKey(Clinic)
seekers = models.ManyToManyField(DoctorSeeker, through='Review')
language = models.ManyToManyField(Language)
education1 = models.CharField(max_length=100)
education2 = models.CharField(max_length=100, null = True)
gender_choices = ( ('M', 'Male'), ('F','Female'),)
gender = models.CharField(max_length=5, choices = gender_choices, null=True)
profile_pic = models.ImageField(upload_to='uploads/', null=True)
statement = models.TextField(null=True)
affiliation = models.CharField(max_length=100, null = True)
here is views.py
def getDocProfilePicture(request, id):
d = Doctor.objects.get(id=doctor_id)
return HttpResponse(d.profile_pic.read())
Urls.py
url(r'^getDocProfileicture/ (?P<id>\d+)/$', views.getDocProfilePicture, name='getDocProfilePicture'),
You no need such complex logic for display image.
{{ doctor.profile_pic.url }}
You don't need to use url template tag here and have a special separate view.
Just get the url from the ImageField:
<img src="{{ MEDIA_URL }}/{{ doctor.profile_pic.url }} ">
I know this question is old but I had the same problem and this solved in my case:
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_DIR = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_DIR, "media")
MEDIA_URL = '/media/'
urls.py
Then, my urls.py was missing this line of code to discover the /media/ folder and show the content:
urlpatterns += staticfiles_urlpatterns()
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}, name="media_url"),
) + urlpatterns
Hope it can help someone.
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