Django images not displaying - django

I am trying to give the users the ability to upload profile pictures and I have the Upload section working. Im running into issues when trying to display the picture in the template. Here is what I currently have:
Urls.py:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.ME DIA_ROOT,}),
#other urls
);
Settings.py:
MEDIA_ROOT = '/home/bpurdy/socialCompromise/media/'
MEDIA_URL = '/media/'
Model:
class Member(models.Model):
STATUS = Choices('active', 'disabled')
GENDER_CHOICES = (('Male','M'), ('Female','F'),)
user = models.ForeignKey(User)
created_date = models.DateTimeField(auto_now_add = True)
updated_date = models.DateTimeField(auto_now = True)
photo = models.ImageField("Profile Pic", upload_to="images/profiles", blank = True, null = True)
#Other user properties
Template: (Key is the user)
{%if key.profile.photo %}
<img src="{{ key.profile.photo.url }}" alt="{{key.profile.photo.title}}">
{%endif%}
After the upload there is a file located in the /home/bpurdy/socialCompromise/media/images/profiles directory however when trying to render the page I get the following errors:
SERVER_IP_ADDRESS/media/images/profiles/Desert.jpg 404 (Not Found) And
Resource interpreted as Image but transferred with MIME type text/html: SERVER_IP_ADDRESS/search/images/profiles/Desert.jpg".
And the image wont display.

Try urls.py like this:
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
# urls
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and tell me how it works.

Related

Django is showing me a 404 error instead of my image

my friends, this is my first question here.
So, I follow the Django documentation and some questions here, but the problem keep happening.
I did what was said on other similar questions, like this one, for examaple:
Issue with image in django
But the problem persists.
So, my model looks like this:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True)
picture = models.ImageField(blank = True, null = True, upload_to = user_directory_path)
whatsapp = models.PositiveIntegerField(blank = True, null = True)
My settings looks like this:
MEDIA_ROOT = f"{BASE_DIR}/media"
MEDIA_URL = '/media/'
I added
+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
to the end of my urls.py file:
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import UserList, FeedbackList, DayList, AttractionList, UserDetail, UserProfileList, ProfileDetail
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('users/', UserList.as_view()),
path('user/<str:username>', UserDetail.as_view()),
path('profiles/', UserProfileList.as_view()),
path('profile/<str:user__username>', ProfileDetail.as_view()),
path('feedbacks/', FeedbackList.as_view()),
path('days/', DayList.as_view()),
path('attractions/', AttractionList.as_view()),
path('token/', TokenObtainPairView.as_view()),
path('token/refresh/', TokenRefreshView.as_view()),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
The folder and images are being created on my file system when I add them via the admin, but when I click to see them over there I recieve a 404.
Request URL: http://192.168.15.21:8000/media/uploads/profile_pictures/1-417ee0cb-cd83-4ea6-a692-a4af3b4afcce-eu.jpg
Using the URLconf defined in evento.urls, Django tried these URL patterns, in this order:
event_app/
admin/
The current path, media/uploads/profile_pictures/1-417ee0cb-cd83-4ea6-a692-a4af3b4afcce-eu.jpg, didn’t match any of these.
This is my file structure
I am making a mobile app and serving my data using Django Rest Framework, the images are the only thing giving me a headache right now.
Herer i have change your upload_to = profile_pictures
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True)
picture = models.ImageField(blank = True, null = True, upload_to = profile_pictures)
whatsapp = models.PositiveIntegerField(blank = True, null = True)
I have also change settings as given below
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In your main project app you can add urlpatterns as given below if you have to
urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

Why cannot I see the image file in django?

