simple gravatar not displaying in django template - django

I took reference from this site:
http://tomatohater.com/2008/08/16/implementing-gravatar-django/
I have profile app that has templatetags directory with a mytags.py in it.
Contents of mytags.py
import urllib, hashlib
from django import template
register = template.Library()
#register.inclusion_tag('templatetags/gravatar.html')
def show_gravatar(email, size=48):
default = "http://www.mysite.com/media/images/no-avatar.gif"
url = "http://www.gravatar.com/avatar.php?"
url += urllib.urlencode({
'gravatar_id': hashlib.md5(email).hexdigest(),
'default': default,
'size': str(size)
})
return {'gravatar': {'url': url, 'size': size}}
Contents of templates/templatetags/gravatar.html
<img src="{{ gravatar.url }}" width="{{ gravatar.size }}" height="{{ gravatar.size }}" border="0" />
The tag is utilized in profile.html template file.
But the gravatar is not displayed in profile.html. However the source shows
<div class="gravatar">
<a href="">
<img src="http://www.gravatar.com/avatar.php?default=http%3A%2F%2Fwww.mysite.com%2Fmedia%2Fimages%2Fno-avatar.gif&size=48&gravatar_id=5d1b0b64499475516bd9c051aa7f3560" width="48" height="48" border="0" />
</a></div>

<img src="{{ gravatar.url|safe }}" width="{{ gravatar.size }}" height="{{ gravatar.size }}" border="0" />
Safe template filter prevents auto-escaping &

When I try the image URL, gravatar doesn't recognize the hashed email address, so it redirects to the fallback image that you provided: http://www.mysite.com/media/images/no-avatar.gif
Is it correct that you get the fallback? Or did you expect a real gravatar? If so, the error is in the hash somehow.
mysite.com is obviously not your site. But, did you in reality use the correct URL?
A hardcoded URL: are you using the correct hostname? The correct MEDIA_URL from your settings.py?

Refs the doc, always lower and strip the email.
Also, use 'http://www.gravatar.com/avatar/'+hash instead of the legacy format.
Then the code looks like
url = 'http://www.gravatar.com/avatar/%s?%s" % (
hashlib.md5(email.strip().lower()).hexdigest(),
urllib.urlencode({'default': default, 'size': size}))
For you code, its highly probably that email hash does not match anything. I tried my avatar using the format in your code, it works well. Has the email been registered?

Related

How to display images from other places in django template

I am fairly new in Django and developing a book recommendation system using Django and PostgreSQL. I have my dataset with some field that also keeps corresponding book images URL (not the images itself) where images reside in other places, not in my static files or database. i want to access that images online and display them in my Django template here is how I tried to do but didn't work and doesn't access the image.
<img src= {{ book.image_url.url }} style="display:block;" width="100%" height="100%" alt="">
and also tried this:
<img src="{{ book.image_url.url }}" style="display:block;" width="100%" height="100%" alt="">
where book is dictionary and images_url is simply a url string for image residing somewhere in the web.
can you help me out how to access this string of url on the web and display it on django template ?
For urls, you want to use a different template tag. Try this:
<img src="{% url book.image_url.url %}" style="display:block;" width="100%" height="100%" alt="">

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.

URLField appending to 'http://127.0.0.1:8000/'

I have a ULRField that I'm trying to link using href but when I click it I am takn to something like http://127.0.0.1:8000/www.example.com rather than www.example.com
models.py
class Website(models.Model):
website = models.URLField(max_length=100)
template.html
<a href="{{ dealer.website }}">{{ dealer.website }}</p>
Moving my comment to an answer:
Save the value with the https:// protocol.

Django create path to an image file

I have a normal app that has a directory structure similar to the following:
...static/
Training/
css/
img/
js/
...templates/
....
Within one of my templates, I would like to get the image name from the database and build the path to the image. For example, if I had the image MyPicture.jpg, then I would like to include static and combine this with 'Training/img/' and the file name to get something like
'..path to static../Training/img/MyPicture.jpg'
I found the following article that suggested using template tags, so I have tried this:
from django import template
register = template.Library()
#register.filter
def addstr(arg1, arg2):
# Apparently, add has side effects, so use this:
# https://stackoverflow.com/questions/4386168/how-to-concatenate-strings-in-django-templates
return str(arg1) + str(arg2)
With the template:
{% with static|addstr:"Training/img/"|addstr:course.img as imgpath %}
<img class="card-img rounded-lg rounded-top" src="{{ imgpath }}" alt="Card image">
{% endwith %}
This is unfortunately leaving out the static part of the address.
How do I combine all three parts ?
[p.s. I have a {% load static %} at the top of the template ]
Thanks
Mark
if you wanna show the absolute full url, this is what you need:
{{request.scheme}}://{{request.META.HTTP_HOST}}{{object.filefield.url}}
but if you just need to show the file, you can use this:
<img class="card-img rounded-lg rounded-top" src="{{ object.filefield.url }}" alt="Card image">
Silly mistake really. All I needed to do was separate out the static and not treat it like a string. This works:
"{% static 'Training/img/'|addstr:course.img %}"

How to let the django thumbnail show me image?

Currenlty,I have learn django from the http://www.lightbird.net/dbe/photo.html and I meet a problem!I want show the thumbnail image on the 'Thumbnail item' but it's just show the html code:
<a href="/photos/1414.jpg><img border="0" alt="" src="/photos/1414.jpg" height="40"/></a>
I have define the class Image method like below:
def thumbnail(self):
return """<a href="/%s><img border="0" alt="" src="/%s" height="40"/> """ % ((self.image.name,self.image.name))
The attribute of Class Image have define like that:
class Image(Models.Model):
#The rest of another code
image=models.ManyToManyField(upload_to="photos/")
#....another code ..
I have check my path have create a photos on my project 'myweb/photos/'
How can i let the page understand it's html code .
First, I have no idea why you're using a ManyToMany field for this use case. You need to be using an ImageField.
The field you define as an ImageField will have a url property, which is what you use to reference the relative path to the file.
Second, don't mix HTML and Python in your model class. Django has templating specifically for this use case:
from django.template.loader import render_to_string
class Image(models.Model):
image = models.ImageField(upload_to='photos')
alt = models.CharField(max_length=100)
def thumbnail(self):
return render_to_string('thumbnail.html', {'image': self})
# thumbnail.html
<img src="{{ image.image.url }}" alt="{{ image.alt }}" ... />
Keep in mind that artificially scaling a full-size image to 40x40 pixels to generate a thumbnail is horribly inefficient, and if there are lots of these, will absolutely crush performance.
As others have mentioned, you can use excellent libraries like django-easy-thumbnails or sorl-thumbnail to generate proper, scaled down, optimized versions of these images at whatever dimensions you need.
please follow the tutorial on djangoproject.com ..the code on your link is not a right way use django,close it and read official docs
Use the url attribute instead of the name attribute on the image:
def thumbnail(self):
return """<a href="/%s><img border="0" alt="" src="/%s" height="40"/> """ % ((self.image.url,self.image.url))
There is also the excellent tool sorl-thumbnail. It helps with dynamically generating thumbnails in your templates. Install it with pip install sorl-thumbnail. You can use it like this:
template.html
{% load thumbnail %}
{% thumbnail item.image "100x100" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}