Django wont upload images to media directory - python

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')

Related

Django Rest Framework - Uploading files link 404

I'm trying to upload a file (any file) to my rest framework.
At the current time, I'm able to upload the file but unable to click on the generated link for some reason.
This is my settings.py:
...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "site_static")]
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
This is my model.py:
...
class FileUpload(models.Model):
created = models.DateTimeField(auto_now_add=True)
user_profile = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
datafile = models.FileField(blank=False, null=False)
This is my views.py:
...
class FileUploadViewSet(viewsets.ModelViewSet):
"""Handles uploading a file"""
authentication_classes = (TokenAuthentication,)
serializer_class = (serializers.FileUploadSerializer)
queryset = models.FileUpload.objects.all()
parser_classes = (MultiPartParser, FormParser,)
permission_classes = (
permissions.UpdateOwnStatus,
IsAuthenticated
)
def perform_create(self, serializer):
"""Sets the user profile"""
serializer.save(user_profile=self.request.user,
datafile=self.request.data.get('datafile'))
This is my serializer.py:
...
class FileUploadSerializer(serializers.HyperlinkedModelSerializer):
user_profile = serializers.SlugRelatedField(
read_only=True,
slug_field='id'
)
class Meta:
model = models.FileUpload
fields = ('id', 'user_profile', 'created', 'datafile')
extra_kwargs = {'user_profile': {'read_only': True},
'created': {'read_only': True}}
This is my complete urls.py:
router = DefaultRouter()
router.register('hello-viewset', views.HelloViewSet, basename='hello-viewset')
router.register('profile', views.UserProfileViewSet)
router.register('feed', views.UserProfileFeedViewSet)
router.register('upload', views.FileUploadViewSet)
urlpatterns = [
path('hello-view/', views.HelloApiView.as_view()),
path('login/', views.UserLoginApiView.as_view()),
path('', include(router.urls)),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
When I upload a file, the datafile field becomes populated with the file location, such as:
{
"id": 2,
"user_profile": 4,
"created": "2020-04-27T21:08:16.269058Z",
"datafile": "http://127.0.0.1:8000/media/test.png"
},
I look at the project files and I can find the file at /media/, however, the link does not work.
How can I make the link work.
quoted from the docs here
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My problem, as it turns out, is that I was editing the wrong urls.py.
Both the api folder and the project folder has urls.py.
When adding that urlpattern to the correct project urls.py, it works fine!

DJANGO - upload image stored locally to model ImageField attribute

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)

Django Admin: Determine correct image upload path

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)

page not found django.views.static.serve

first post so be gentle.
I am trying to display a static image in django. I can upload the image to my media directory but when I try to display it I get a nothing. If I copy the url to the browser I get ...
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/Will_and_Matt.jpg
Raised by: django.views.static.serve
detail.py
...
<img src="{{ student.photo.url }}" class="img-responsive">
...
model.py
class Student(models.Model):
photo = models.FileField( blank=True, null=True)
project urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^opencmis/', include('opencmis.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_URL)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL)
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
My update form works as it created the media folder and places images in it.
The URL pattern seems to match /media as it doesn't give an error there it just doesn't display the image.
Any ideas?
document_root=settings.STATIC_URL should be document_root=settings.STATIC_ROOT and similar for MEDIA_ROOT. You want the filesystem path in there, not the URL.
– dhke

Django rest framework api - image url is not returning properly

I am facing problem in returned image url, which is not proper.
My return image url is "http://127.0.0.1:8000/showimage/6/E%3A/workspace/tutorial_2/media/Capture1.PNG"
But i need
"http://127.0.0.1:8000/media/Capture1.PNG"
When i click on image_url then image open in new browser tab
But currently its shown error:
view.py
from showimage.models import ShowImage
from showimage.serializers import ShowImageSerializer
from rest_framework import generics
# Create your views here.
class ShowImageList(generics.ListCreateAPIView):
queryset = ShowImage.objects.all()
serializer_class = ShowImageSerializer
class ShowImageDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = ShowImage.objects.all()
serializer_class = ShowImageSerializer
model.py
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
# Create your models here.
class ShowImage(models.Model):
image_name = models.CharField(max_length=255)
image_url = models.ImageField(upload_to=settings.MEDIA)
serializer.py
from rest_framework import serializers
from showimage.models import ShowImage
class ShowImageSerializer (serializers.ModelSerializer):
class Meta:
model = ShowImage
fields = ('id', 'image_name', 'image_url')
settings.py
MEDIA=os.path.join(BASE_DIR, "media")
urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
I am new in python and also in django-rest-framework.
Please also tell me how we extend models or serialize class
You might want to try this in your settings:
MEDIA_URL = '/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, "media")
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in your models:
class ShowImage(models.Model):
image_name = models.CharField(max_length=255)
image_url = models.ImageField(upload_to="") # or upload_to="images", which would result in your images being at "http://127.0.0.1:8000/media/images/Capture1.PNG"
Finally, i solve this road block with the help of
#Remi
Thanks #Remi
But some other change i do so that i elaborate solution and fix this issue.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, "media")
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your code seems correct except one thing you have passed settings.MEDIA in uploads image. you don't need to pass settings.MEDIA in uploads.
try this
image_url = models.ImageField(upload_to='Dir_name')
Dir_name will create when you'll run script.

Categories