django MEDIA_URL changes in child template? - django

I have these URLs in my project .urls:
urlpatterns = patterns('',
(r'^categories/', include('category.urls')),
)
In the categroy app, my category.urls:
urlpatterns = patterns('category.views',
(r'^$', 'category_tree'),
(r'^add/?$', 'category_add'),)
I have this in my settings.py:
MEDIA_URL = "http://localhost:80/media/"
ROOT_PATH = os.path.normpath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(ROOT_PATH, 'templates'),
)
In the project templates directory there is a base template "base.html" with this line:
<link href="{{MEDIA_URL}}css/base.css" rel="stylesheet" />
In my "category" app, I also have templates "category_tree.html" and "category_add.html".
These both extend from base.html:
{% extends "base.html" %}
The blocks in base.html are rendered correctly with content from these two child templates/views.
But the css and images of category_add.html aren't found.
There is a link on categroy_tree.html like this:
<div>Add category</div>
This points to the correct view if clicked. But then the css MEDIA_URL request changes from
http://localhost/media/css/base.css
// (Correct)
to
http://localhost:8000/categories/css/base.css
// (Incorrect)
Why is this happening and what do I have to do to fix this?

The add category view isn't using a RequestContext to render the page, so MEDIA_URL is not sent to the template context.

Related

Problem in loading the logo in different URLs in Django

I have the same html for Tools.html and home.html but I realized the logo can be loaded in this URL:
path('',views.home),
But in this URL I do not see the logo and also the favicon:
path('Tools/', views.Tools ),
http://127.0.0.1:8000/
http://127.0.0.1:8000/Tools/
views:
def Tools(request):
p=product.objects.filter(category__name='Tools')
return render(request,'Tools.html',{'p':p})
def home(request):
p=product.objects.filter(category__name='home')
return render(request,'home.html',{'p':p})
urls:
urlpatterns = [
path('Tools/', views.Tools ),
path('',views.home),
]
the following codes are for favicon and logo in html file:
<link rel="icon" type="image/x-icon" href="static/logo.png">
<img class="img" width="270px" src="static/logo.svg">
Why is this happening?
You should not hardcode static/logo.png, the right way is to use {% static 'logo.png' %}. Then it will always search in your static folder. You just need to start the template with {% load static %}. Assuming, that you have set in settings something like:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
and you keep such files in your_project/static folder it should work for every level on every app.
More info in Django DOCS

can't get image to load

I probably did something stupid but when i upload a image with /admin I can't get it to load.
I made a for loop to get all post's and everything shows except for the image
model:
`class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
image = models.ImageField(upload_to='blog/media/photos')
date = models.DateTimeField()`
template page:
` {% for post in object_list %}
<h5>{{post.title}}</h5>
<img src="{{ post.image.url }}">
<h1>{{ post.image.url }}</h1>
{% endfor %}`
I would imagine it is related to your MEDIA_URL settings. Check the terminal output and look for the request to the image, there is a good chance you've not set that, and/or you've not added the media url handler to your urls.
https://docs.djangoproject.com/en/2.0/howto/static-files/#serving-files-uploaded-by-a-user-during-development
You must set the media folder path in the settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
or add media root on url.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Is there a blog/media/photos folder path and accessable?

saving image files in django model

i want to store a lot of images in a table(model of django) under an attribute 'imgsrc'. How do i do that? i have seen a lot of online material but i am not getting the complete information anywhere. What changes do i need to do in settings.py and where do i store my image files?...
a part of models.py
class elementdetails(models.Model):
sid=models.IntegerField()
imgsrc=models.ImageField()
soundsrc=models.FileField()
sounddesc=models.CharField(max_length=20)
Setup MEDIA_ROOT and MEDIA_URL in you settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
In your urls.py, add:
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)
Make sure to have media directory in your root directory.
Now, you can also use uploaded_to in your model for storing those images in a directory.
class elementdetails(models.Model):
sid=models.IntegerField()
imgsrc=models.ImageField(upload_to='elements/')
soundsrc=models.FileField()
sounddesc=models.CharField(max_length=20)
In order to get the image in templates, use:
<img src="{{ object.imgsrc.url }}" alt="image">
If you want to upload images in forms, make sure to use enctype="multipart/form-data" in template:
<form action="" method="post" enctype="multipart/form-data">
Also, make sure in views, use:
form = Form(request.POST, request.FILES)
It will work.

Displaying uploaded media in a web page

Friends,
I am using Django 1.6 and I have for the last week(!) been trying to display photos on a web page that are uploaded via the Django Admin site.
I know this is a common problem. I have tried reading the documentation, numerous SO questions like this one and this one all without success.
After uploading the image via the Admin site, I can see that the image exists in the following folder:
/home/ian/django/mysite/cars/media/images/1.JPG
However when the page loads (or trying to view the image after uploading them via the Admin Site) I see a 404 error. The source for the image shows the following:
<li><img src="/media/images/1.JPG" height="420"/></li>
The model.py has the following field:
photo = models.ImageField(upload_to='images/')
The urls.py has the following added:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The template is:
{% extends "base.html" %}
<h1>Here</h1>
<p>{{ collectiondetail.title }}</p>
{% for photo in photos %}
<li><img src="{{ photo.photo.url }}" height="420"/></li>
{% endfor %}
{% endblock %}
Finally the settings.py are:
STATIC_ROOT = '/home/ian/django/mysite/cars/static/'
STATIC_URL = '/static/'
MEDIA_ROOT = '/home/ian/django/mysite/cars/media/'
MEDIA_URL = '/media/'
What have I missed?
The urls.py snippet you are using is only for development and will only work in debug mode. Everything you have looks correct so double-check that in settings.py DEBUG = True. From the docs on this feature:
This helper function works only in debug mode and only if the given prefix is local (e.g. /media/) and not a URL
Thanks to everyone for helping out. The default permissions when the files were uploaded were ok.
Finally managed to track down the problem to two settings.
MEDIA_URL was previously set to:
MEDIA_URL = '/media/'
Changed this to:
MEDIA_URL = '/cars/media/'
Changed the following in the urls.py file from
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
And now the images show as expected.

RequestContext returns 404 error for my imagaes?

I stumbled on a silly situation with Django's RequestContext thing. Here is my question:
I stored all my images in my media/uploads file. In my template I'm simply using :
{% for photo in photos %}
<img src="{{gallery_root}}/{{photo.get_name}}" />
{% endfor %}
My view is :
def gallery_view(request):
photos = Photo.objects.all()
return render_to_response('gallery/sampleGallery.html',{'photos':photos},context_instance=RequestContext(request))
In my settings file :
GALLERY_ROOT = os.path.join(MEDIA_ROOT, "media/uploads")
And i have a contextprocessor file which contains:
from django.conf import settings
def gallery_root(request):
return {'gallery_root':settings.GALLERY_ROOT}
When I open my template, the image's path appears however the server gives 404, the path seems correct but django can not serves them.. So what's the reason that I can not see images on my template ?
The image source appears like this :
<img src="/Users/imperium/Desktop/sample/media/uploads/popo.jpg" />
Hey there, it's probably that your media isn't being served propery.
Try something like this in your urls.py file.
# if we're in DEBUG mode, allow django to serve media
# This is considered inefficient and isn't secure.
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.GALLERY_ROOT}),
)
MEDIA_ROOT is the filesystem path to your media, not the URL path. Building on the suggestion from mongoose_za, your template should look like:
{% for photo in photos %}
<img src="/media/{{photo.get_name}}" />
{% endfor %}
Of course, you can define a new constant in settings.py which corresponds to the URL root you've chosen, and use this both in urls.py as well as in your templates.