Having trouble trying to change where Django looks for the default image in the ImageField. I am trying to store a default image within a folder in my "media" file.
Code from models.py below:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics')
When I load the page I get a 404 error:
Not Found: /media/default.jpg
[21/Apr/2020 18:11:48] "GET /media/default.jpg HTTP/1.1" 404 1795
Any ideas on how to add the "profile_pics" piece to the path?
add media path to your urlpatterns in DEBUG mode
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
you have to copy a image with default.jpg in media/profile_pics directory and use it for your default image for users
Related
Today I tried to have images in my project and the idea is simple - create news with an image, title, and description.
I wonder why when I set up my media files
So I make my news in this view:
class NewsCreate(views.CreateView):
template_name = 'web/create_news.html'
model = News
fields = ('title', 'image', 'description')
success_url = reverse_lazy('home')
Here is the model:
class News(models.Model):
TITLE_MAX_LENGTH = 30
title = models.CharField(
max_length=TITLE_MAX_LENGTH
)
image = models.ImageField(
upload_to='news/',
blank=True
)
description = models.TextField()
Here is the set-up in settings.py:
MEDIA_ROOT = BASE_DIR / 'mediafiles'
MEDIA_URL = '/media/'
Here is the urls.py file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('University_Faculty.web.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I've noticed that when I try to go to none existing URL this happens : wrong ulr page showing media as a correct one
This is the result in my media folder after 10+ POST requests it shows in the database that it is actually creating the news, but the images won't go anywhere: no files media folder
You need to correct
MEDIA_ROOT = BASE_DIR / 'media'
Hope this will work for you.
add this to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I want to download a file from the file field through Django views. I tried al lot but didn't get it. Now if I click on the media link it will show in the browser and I want to download it.
Thanks in advance.
models.py
class Question(models.Model):
title = models.CharField(max_length=254)
file = models.FileField(upload_to='exam/question')
def __str__(self):
return self.title
add your Folder path in setting.py file
Consider my folder name is media and that avaliable in where manage.py file is avaliable.
Add path in MEDIA_ROOT
settings.py
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
urls.py
add MEDIA_URL in appname>urls.py if you are access file from app.
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
#Add Your Path
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Download File
For localhost
http://localhost:8000/media/media/filename
I have my images downloaded inside the subroot images in my media folder and I'm trying to generate new models which will contain the photo inside the images folder. This is what my model and my view look like:
class Post(models.Model):
...
image = models.ImageField(upload_to="images", blank=True, null=True)
def generate_posts(request):
for i in range(20):
title_ = f'title{i}'
body_ = f'text for post number : {i}'
author_ = f'author{i}'
network_ = randomize_social()
post = Post(title=title_, body=body_, author=author_, social_network=network_)
if randomize_picture():
post.image.save("logo.png", File("images/svante.jpg"), save=True)
else:
post.image = None
post.save()
areGenerated = True
return render(request, "posts/generate_posts.html", {'areGenerated':areGenerated})
The logo.png file is created inside the images folder, but it's blank, 0kb size and when I follow the /generateposts url, I receive this error message:
AttributeError at /generateposts
'str' object has no attribute 'read'
What can I do to solve this problem?
Did you make changes to your settings file? you need to make changes such as
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
and don't forget to add these to your urls:
from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am new to Django and I am currently having problems in showing uploaded images in Django Admin. I have followed many posted Q and A here in stackoverflow but of those worked in my problem. I hope any active of the coding ninja here could help me with this problem. Here is the detailed view of the problem:
I have defined the MEDIA_ROOT and MEDIA_URL in settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
This is my upload model in models.py:
from django.utils.html import mark_safe
class ImageDetails(models.Model):
image = models.ImageField(null=True)
def image_img(self):
if self.image:
return mark_safe('<img src="%s" height="125px" width="125px"/>' % (self.image.url))
else:
return '(No image found)'
image_img.short_description = 'Thumbnail'
In my Application urls.py:
urlpatterns = [
url(r'^inputImage', views.inputImage, name='inputImage'),
url(r'', views.index),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In my admin.py:
class ImageDetailsAdmin(admin.ModelAdmin):
fields = ["image"] #for file upload
list_display = ("image_img",)
admin.site.register(ImageDetails, ImageDetailsAdmin)
The image was successfully stored at ProjectDIR/media. The HTML returns the url: http://127.0.0.1:8000/media/imagename.jpg at img tag. But the page fails to load the image (I will be redirected to index page whenever when using the url http://127.0.0.1:8000/media/imagename.jpg). I am using Django version 1.10
As suspected, this problem is about URLs in Django. The problem occurred because I declared the following urlpattern in an app urls.py:
url(r'', views.index, name='index'),
I solved the problem by changing the code to:
url(r'^$', views.index, name='index'),
And adding the following code at the project's main urls.py:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am newbie of django user.I trying to learn django webframework. because of that I meet interesting error and I couldn't solve it. I want save image to sqlite.When I upload an image it's working but when I try to display the picture I meet an error. I tried other answers but its didn't work.I am waiting your help.Thank you
error
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/info/airimage/1/media/Ataturk_Havalimani_2.jpg/
airimage object with primary key u'1/media/Ataturk_Havalimani_2.jpg' does not exist.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
my settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'amln51jyuo*wj2#g6k3vdd^#2)&84i#1#n2xvgx7hh#bpf7(l!'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = [] .......
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tav.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
and my content of folder
>tav
>info
__init__.py
admin.py
models.py
tests.py
views.py
>media
>tav
__init__.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
model for airimage
class airimage(models.Model):
stuff_image = models.FileField(upload_to="media/")
airno=models.ForeignKey(airandoto)
def __unicode__(Self):
return self.airno
class Meta:
verbose_name_plural="AirImage"
You're attempting to access the image incorrectly. Can you post the model for airimage? The primary key for the image in question looks to be 1, but you are appending extra information to the URL which is making Django think that you are looking for the row with the primary key of '1/media/Ataturk_Havalimani_2.jpg', which definitely does not exist.