Django Admin: Determine correct image upload path - python

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)

Related

Django wont upload images to media directory

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

How to add poll code to the django-cms url.py file?

I am new to Django-cms but I couldn't add the poll URL code to the url.py file. I follow every step in the Django-cms documentation but I still couldn't succeed can anyone help me with it.
This the documentation of the Django-cms:
integrating_applications
" Install the application from its GitHub repository using pip:
pip install git+http://git#github.com/divio/django-polls.git#egg=polls
Let’s add this application to our project. Add 'polls' to the end of INSTALLED_APPS in your project’s settings.py (see the note on The INSTALLED_APPS setting about ordering ).
Add the poll URL configuration to urlpatterns in the project’s urls.py:
urlpatterns += i18n_patterns(
re_path(r'^admin/', include(admin.site.urls)),
re_path(r'^polls/', include('polls.urls')),
re_path(r'^', include('cms.urls')),
)
Note that it must be included before the line for the django CMS URLs. django CMS’s URL pattern needs to be last, because it “swallows up” anything that hasn’t already been matched by a previous pattern. "
I had added the "polls" in the setting into the installation app code. But---
My question is where or how will put this code to the urls.py file. -- my urls.py file looks like this:
from cms.sitemaps import CMSSitemap
from django.conf import settings
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.urls import include, path
admin.autodiscover()
urlpatterns = [path("sitemap.xml", sitemap, {"sitemaps": {"cmspages": CMSSitemap}}),]
urlpatterns += i18n_patterns(
path("admin/", admin.site.urls),
path("", include("cms.urls"))
)
# This is only needed when using runserver.
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += i18n_patterns(
path("admin/", admin.site.urls),
path("polls/", include("polls.urls")),
path("", include("cms.urls"))
)
It will include all the sub-urls that are listed in your other polls/urls.py file under the "mywebsite/polls/" URL. This is the standard Django way to organize your routes: per app.

Django "TemplateView" and "/media/" url conflict

I am writing an SPA with Django 1.11 (switching to 2.0 is no an option), as backend, getting all the data from Django Rest Framework API and I route my app via React routing.
Here is my my main urls.py :
urlpatterns = [
url(r'^api/', include('text_cms.urls')),
url(r'^api/', include('photos_admin.urls')),
url(r'^admin/', admin.site.urls),
url('', TemplateView.as_view(template_name='index.html'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And here is my settings.py file:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media-files/'
The issue is, that the particular url setting
url('', TemplateView.as_view(template_name='index.html'),
is messing up media url, and files uploaded by user cannot be reached by url link, even though they are saved to folder, I just get a 404 error. When I comment my "Template as view" url, delete it or just give it another address, like url('main/') - everything works fine again.
I've tried to serve the template from the other app and registering it in the main urls.py file, but it did not work too
urlpatterns = [
url(r'^', views.IndexView),
]
views.py
def IndexView(request):
return render(request, 'main/index.html', {})
url('', TemplateView.as_view(template_name='index.html'),
You are missing a closing ). It also appears that you url pattern is incorrect as well. Should be
url(r'^$' , TemplateView.as_view(template_name='index.html')),

can't get media files in heroku

I deployed mu project in heroku successfully.
The only problem is that I can't find media files on heroku.
When I type .../media/pic1.png locally , I get the picture in the browser.
But, in heroku,, that gives
Page not found (404)
Request Method: GET
Request URL:
...../media/pic1.png
Raised by: django.views.static.serve
Path ...../media/pic1.png doesn't exist
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
project/urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^admin_platform/', include('admin_platform.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your setting.py should look something like this:-
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')#by doing this there will be media folder in your main directory.
And in your url.py your code should be like this:-
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^admin_platform/', include('admin_platform.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)#this will help to access your media folder.
Hope this help in your project. :-)

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

Categories