Django Show Image in HTML - html

I am new to Django and want to show an image in HTML which is identified by an item's link being clicked in a table. The ID is given when a link is clicked. HTML:
<div id="link-product">
<a id= "product-clicked" href="/prod_details/{item.id }}"> {{ item.product }}
</a>
</div>
VIEWS:
def list_details(request,info_id):
active_user = request.user
product_image = Item_Model.objects.values_list('image').filter(id=info_id)
return render(request,'prod_details.html', {'active_user': active_user, 'product_image': product_image})
Then it will go to the next page and the HTML should receive that item's ID and display its image accordingly. HTML:
<div id="info-box-container">
<img id= "product-image" src = "{{ MEDIA_URL }}{{ product_image }}" />
</div>
But when I do this, the image does not show. I am definitely missing some process. How can I get this to work as desired?

values_list returns a list of tuples but not the single value. Change your query to:
product_image = Item_Model.objects.filter(id=info_id) \
.values_list('image', flat=True).first()

Related

Using a dynamic name for image source in Angular

I have some decks of cards.
I want to display a specific image for each deck, I have an assets folder with all my images.
<div class="decks">
<div *ngFor="let deck of decks" class="deck">
<img
src="../../assets/img/MAGE.png"
MAGE is just an exemple of a deckClass, that name should match deck.deckClass
class="img-responsive"
style="height: 200px;">
<h4> {{deck.deckName}} : {{deck.deckClass}} </h4>
<p *ngFor="let card of deck.deckCards" >
{{ card.name }} : {{ card.manaCost }}
</p>
</div>
</div>
How can I concatenate in a src attribute the deck.deckClass name in a dynamic way?
Consider using the Expression Context
You can wrap the sry attribute with square brackets, this way Angular will know to evaluate the value:
[src]="'../../assets/img/' + deck.deckClass '.png'"
See a demo here: https://stackblitz.com/edit/angular-ua9cfc
I don't have images in there, so they will be shown as broken img's in the demo ...
p.s.: if those images are in your src/assets/ folder, then this should suffice:
[src]="'assets/img/' + deck.deckClass '.png'"

Django ImageField not render at <img> tag HTML

# models.py
from django.db import models
from . import constants
class Photos(models.Model):
band_member = models.ForeignKey(BandMember,on_delete=models.CASCADE)
photo = models.ImageField(upload_to='media/')
photo_description = models.TextField(max_length=400)
class Photos(models.Model):
band_member = models.ForeignKey(BandMember,on_delete=models.CASCADE)
photo = models.ImageField(upload_to='media/')
photo_description = models.TextField(max_length=400)
#property
def photo_url(self):
if self.photo and hasattr(self.photo, 'url'):
return self.photo.url
# views.py
def member_photos(request,member_id):
current_member = BandMember.objects.get(pk=member_id)
photos = current_member.photos_set.all()
context = {
'all_photos': photos,
'current_member': current_member,
}
return render(request,'band_members/member_photos.html', context)
html file :
{% if all_photos %}
{% for foto in all_photos %}
<img class"" src="{{ foto.photo_url }}"
alt = {{foto.photo_url }}">
<h5>{{ foto.photo_description }}</h5>
{% endfor %}
Although , image is not displayed , alt displays the correct path of the file
What am i doing wrong ?
What i'm trying to achieve , is when user clicks on a 'SHOW PHOTOS' button at a page containing informations about a specific band member
(site/band_member/member_id here ), another page loads (site/band_member/member_id/photos) , displaying all the photos of the current member.
NEW TO DJANGO !!!
Thank you !
sorry for my 'bad english' language :)
The html inside the loop is not correct. Try fixing that like this.
<img src="{{ foto.photo_url }}" alt ="{{foto.photo_url }}">
<h5>{{ foto.photo_description }}</h5>

Passing variable name into {{ }} flask [duplicate]

This question already has an answer here:
Reference template variable within Jinja expression
(1 answer)
Closed 4 years ago.
I want to get image name from database and make it display at html file by this code
<img src="{{ url_for('static', filename='img/{{rows.infor_image}}') }}" style="width:50%; height:60%;">
but I dont know how to write in the correct syntax to get image to be display
I try to declare image_name in .py file but I dont know how to use it
#app.route('/herbsinfo/<id>')
def landing_page(id):
cur = mysql.connection.cursor()
#Query
cur.execute('SELECT version()')
result = cur.execute("SELECT * FROM information where infor_id = %s",[id])
rows = cur.fetchone()
image_name = rows['infor_image']
if result > 0:
return render_template('herbsinfo.html', rows=rows,image_name=image_name)
or I can display image in other way
Try this :
<img src="{{ url_for('static', filename='img/'+image_name) }}" style="width:50%; height:60%;">
or
<img src="{{ url_for('static', filename='img/'+rows.infor_image) }}" style="width:50%; height:60%;">
You don't need to add extra {{ }}

Replacing image with CSS on Django if/else statement

I am trying to create a voting system similar to that of stackoverflow, but I can't figure out how to call on the css instead of the images.
I have the following code:
<input type="image" id="uparrow{{ vote.id }}" src="{{ MEDIA_URL }}static/img/aup{% if vote and vote.is_upvote %}mod{% else %}grey{% endif %}.PNG">
How can I change the code so it calls a css class instead of an img src?
You are looking for something like:
<input type="image" id="uparrow{{ vote.id }}"
src="{{ MEDIA_URL }}static/img/vote.png"
class="otherclass {% if vote and vote.is_upvote %}upvote{% else %}novote{% endif %}" />
The image would have classes "otherclass" and "upvote" in one case, "otherclass" and "novote" in the other.

Create hyperlink in django template of object that has a space

I am trying to create a dynamic hyperlink that depends on a value passed from a function:
{% for item in field_list %}
<a href={% url index_view %}{{ item }}/> {{ item }} </a> <br>
{% endfor %}
The problem is that one of the items in field_list is "Hockey Player". The link for some reason is dropping everything after the space, so it creates the hyperlink on the entire "Hockey Player", but the address is
http://126.0.0.1:8000/Hockey
How can I get it to go to
http://126.0.0.1:8000/Hockey Player/
instead?
Use the urlencode filter.
{{ item|urlencode }}
But why are you taking the name? You should be passing the appropriate view and PK or slug to url which will create a suitable URL on its own.
Since spaces are illegal in URLs,
http://126.0.0.1:8000/Hockey Player/
is unacceptable. The urlencode filter will simply replace the space with %20, which is ugly/inelegant, even if it does kind of get the job done. A much better solution is to use a "slug" field on your model that represents a cleaned-up version of the title field (I'll assume it's called the title field). You want to end up with a clean URL like:
http://126.0.0.1:8000/hockey_player/
To make that happen, use something like this in your model:
class Player(models.Model):
title = models.CharField(max_length=60)
slug = models.SlugField()
...
If you want the slug field to be pre-populated in the admin, use something like this in your admin.py:
class PlayerAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
....
admin.site.register(Player,PlayerAdmin)
Now when you enter a new Player in the admin, if you type "Hockey Player" for the Title, the Slug field will become "hockey_player" automatically.
In the template you would then use:
{% for item in field_list %}
<a href={% url index_view %}{{ item.slug }}/> {{ item }} </a> <br>
{% endfor %}
There is this builtin filter .
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#urlencode
Although you should be using one of these
http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield