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.
Related
I get an error regarding Media directory on Django.
forms.py
from django.forms import ModelForm
from .models import Mots
from django import forms
class CreeMot(ModelForm):
mot = forms.CharField(max_length=50)
level = forms.IntegerField(max_value=10)
image = forms.FileField()
class Meta:
model = Mots
fields = ["mot", "level", "image"]
views.py
def cree_mot(request):
if request.method == "POST":
form = CreeMot(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = CreeMot()
return render(request, "cp/cree_mot.html", {'form': form})
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
# Add these new lines
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles', 'media_root')
When the form is submitted I get this error:
[Errno 30] Read-only file system: '/media'
Actually my /media/ directory is at the same level of /static/:
cp
/views.py
/forms.py
main_app
/settings.py
/...
media
static
manage.py
I put my /media/ in 777 chmod.
You should erase and leave just basics staff to understand what is going on in your app. In your case firstly, remove
MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles', 'media_root')
and leave just path to your path to media like :
MEDIA_ROOT = 'path/to/media'
Hope it will help for you
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 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
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"),
)
first post so be gentle.
I am trying to display a static image in django. I can upload the image to my media directory but when I try to display it I get a nothing. If I copy the url to the browser I get ...
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/Will_and_Matt.jpg
Raised by: django.views.static.serve
detail.py
...
<img src="{{ student.photo.url }}" class="img-responsive">
...
model.py
class Student(models.Model):
photo = models.FileField( blank=True, null=True)
project urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^opencmis/', include('opencmis.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_URL)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL)
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
My update form works as it created the media folder and places images in it.
The URL pattern seems to match /media as it doesn't give an error there it just doesn't display the image.
Any ideas?
document_root=settings.STATIC_URL should be document_root=settings.STATIC_ROOT and similar for MEDIA_ROOT. You want the filesystem path in there, not the URL.
– dhke