I'm trying to built a CMS for the admin where he is able to change the images.
But so far it doesn't work and I can't find the error.
Here is the model and there is no default.png
models.py
class Media(models.Model):
image = models.ImageField(blank=True, null=True)
class Meta:
verbose_name_plural = "Photo"
def __str__(self):
return self.image.name
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
print(MEDIA_ROOT)
views.py
def gallery_view(request):
return render(request, 'web/gallery.html', context={"pic": Media.objects.first()})
Here is my template for the ImageField:
<img class="ui bordered image" src="{{ pic.image.url }}">
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('webpage/', include('webpage.urls')),
path('', include('web.urls')),
path(r'^', include('web.urls', namespace='web')),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now when I print(MEDIA_ROOT) my terminal shows this:
'Not Found: /media/default.png'
"GET /media/default.png HTTP/1.1" 404 1808"
and
"POST /admin/web/media/add/ HTTP/1.1" 302 0"
"GET /admin/web/media/ HTTP/1.1" 200 1282"
Does anyone have a suggestion for me where the bug is?
Thanks in advance.
Double check if you have added paths for both Static and Media URL in settings.py.
For Static URL:
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
For Media URL:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
To access display your img:
<img class="border-radius-50 profile-img" src="{{ MEDIA_URL }}{{ pic.image.url }}" alt="...">
class Media(models.Model):
image = models.ImageField(blank=True, null=True)
Give a default value for you models
image = models.Imagefield(blank =True, null=True, default ="add photo")
Makemigrations and migrate after adding default.
Not so sure for views
def gallery_view(request):
if(request.method=='POST'):
= request.POST['media']
value = 'Media : %s (media)
return render(request, 'web/gallery.html', context={"pic": Media.objects.first()})
Related
I used Django Admin to upload an image and I am trying to get it to display in a template. The alt text is displayed but I keep getting a 404 error for the image and it does not display. When I uploaded the image the path that it pulls in the template media/images/mari-profile-pic.png is valid and contains the image I am trying to display.
models.py
from django.db import models
# Create your models here.
class Image(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(upload_to='images/')
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Image
# Create your views here.
def index(request):
imageModel = Image.objects.get(pk=1)
return render(
request,
"SocialLinks/index.html",
{
"profile_pic_title":imageModel.title,
"profile_pic":imageModel.image
}
)
index.html template
<div id="profile">
<img id="userPhoto" src="{% get_media_prefix %}{{ profile_pic }}" alt="{{ profile_pic_title }}">
</div>
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I have tried removing and adding the {% get_media_prefix %} tag and the image still does not display.
settings.py:
MEDIA_URL = '/media/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(VENV_PATH, 'static_root')
MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root')
your.html:
{% load static %}
To make the imgaes works add .url to be like this: {{ i.img.url }}, and go to the urls.py of the app, and add the following:
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)
Call the templates and the statics from the (PROJECTNAME/settings.py) by add the following in the TEMPLATES 'DIRS':
'DIRS': [os.path.join(BASE_DIR, 'temp')],
Need to access static files from common directory as suggested in
https://docs.djangoproject.com/en/3.2/ref/contrib/staticfiles/
command, python manage.py collectstatic
copies to STATIC_ROOT but when referring to it in html, it throws error
Not Found: /static/teststatic/images/product-5.jpg
How to make it work with files from the STATIC_ROOT location ?
I have tried this and has worked
<img src="{% static 'teststatic/static/teststatic/images/product-5.jpg' %}" alt="Trulli" width="500" height="333">
urls.py
from django.urls import path
from . import views
app_name = 'teststatic'
urlpatterns = [
path('tstatic/', views.tstatic, name='tstatic'),
]
views.py
from django.shortcuts import render
# Create your views here.
def tstatic(request):
return render(request, 'tstatic.html', {})
settings.py
DEBUG = True
.
.
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
STATICFILES_DIRS = (
('testcss', os.path.join(BASE_DIR, 'testcss', 'static', 'testcss')),
('helpdesk', os.path.join(BASE_DIR, 'helpdesk', 'static', 'helpdesk')),
('teststatic', os.path.join(BASE_DIR, 'teststatic', 'static', 'teststatic')),
(os.path.join(BASE_DIR, 'staticfiles'))
)
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
tstatic.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<body>
<h2>HTML Image</h2>
<img src="{% static 'teststatic/images/product-5.jpg' %}" alt="Trulli" width="500" height="333">
</body>
</html>
Error :
2021-04-27 12:42:47,744: Not Found: /static/teststatic/images/product-5.jpg
My image path is working but Idk why it's not able to display it, any help is appreciated
models.py
class movies(models.Model):
Image = models.ImageField(blank=True, null=True)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'media'
home.html
{% for m in movies %}
<img src="{{ m.Image.url }}" width="200px", height="300px">
{% endfor %}
class movies(models.Model):
Image = models.ImageField(upload_to='images/', blank=True, null=True)
So the problem was with the Media root, my path was fine but Django wasn't able to get it somehow, so I ran this code to automate Django to find media root by itself
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')
and made a debug condition in the urls.py to run the request if viewed under development or localhost
if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am using Django 1.9.3. I am trying to display media files uploaded by say a user (e.g. imageFields).
HTML Page:
{% for project in projects %}
<img src="{{ project.image.url }}" class="img-responsive" alt="">
{% endfor %}
Views.py:
def home(request):
projects = AvailableProject.objects.all().order_by('-published_date')
return render(request, 'accounts/home.html', {'projects': projects})
urls.py:
urlpatterns = [
...
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
('global', os.path.join(BASE_DIR, 'smilesite', 'project_static')),
('admins', os.path.join(BASE_DIR, 'admins', 'static')),
('accounts', os.path.join(BASE_DIR, 'accounts', 'static')),
('mysite', os.path.join(BASE_DIR, 'mysite', 'static')),
('media', os.path.join(BASE_DIR, 'media')),
)
# print(STATICFILES_DIRS)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
)
# Define place to save media (e.g. pictures for all the projects)
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
models.py:
from django.db import models
from django.conf import settings
# Create your models here.
class AvailableProject(models.Model):
image = models.ImageField(upload_to=settings.MEDIA_ROOT)
I have literally went through every single stack over flow page on this and tried the following solutions, but still has not worked...:
<img src="{% static 'media/{{project.image.title}}.jpg' %}" class="img-responsive" alt="">
<img src="{{ project.image.url }}" class="img-responsive" alt="">
I don't know why the project.image.url is not showing the corresponding image correctly.
The reason was exactly what Joni Bekenstein said.
I changed this one line and everything worked:
image = models.ImageField(upload_to='uploads/')
Then {{ project.image.url }}, was the correct url.
I am trying to upload a file.
this is my model.
def custom_path(instance, filename):
return '/'.join(['upload',instance.student.user.username,filename])
class Doc(models.Model):
uploadtime = models.DateTimeField(auto_now_add=True, blank=True)
datei = models.FileField(upload_to=custom_path,default='')
student = models.ForeignKey(Student,related_name='students_file')
title = models.TextField()
desc = models.TextField()
def __unicode__(self):
return self.title
and this is my views.py
def hochgeladen_danke(request):
if request.FILES.get('file'):
student = request.user.get_profile()
student.students_file.create(datei=request.FILES.get('file'),title='t',desc='t')
return render_to_response('upload.html',{},context_instance=RequestContext(request))
my html:
<form action="/hochgeladen_danke/" method="post" enctype="multipart/form-data">
{% csrf_token %}
File: <input type="file" name="file"/>
<button type="submit">upload</button>
</form>
my settings.py:
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media")
MEDIA_URL = "/media/"
STATIC_ROOT = os.path.join(PROJECT_PATH, "static")
STATIC_URL = '/static/'
when i try to upload a file. it is saying:
ImproperlyConfigured at /hochgeladen_danke/
/static/ isn't a storage module.
i dont know why this is happening. my custom_path seems to be right.
my urls.py:
..
url(r'^hochgeladen_danke/$','hochgeladen_danke',name='hochgeladen_danke'),
)
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns
Something is wrong with your settings.DEFAULT_FILE_STORAGE.
The exception you have provided comes from django.core.files.storage#272, which in turn comes from default_storage right below, and django.db.models.files#221. The constructor is called in your view, causing the exception to be thrown.