I am trying to display the image and name in a for loop on my template.
This is what I have on my template for loop, and I thought it should work, but it doesn't
{% for op in tracked_objects %}
{% if op.is_mine %}
<div style="float:left;">
<div>
<img src="{{ op.tracked_object.image }}" alt="">
<a href='{% url track-profile op.tracked_object.id %}'>{{ op.tracked_object }}</a><br>
</div>
</div>
{% endif %}
{% endfor %}
I know that op.is_mine is true because the Name shows.
Here is my views.py:
#login_required
def profile(request):
user = request.user
tracked_objects = user.tracked_object_perms.all().order_by('is_mine',)
context = {
'tracked_objects':tracked_objects,
}
return render_to_response( 'accounts/profile.html' , RequestContext(request, context))
and finally the models.py
name = models.CharField(max_length='140')
image = models.ImageField(upload_to='img/tracked_object_images', null=True, blank=True)
Update
Now when I use the below anser of adding the .url onto the end, I get three broken image icons. Now I have checked the path and it goes to the correct image. Would this be a server issue possibly? Or something along those lines?
Try:
<img src="{{ op.tracked_object.image.url }}" alt="">
See Using django.contrib.staticfiles.
Related
From my base.html:
<div id="button_container">
<button class="button"> HOME </button>
<button class="button"><a href="{% url 'rooms' %}"> ROOMS & SUITES </button>
<button class="button"><a href="{% url 'roomBookingsList' %}"> ROOM BOOKINGS </button>
</div>
Urls.py:
path('rooms/mybooking', views.roomBookingsList, name='roomBookingsList'),
Views.py:
def roomBookingsList(request):
suiteBookingList = Suite_booking.objects.all()
context = {
'suiteBookingList': suiteBookingList,
}
return render (request, 'roomBookingsList.html', context=context)
roomBookingsList.html:
{% for suiteBookingList in suiteBookingList %}
<li> {{ suiteBookingList }}</li>
{% endfor %}
So when I run it and click the ROOM BOOKINGS from the base.html, it will show me whatever rooms I have booked. No problem here. I also want to add an edit button here so I can update the booking if I accidentally typo the name or something.
So I added in the roomBookingsList.html:
{% for suiteBookingList in suiteBookingList %}
<li> {{ suiteBookingList }}</li> - Edit
{% endfor %}
Added in urls.py:
path('rooms/suite/edit/<int:suite_id>', views.edit_suite, name='edit_suite'),
Added in views.py:
def edit_suite(request, suite_id):
if request.method == 'POST':
suite = Suite_booking.objects.get(pk=suite_id)
form = BookingForm(request.POST, instance=suite)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('roomBookingsList'))
else:
suite = Suite_booking.objects.get(pk=suite_id)
fields = model_to_dict(suite)
form = BookingForm(initial=fields, instance=suite)
context = {
'form': form,
'type': 'edit',
}
return render(request, 'roomBookingsList.html', context=context)
Then I tried to run it again, and this time when I click the ROOM BOOKINGS button, it gave an error:
NoReverseMatch at /system/rooms/mybooking
Reverse for 'edit_suite' with arguments '('',)' not found. 1 pattern(s) tried: ['system/rooms/suite/edit/(?P<suite_id>[0-9]+)$']
In the traceback there's this:
D:\ssip\hotel\system\views.py, line 59, in roomBookingsList
59. return render (request, 'roomBookingsList.html', context=context)
I tried searching all the files I used for the ('',) but didn't find any. I also looked over my def roomBookingsList but didn't find anything odd in it. I already tried searching the error but most answers were OP forgetting the dot or underscore when passing args.
Is it because I'm calling Suite_booking object in both the def roomBookingsList and edit_suite? What should I change here?
Sorry it's long and thank you in advance.
It seems like suite.id does not exist. Shouldn't it be suiteBookingList.id instead?
{% for suiteBookingList in suiteBookingList %}
<li> {{ suiteBookingList }}</li> - Edit
{% endfor %}
And though it works, I would recommend not using the same name as your variable to iterate:
{% for suite in suiteBookingList %}
<li> {{ suite }}</li> - Edit
{% endfor %}
I am displaying django models on one of my website's pages. When I press one's ImageField on the page, I want it to open another page including only that one object. How do I do that ?
I thought about using the filter method in my views.py for filtering through my objects and finding that exact one, but I don't know what arguments to use.
Any ideas? (I am a beginner in django)
VIEWS.PY
from django.shortcuts import render
import requests
from . import models
def index(request):
return render(request, 'base.html')
def new_search(request): ********NOT IMPORTANT (I THINK)********
search = request.POST.get('search')
models.Search.objects.create(search=search)
objects = models.Object.objects.all()
results = objects.filter(name__contains=search).all()
args = { 'results': results }
return render(request, "my_app/new_search.html", args)
def individual_page(request):
link = request.GET.get('object-link')
objects = models.Object.objects.all()
return render(request, "my_app/individual_page.html")
MY TEMPLATE
{% extends "base.html" %}
{% block content %}
{% load static %}
<h2 style="text-align: center">{{ search | title }}</h2>
<div class="row">
{% for result in results %}
<div class="col s4">
<div class="card medium">
<div class="card-image">
<a name="object-link" href="{% url 'individual_page' %}"><img src="{{ result.image.url }}" alt=""></a>
</div>
<div class="card-content">
<p>{{result.name}}</p>
</div>
<div class="card-action">
View listing: Price TEST
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
So, the thing I want to do is: when I press the anchor tag that includes the image, I get redirectioned to another page which contains only that one object's info.
anyone can help me with python django models, here is my code
models.py
class honeymoon(models.Model):
locationh = models.CharField(max_length=100)
imgh = models.ImageField(upload_to='locations')
detailh = models.TextField()
def __str__(self):
return self.locationh
views.py
def top10_honeymoon(request):
context = {
'posth': honeymoon.objects.all()
}
return render(request,'shop/honeymoon.html',context)
html
<div class="blog_list">
<h1 class="blog_heading"> Top 10 Destination For Honeymoon</h1><br><br>
<h2 class="blog_location">{{ posth.locationh }}</h2><br>
<img class="blog_img" src="{{ posth.imgh.url }}"><br>
<p class="blog_details">{{ posth.detailh }}</p><br><br>
</div>
admin.py
admin.site.register(honeymoon)
i'm trying to make model and trying to add some items from admin blog but its not displaying anything in my site, and not even showing the error. data is uploading from admin panel but its not displaying
you have to loop through the instances to see it
{% for obj in posth %}
<h2 class="blog_location">{{ obj.locationh }}</h2><br>
<img class="blog_img" src="{{ obj.imgh.url }}"><br>
<p class="blog_details">{{ obj.detailh }}</p><br><br>
{% endfor %}
try this :
<div class="blog_list">
<h1 class="blog_heading"> Top 10 Destination For Honeymoon</h1><br><br>
{% for post in posth.all %}
<h2 class="blog_location">{{ post.locationh }}</h2><br>
<img class="blog_img" src="{{ post.imgh.url }}"><br>
<p class="blog_details">{{ post.detailh }}</p><br><br>
{% endfor %}
</div>
Django cannot iterate itself. that's why you enable to show data.
You have to use for loop to show data in webpage
<div class="blog_list">
<h1 class="blog_heading"> Top 10 Destination For Honeymoon</h1><br><br>
{% for item in posth %} # add this
<h2 class="blog_location">{{ item.locationh }}</h2><br>
<img class="blog_img" src="{{ item.imgh.url }}"><br>
<p class="blog_details">{{ item.detailh }}</p><br><br>
{% endfor %} # add this
</div>
In my blog app I want to display an image in the post's details. But the tricky part is that I want to display the image corresponding to the first letter of the user's first name. For example if the user's name is "Sam" I want to display the letter 'S' image. I tried to add all letters avatars in static folder.And i tried
<!--code for displaying image from database--->
{% if post.author.profile.image.url is None %}
<img src="{% static 'images/{{letter}}.png' %}" class='logo3'/>
{% else %}
<img src="{{ post.author.profile.image.url }}" class='logo3'/>
{% endif %}
views.py
def homepage(request):
l=[]
post= Post.objects.all().order_by('-date')
ctr= post.count()
print(ctr)
for i in range(0,ctr):
letter = post[i].author_id[0].lower()
l.append(letter)
return render(request,'layout.html',{'posts':post,'letter':l})
models.py
class Post(models.Model):
title=models.CharField(max_length=100)
desc=models.TextField()
date=models.DateTimeField(auto_now=True)
author=models.ForeignKey(settings.AUTH_USER_MODEL,
to_field="username",on_delete=models.CASCADE)
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(default=None,upload_to='pics')
In my browser if i click on inspect in img tag the src displaying is /media/None
The simplest way to display images according to the user's first name is create a div instead of an image with rounded corners.
{% if post.author.profile.image %}
<img src="{{ post.author.profile.image.url }}" class='logo3'/>
{% else %}
<div class="text-center align-center" style="align-items:center !important;justify-content:center !important;background-color: black;width: 50px;height: 50px;border-radius: 50px">
<p style="padding-top: 25%" >{{ post.author.username.0 }}</p>
</div>
{% endif %}
{{ post.author.username.0 }} will give you the first letter of username
You are accessing author by post.author object, so just do post.author.username.0 in your template, you don't need that list of letters in context. name.0 in Django templates corresponds to name[0] in Python.
Edit: set to username field, the alternatives are first_name and last_name.
I have a question,this is my code
When uploade image success,It will return all data (item=Item.objects.all()) and show on the template
What if I only want the picture which is just uploaded by user to show on template(not all images in database),how can I do this?
Please guide me !
Thank you very much.
views.py
def background(request):
if request.method=="POST":
img = ItemForm(request.POST, request.FILES)
if img.is_valid():
img.save()
return HttpResponseRedirect(reverse('imageupload:background'))
img=ItemForm()
item=Item.objects.all()
return render(request,'uploader/background.html',{'form':img,'item':item,})
models.py
from sorl.thumbnail import ImageField
class Item(models.Model):
image = ImageField(upload_to='thumb/')
class ItemForm(forms.ModelForm):
class Meta:
model = Item
templates:
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form}} <input type="submit" value="Upload" />
</form>
{% for i in item%}
{{i.image}}
{% thumbnail i.image "1024" crop="center" format="PNG" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
{% endfor %}
It would be better if you add a field that can be used to keep track of your latest uploaded Image.
class Item(models.Model):
image = ImageField(upload_to='thumb/')
upload_time = models.DateTimeField(auto_now=False, auto_now_add=True)
Here I have added one more feild named upload_time with parameter auto_now_add=True.
DateField.auto_now_add
Automatically set the field to now when the object is first created.
Useful for creation of timestamps. Note that the current date is always used;
it’s not just a default value that you can override.
After that you can get the latest object from Item model using latest method.
def background(request):
if request.method=="POST":
img = ItemForm(request.POST, request.FILES)
if img.is_valid():
img.save()
return HttpResponseRedirect(reverse('imageupload:background'))
img=ItemForm()
item=Item.objects.latest('upload_time')
return render(request,'uploader/background.html',{'form':img,'item':item,})
About latest:
latest(field_name=None)
Returns the latest object in the table, by date, using the field_name provided as the date field.
So you will be getting single object then it would not be required to iterate it in your template.
{{item.image}}
{% thumbnail item.image "1024" crop="center" format="PNG" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
You can have the id there when save. Just set the id in session. So when redirecting you can have the id of that photo & user also like ...
photoId = request.session['photoId']
userId = request.session['_auth_user_id']
item=Item.objects.get(pk=photoId) #you can also use filter by userId
Code:
if img.is_valid():
img.save()
request.session['photoId'] = img.id
return HttpResponseRedirect(reverse('imageupload:background'))
You don't have to use the session and redirect or add any extra field. The ModelForm save() method returns the object just saved. Try this:
# views.py
def background(request):
form = ItemForm(request.POST or None, request.FILES or None)
item = None
if request.method=="POST" and form.is_valid():
item = form.save()
return render(request,'uploader/background.html',{'form': form,'item': item,})
# template
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form}} <input type="submit" value="Upload" />
</form>
{% if item %}
{{ item.image }}
{% thumbnail item.image "1024" crop="center" format="PNG" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
{% endif %}
I did something slightly different. My view renders a graph figure (an image) dynamically each time so it is not in the database. But to embed a single instance of a graph from my models this is what I did:
First, I made a view that renders the graph from my data and created a url that goes to it (selected by using it's id):
url(r'^graphs/graphImage/(?P<graph_id>\d+?)/$', 'hydro.views.render_graph', name='graphImage'),
no need to show my view, but if i went to that url my view would be called and it would render the graph and only the graph. Similar to most sites where if you click on the picture you just get a webpage showing only the picture.
Now working with this url:
url(r'^graphs/(?P<graph_id>\d+?)/$', 'hydro.views.single_graph', name='graph_detail'),
this view brings up a template with this bad boy:
{% url 'graphImage' graph.id as the_graph %}
<img src="{{the_graph}}" alt="{{the_graph}}"/>
the url portion grabs my graphImage url and inputs the graph.id with it. And then I name it the_graph to keep it simple.
then i make an image tag as the src as the _graph. Don't worry about alt it just shows the url if it doesnt work for debugging.
So what I did was render a graph on one webpage and just use that as a source for an image tag. Theres a million ways to do this sort of thing, but this was the most obvious with my limited skills and just knowing about html and django.