How to get link to download file in pdf? (Django) - django

I have the following structure in the details.html
<p>Files:
{% for file in files %}
<p>{{ file.name }}</p>
{% endfor %}
</p>
This link returns the correct url.
http://localhost/media/file.pdf
However, every time I click, instead of downloading the file, it returns error 404.
What is the correct way to do this operation?

<p><a href="{{ file }}" download>{{ file.name }}</a></p>
if you try to query to on database and print in client side, so in your anchor link write a right path
example:
<p><a href="/media/{{ file }}" download>{{ file.name }}</a></p>

Is this on the local development server or in production?
My guess is you haven't configured Django to serve /media/ files.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
However, do note the admonition in the documentation:
This is not suitable for production use!

Related

media image is not able to display on webpage

when click on "yo" I am able to see media file but when tried to display image through the image tag it is not seen on webpage
yo
<img src="{{status.adv.url}}" width="250" height="250" alt="advertise"/>
Change this
<img src="{{status.adv.url}}" width="250" height="250" alt="advertise"/>
to
<img src="{% static status.adv.url %}" width="250" height="250" alt="advertise"/>
and include {% load static %} template tag on the top of your template(s)
Your project url.py should have these
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)
Documentation: Managing static files (e.g. images, JavaScript, CSS)
It was add blocker used by me. so disable your add blocker.
If you want to confirm that it is add blocker open your chrome and in console you will find this "Failed to load resource: net::ERR_BLOCKED_BY_CLIENT"

Find if static file exists before calling in deployment - Django

In production I am able to run:
#views.py
from django.contrib.staticfiles import finders
result = finders.find(f'Images/{var}')
context = {"r", results}
#template.html
{% if r %}
{% with 'Images/'|add:var as var %}
<img src="{% static var %}">
{% endwith %}
{% endif %}
However, now that my files are being stored in Google's buckets finders.find(f'Images/{var}') keeps returning False and my images aren't being displayed. I need a way to test if files exists prior to calling them to avoid displaying empty boxes when a variable's image does not exist.
Incase there's a way to search through the remote buckets, here is my settings.py configuration:
#settings.py
. . .
STATIC_URL = http://storage.googleapis.com/env("BUCKET")/static/
STATIC_ROOT = http://storage.googleapis.com/env("BUCKET")/static/
you could use request lib:
import request
r = requests.head(file_url)
if r.status_code == 200:
do something...
but that's gonna cost you a lot (I mean response time, not money)
better solution would be using JS, something like this (this is jquery):
<script>
$("img").on("error", function () {
//$(this).attr("src", "broken.gif"); // set default pic
$(this).hide(); // hide img
});
</script>
That way you can hide or change all images in the page, when it doesn't load
After looking through a bunch of websites (mostly SO,) I found this solution really helpful:
{% with 'Images/'|add:var as var %}
<img src="{% static var %}" class="img" onerror="this.onerror=null;this.style.display='none';src='';this.class='';" />
{% endwith %}

Django template is adding its name to path of image, preventing image from being found

