Uploaded dynamic file cannot be found - django

I uploaded a dynamic picture named "IMG_4606.png" through admin page and when loading it through another app, it is not being found.
setting.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'project_headshots')
MEDIA_URL = '/project_headshots/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")`
models.py
from django.db import models
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.ImageField(null=True, blank=True, upload_to="iad")
`
html code
img class="card-img-top" src="{{project.image.url}}" alt=""
ERROR:
`Not Found: /projects/project_headshots/iad/IMG_4606.png
[25/Sep/2019 16:28:34]
"GET /projects/project_headshots/iad/IMG_4606.png HTTP/1.1" 404'

Related

raise ImproperlyConfigured(msg)

raise ImproperlyConfigured(msg)
In "additional_app", in "models.py":
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
id_user = models.IntegerField()
bio = models.TextField(max_length=500, blank=True)
profileimg = models.ImageField(upload_to='profile_images', default='btm-banner.png')
location = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.user.username
I have created 'media_folder' in "additional_app" and put into img 'btm-banner.png' to django load it if user dont load self picture in profile.
Also i write in settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Also in 'main_app', in urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now i want make 'migration'
In Terminal:
S:\Programms\Projects\social_app\main_app> py manage.py makemigration
Enter
Result:
django.core.exceptions.ImproperlyConfigured:
additional_app.apps.AdditionalAppConfig.default_auto_field refers to the module 'django.db.media
.BigAutoField' that could not be imported.
img
img

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)

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.

Images not loading Django website

Images on my django website are not loading for some reason
This is my models.py
thumbnail = models.ImageField(upload_to='images/',blank=True)
This is my settings.py lines
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
if DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'static/static-only')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/static'),
)
This is my views.py
class BlogIndex(generic.ListView):
queryset = models.Entry.objects.published()
template_name = "index.html"
paginate_by = 5
In url.py
if settings.DEBUG:
urlpatterns +=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
In index.html i did this
<img class="img-rounded" src = "{{object.thumbnail.url}}"/>
pip freeze
Django==1.11.2
django-ckeditor==5.2.2
django-crispy-forms==1.6.1
django-markdown==0.8.4
django-pagedown==0.1.3
Markdown==2.6.8
olefile==0.44
Pillow==4.1.1
The Images are getting saved in the static/media/images directory
But the images are not loading in the web page...
When i try to right-click and view the image It shows this error SCREEN SHOT
Other objects are working perfectly.. Only the images aren't loading
You need the media url in the src:
<img class="img-rounded" src = "{{object.thumbnail.url}}"/>
should be:
<img class="img-rounded" src = "{{MEDIA_URL}}{{object.thumbnail.url}}"/>
or something similar
<img class="img-rounded" src = "/static/media/uploads/{{object.thumbnail.url}}"/>
The Issue is fixed, (Got assistance from a facebook group)
The issue was a url pattern in the views.py
The screen shot that I put had a line
Raised by : blog.views.Blogdetail
Apparently i had a urlpattern
url(r'^(?P<slug>\S+)/$', views.BlogDetail.as_view(), name='entry_detail'),
My pattern for blog detail view has match \S+ - so any string of characters that has no spaces in
Which will match pretty much any pattern that hasn't matched previously and any other url pattern which are below this particular url will not be accessed
Changed the url pattern to the following and I was good to go
url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(),name='entry_detail'),
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
in this model you can see Overwrite of exist IMG, return img as base string:
models.py
from django.db import models
from django.core.files.storage import FileSystemStorage
from base64 import b64encode, b64decode
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name, max_length=700):
if self.exists(name):
os.remove(os.path.join(settings.MEDIA_ROOT, name))
return name
def upload_location(instance, filename):
return os.path.join('defaultfolder', instance.phone, filename)
class ImgModel(models.Model):
name= models.CharField(max_length=100)
img = models.FileField(storage=OverwriteStorage(),
upload_to=phone_upload_location,
null=True,
blank=True,
max_length=700)
def image_to_base64(self, model_picture_path):
if model_picture_path:
try:
with open(model_picture_path.path, "rb") as imageFile:
str = b64encode(imageFile.read())
return "data:image/jpg;base64,%s" % str.decode()
except IOError:
return model_picture_path.url
else:
return None
.html
<img src="{{ MEDIA_URL }}foo.jpg">
I faced this issue and I tried lot of things but imges wont load then I tried out a simple trick but this did the job. What I did was, in my settings.py file, I included the STATIC_DIR varaible just after BASE_DIR. Below is my settings.py file
Settings.py
#Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,"static")
#Other content
STATIC_URL = '/static/'
STATICFILES_DIRS=(
STATIC_DIR,
)
Check this out maybe this will help!
How to fix images answer is
mention above index.html
{% static 'travello/images/' as baseUrl %}
path
then

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.