I tried to load an image file, but it didn't work. I uploaded the image file by admin. Thanks for the help!
here is my code
in urls.py
path('main/archive/<int:video_id>/', views.loadphoto, name='loadphoto'),
in views.py
def loadphoto(request, video_id):
target_img=get_object_or_404(Record, pk=video_id)
context={'target_img':target_img.picture}
in models.py
class Record(models.Model):
record_text = models.CharField(max_length=50)
pub_date = models.DateTimeField('date published')
picture=models.ImageField(blank=True)
def __str__(self):
return self.record_text
in img.html
<img src="target_img">
Main
First You Need To Join Your Media directory to your app
Here is the Way You Can Do That:
First You Need To Add This in Your Setting.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASEDIR,'your folder directory')
#for example app/media or something
Then You Need To Create Media Url Here is The Way:
Then You Need To Add in your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('main/archive/<int:video_id>/', views.loadphoto,name='loadphoto'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then You Need To Add This in Your Html File
<img src='{{ target_img.url }}'>
You Can See More Details Here:
https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.fields.files.FieldFile.url
ImageField is derived from FileField. In order to display the image in your template, you should provide its url, see https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.fields.files.FieldFile.url
The source attribute should instead by populated as follow:
<img src="target_img.url">

How to generate link for file download?

I created a model without using FileField() and saved the url into path field. Now while displaying I can see the attributes but I cannot download the file. href treats it as a page and i get an error saying GET request failed.
I need to do the same for static files also.
models.py looks like this:
import os
from django.conf import settings
from django.db import models
# Create your models here.
class Document(models.Model):
code = models.CharField(max_length = 50)
path = models.CharField(max_length = 500)
date_of_submission = models.CharField(max_length = 50)
type = models.CharField(max_length = 50)
title = models.CharField(max_length = 200)
department = models.CharField(max_length = 50)
subject = models.CharField(max_length = 100)
updation_allowed = models.CharField(max_length = 1, default = '0')
#property
def relative_path(self):
return os.path.relpath(self.path, settings.MEDIA_ROOT)
template has some code like this:
<a href = '{{ MEDIA_URL }}{{ value.thesis.relative_path }}'> Thesis </a>
*static files*
<a href='/uploads/report.pdf'> Front Page</a>
I tried using the property and provinding the path myself.
urls.py (project/urls.py)
from django.conf.urls.static import static
urlpatterns = [
...
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
...
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
To allow file downloading you need to create a separate view with FileResponse as a response. This view will take some unique argument (I suppose it will be relative path to the file) with url provided in html template. Inside this view, FileResponse will open your file by provided path and then will return response with your file. I think you should do it like this:
Views.py:
def download_file(request, relative_path): # this is a view with file response
media_root = settings.MEDIA_ROOT
return FileResponse(open(f"{media_root}\{relative_path}", "rb"), as_attachment=True, filename="some_name.smth")
template:
<a href = '{% url "download" relative_path=value.thesis.relative_path %}'> Thesis </a>
*static files*
<a href='/uploads/report.pdf'> Front Page</a>
urls.py:
urlpatterns = [
path("download-file/<slug:relative_path>/", views.download_file, name="download")]
You will need to combine with PATHes to get it to work.

Django ImageField Image Not Displaying

I'm trying to use Django 2.0. I'm using the development 'runserver' right now, so please keep in mind that I'm not in production yet. I am familiar with the differences between the two with regard to static files.
I have a Blog Post model. In the admin, I want to be able to add an image to my model using ImageField. I'd like it to be optional, and provide a default image if none is added.
I am able to load images in admin. I am unable to render my image in my template. The console shows that Django is trying to GET my image, but my configurations have not worked so far.
Here's my model and relevant field:
from PIL import Image
class Post(models.Model):
....
thumbnail = models.ImageField(default='/img/default.png', upload_to='img', blank=True, null=True)
....
My model works well aside from the ImageField. My View works well, and I don't think there is any issue there.
Here is my urls.py
....
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
....
path('posts/', views.PostListView.as_view(), name='post_list'),
path('post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'),
path('post/random/', views.random_post, name='random_post'),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I'm not at all sure about how to handle static files vs. media files in my urls.py, especially with changes to Django in version 2.0.
Here's my relevant settings.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
....
'django.contrib.messages.context_processors.media',
....
]
},
},
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media/'
I am equally unsure of what to put in my settings.py concerning media. My static CSS files are working just fine. I have a logo image in my static files that is rendering in my base template.
Here is my template tag for the ImageField:
<img class="card-image mr-3" src="{{ post.thumbnail.url }}" alt="Generic placeholder image">
Lastly, my /static folder and my /media folder are in the same directory. These are both in my app directory, /blog.
Can anyone see any blaring errors here, or can they make suggestions? My issue is the default image is not loading. The default image IS in the correct directory /media/img/. The console warning says "Not Found: /media/img/default.png".
Thanks in advance. Any suggestions will be helpful.
Django ImageField for Admin Panel
There is important thing you have to define your MEDIA_URL in urls.py.
Without this definition framework doesn't gives to you permission to access image
Setting.py
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
urls.py
if settings.DEBUG: # new
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Models.py
class Product(models.Model):
title = models.CharField(max_length=150)
image=models.ImageField(blank=True,upload_to='images/')
def __str__(self):
return self.title
def image_tag(self):
return mark_safe('<img src="{}" height="50"/>'.format(self.image.url))
image_tag.short_description = 'Image'
Admin.py
class ProductAdmin(admin.ModelAdmin):
list_display = ['title','image_tag']
readonly_fields = ('image_tag',)
Printing the media root helped me solve this issue. Thanks Alasdair.
I don't think there was any issue with my model field above.
The urls.py code that I ended up using is directly from Django docs for Django 2.0 in handling static files https://docs.djangoproject.com/en/2.0/howto/static-files/.
The changes I made to Settings were done thanks to printing my MEDIA_ROOT in the console. I changed the syntax and the direction of a slash (blog\media). I also deleted the context processor shown above in my TEMPLATES options.
Here's what works for me:
models.py
thumbnail = models.ImageField(default='img/default.png', upload_to='img', blank=True, null=True)
urls.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'blog\media')
MEDIA_URL = '/media/'
print(MEDIA_ROOT)
Template tag
<img class="card-image mr-3" src="{{ post.thumbnail.url }}" alt="Generic placeholder image">