I am working with images uploaded using ImageFields and upload_topath and name, and these images end up in the correct directory media/img/whatevs/. In my settings.py I have the following two lines.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Now, in the template that matches my / URL, these images display properly and I can see/inspect that the path ends up pointing correctly to media/img/whatevs/imgname.jpg
However, when I want to display these images in another template called product.html that does not match the / url, then the path ends up pointing to product/media/img/whatevs/imgname.jpg instead of to media/img/whatevs/imgname.jpg, resulting in a 404. Somehow the name of the template is added to the img src path automatically. If I inspect it I see that the text points to media/img/whatevs/imgname.jpg but then if I hover my mouse over it I end up seeing this http://127.0.0.1:8000/product/media/img/whatevs/imgname.jpg.
For clarity I add what I have in my files:
urls.py
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('product/<slug>', ItemDetailView.as_view(), name='product'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
class Item(models.Model):
image = models.ImageField(upload_to=get_image_upload_path)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
product.html, where it does not display
<img src='media/img/whatevs/{{ item.slug }}' class="img-fluid" alt="">
home.html, where it displays properly
<img src='media/img/whatevs/{{ item.slug }}' class="card-img-top" alt="">
I am working with Django 3.0.6 in debug mode.
Any clue what I am doing wrong and why the template name is added to the path and how to prevent it?
The reason why it works on homepage and not in the other pages is because HTML anchors paths are relative since they are missing a slash(/) at the beginning. But still it is best practice to you link Item.image this way:
<img src='{{ item.image.url }}' class="img-fluid" alt="">
if you uploaded images and you configured settings settings.py well and also your urls.py do there is no need of force you html to found the images like this
<img src='media/img/whatevs/{{ item.slug }}' class="img-fluid" alt="">
you have to do it like this
<img src='{{ item.slug.url }}' class="img-fluid" alt="">
this will work better
The problem is you use relative paths in the template, instead of this:
<img src='media/img/whatevs/{{ item.slug }}' class="img-fluid" alt="">
you should have that:
<img src='/media/img/whatevs/{{ item.slug }}' class="img-fluid" alt="">
It would be a good idea to have the model return full path, it's not a good practice to put the paths in the template.

Django Reason for getting TemplateSyntaxError?

I have created a new app called newsletters. I can access the pages when I write their location directly from local host by writing
http://127.0.0.1:8000/newsletters/signup/
but when I try to add their url in the nav bar I am getting an error:
TemplateSyntaxError at /
Invalid block tag on line 40: 'url'newsletters:subscribe''. Did you forget to register or load this tag?
Here are the main project urls:
urlpatterns = [
path('admin/', admin.site.urls),
path('newsletters/', include('newsletters.urls', namespace='newsletters')),
]
Here are newsletters app urls:
app_name = 'newsletters'
urlpatterns = [
path('signup/', newsletter_signup, name="subscribe"),
path('unsubscribe/', newsletter_unsubscribe, name='unsubscribe'),
]
here are the nav bar template:
<div class="dropdown-divider"></div>
<a class="dropdown-item" href=" {% url'newsletters:subscribe' %}">Newsletters</a>
<div class="dropdown-divider"></div>
How should I fix it and what am I have I done wrong to avoid it?
You're missing a space after url in your url tag:
{% url 'newsletters:subscribe' %}

Resolve Static URL on Server

All of my user's have the option to link a profile picture. There are several templates that need to load this profile picture. If the user has not uploaded a picture, we use a default. When I want to display this profile picture, my code looks like this
<img src="{% if user.profile_picture.search_thumbnail.url %}{{ user.profile_picture.search_thumbnail.url }}{% else %}{% static "alternate.jpg" %}{% endif %}">
This is way too verbose for me, especially considering I need to repeat it out in multiple templates. I could use {% with %} blocks to store user.profile_picture.search_thumbnail.url, but that won't help me too much.
My solution was to write a function attached to the user model that returns the url of the static file. Unfortunately, the {% static %} is a template function. {% url %} has an equivalent function on the server called django.core.urlresolvers.reverse(). Does the alternative thing exist for the {% static %} tag?
In case anyone asks, I want to use the static function because my static files are stored in different places depending on the environment. My dev machine serves files locally, while my PRD machine serves static files from s3.
Thank you,
Nick
why not write a filter so you can do this.
<img src="{{ user.profile_picture.search_thumbnail.url|custom_filter }}">
and in the custom_filter you read from the settings.STATIC_URL to return the correct URL the user one is not set.
you could make the filter even shorter like this
<img src="{{ user|user_pic_url }}">
and in the filter pull out the .profile_picture.search_thumbnail.url /checks
This is what the static templatetag does underneath, and you can use it just fine in your own code:
from django.contrib.staticfiles.storage import staticfiles_storage
def static(path):
return staticfiles_storage.url(path)