Django is showing me a 404 error instead of my image - django

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)

Related

How to serve media files correctly in django subdomains (using django-hosts) in development?

I have this model Blog and using it in 'blog' subdomain created with 'django-hosts'.
My subdomains in 'hosts.py':
from django.conf import settings
from django_hosts import patterns, host
host_patterns = patterns('',
host(r'blog', 'blog.urls', name='blog'),
host(r'(|www)', settings.ROOT_URLCONF, name='www'),
)
And Blog model - Note that 'title_image' field powered by 'sorl.thumbnail' and 'content' field is a 'django-ckeditor' uploadable field:
class Blog(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('author'),
on_delete=models.CASCADE,
related_name='blog_author')
title = models.CharField(verbose_name=_('title'), max_length=200)
title_image = ImageField(verbose_name=_('title image'), blank=True)
content = RichTextUploadingField(verbose_name=_('content'))
I've' created a simple ListView for blog that show every blog title, content and title_image to viewer:
class BlogListView(ListView):
"""Everyone can see all blogs"""
template_name = 'blog/templates/blog/blog_list_view.html'
model = Blog
context_object_name = 'blogs'
And my blog.urls:
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.BlogListView.as_view(), name='blog_list_view'),
]
When I'm using my blog subdomain (eg: blog.localhost:8000/) it doesn't show any image to me whether it's the title_image or any image in django-ckeditor powered 'content' field.
But when I'm not using subdomain and instead use 'blog' app as other 'URLCONF' path (eg: localhost:8000/blog/) I can see every images without any problem.
Anyone knows why using subdomains, media files does not shown and how to fix it?
I figured it out.
What you need to do is load the MEDIA folder in your urls.py where your hosts is pointing to.
So in your blog.urls
from django.urls import path
from django.conf import settings
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.BlogListView.as_view(), name='blog_list_view'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
first of all in settings.py
MEDIA_DIR = BASE_DIR / 'media'
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
then in main project urls.py
from django.conf.urls import url
from django.views.static import serve
from django.conf import settings
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and I would ugget in your models use this
title_image = models.ImageField(upload_to='title_images', blank=True)
if you are using app locally then this work fine if the problem is causing in production then use cloudinary

Static and Media Files in Django 1.10

I have a ImageField in my user_accounts/models.py file which i use to store the profile picture of users.It has a upload_to field which calls a function and uploads the file to a media folder in myproj/media/.. . The Image Field also has a default field which is used to set the default profile image from the static folder.
This is an entry of User Table in development server.
In The image the avatar field shows static url but when clicked it /media/ gets attached to the url before /static/ as follows:
In The image the url bar shows /media/ attached before the static url.When i manually remove the /media/ from the url the defaultProfileImage is shown.
This is my project structure
|-myproj
|-myproj
|-__init__.py
|-settings.py
|-urls.py
|-wsgi.py
|-static
|-user_accounts
|-images
|-defaultrofileImage.png
|-user_accounts
|-__init__.py
|-models.py
|-admin.py
|-tests.py
|-views.py
|-urls.py
Models.py File
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
def get_upload_url(instance , filename):
return 'userProfileImages/%s/%s'%(instance.username , filename)
class User(AbstractUser):
mobileNumber = models.IntegerField(blank = True , null = True)
avatar = models.ImageField(upload_to = get_upload_url , default = '/static/user_accounts/images/defaultProfileImage.png')
def __str__(self):
return self.username
I have the following lines added in my settings.py file
AUTH_USER_MODEL = 'user_accounts.User'
STATIC_URL = '/static/'
STATICFILES_DIRS =[
os.path.join(BASE_DIR,'static'),
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
This is my urls.py file
from django.conf.urls import url,include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^user/',include('user_accounts.urls')),
] + static(settings.MEDIA_URL , document_root = settings.MEDIA_ROOT)
How should i correct the url so that when i click the url in my admin panel it shows the correct url in url bar and i get to see the defaultProfileImage??
ImageField default value refers to 'MEDIA_URL', therefore you should create media folder, place your defaultProfileImage there and use default = 'defaultProfileImage.png' in the model field, as in your example it resolves the picture path as MEDIA_URL + default so you get /media/static/....
You probably could omit default= from the model field and override save method to programmatically define the path to the avatar field.
Usually, user-uploaded media files reside in the MEDIA_ROOT and static assets in STATIC_DIRS.
You can find more info here and read about FileField which is the base class of ImageField here.

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.

Django images not displaying

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.