Django video in template, seems to detect media but not working

Please i have been working on this for a while but don't seem to find the problem. I am trying to get a video from the uploaded files to work on the template,but all i keep getting is a blank video, although when i view the page source or inspect the video element, it seems to be pointing to the right video, and all solutions i have tried to make this work proved abortive.
Below are my codes:
MY MODEL:
class Sermon(models.Model):
topic = models.CharField('Topic', max_length=50)
pub_date = models.DateField('Sermon Date')
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
last_edited = models.DateTimeField(auto_now_add=False, auto_now=True)
type = models.CharField('Type', max_length=50, choices=sermon_chioices)
audio = models.FileField(upload_to='audios', default="Not Available", blank=True, validators=[validate_audio_extension], null=True)
video = models.FileField(upload_to='videos', default="Not Available", blank=True)#can be changed if the video will recide in the system
outlines = models.FileField(upload_to="outlines", default="Not Available", blank=True,)
user = models.ForeignKey(User, verbose_name="User", editable=False)
class Meta:
ordering = ['-pub_date']
def __unicode__(self):
return self.topic
def get_absolute_url(self):
#return reverse('sermon_detail', kwargs={'pk': self.pk})
return reverse('sermon_detail', args=[str(self.id)])
MY VIEW:
class SermonDetails(DetailView):
model = Sermon
template_name = 'agonopa/sermon_details.html'
context_object_name = 'sermon'
def get_context_data(self, **kwargs):
context = super(SermonDetails, self).get_context_data(**kwargs)
#context['sermons'] = Sermon.objects.all()
return context
#Sunday Service List
class SundayServiceSermonList(ListView):
model = Sermon
template_name = 'agonopa/sermon.html'
context_object_name = 'sermon_list' #'ss_sermon_list'
queryset = Sermon.objects.filter(type__exact="SUNDAY SERVICE")
def get_context_data(self, **kwargs):
context = super(SundayServiceSermonList, self).get_context_data(**kwargs)
context['title'] = 'Sunday Service'
return context
MY TEMPLATE:
{% if sermon %}
<h3>{{ sermon.topic}}</h3>
{{sermon.outline}}
{{ sermon.pub_date}}
{% endif %}
<video loop class="embed-responsive-item thumbnails" controls>
<source src="{{ MEDIA_URL}}{{sermon.video.url}}" type="video/mp4">
</video>
MY MEDIA SETTINGS:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.dirname(BASE_DIR)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_DIR,'churchsite_static_root','media_root')
The Server returns things like this in the terminal:
[28/Nov/2015 11:38:10]"GET /agonopa/sermon/3/ HTTP/1.1" 200 377
[28/Nov/2015 11:38:10]"GET /media/videos/wowo_Boyz_5gQAbzG.mp4 HTTP/1.1" 404 2344
Thanks for your help in advance, and for further clarification on the question pls do let me know.
It should be noted, that i have tried many solutions from stakeoverflow, and several blogs but none seems to works, so i had to post it here.
It seems to me that your MEDIA_ROOT is way too high (as in no longer within your project). When I use the settings you use, I get a media root directory of ../../../churchsite_static_root/media_root/ relative to your settings.py file. I would expect churchsite_static_root to be one directory up from settings.py (or at the same level as manage.py).
Go into Django shell and check the media root path to see if it seems reasonable (and confirm that your files are actually there):
python manage.py shell
>>> from django.conf import settings
>>> settings.MEDIA_ROOT
Try the following in your settings.py and let me know if it helps:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'churchsite_static_root', 'media_root')
Be sure you have something like this in your site's urls.py if using python manage.py runserver:
# For Django>=1.8:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# For Django<1.8:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
I simply imported settings, and then static, and also added the if Debug: to my urls.py, thus the program looked as below:
Urls.py:
from django.conf.urls import include, url, patterns
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from agonopa.views import SermonMonthArchiveView, SermonYearArchiveView
urlpatterns = [
# Examples:
# url(r'^$', 'churchsite.views.home', name='home'),
url(r'^$', 'agonopa.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^agonopa/', include('agonopa.urls')),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
That's all to it. Thanks to Mike Covington in all.
Also note, that the media settings, template and other files above didn't change for the whole stuff to work.