Creating a detail view for images

We will now create a simple detail view to display an image that has been saved into our site. Open the views.py file of the images application and add the following code to it:

from django.shortcuts import get_object_or_404
from .models import Image

def image_detail(request, id, slug):
image = get_object_or_404(Image, id=id, slug=slug)
return render(request,
'images/image/detail.html',
{'section': 'images',
'image': image})

This is a simple view to display an image. Edit the urls.py file of the images application and add the following URL pattern:

path('detail/<int:id>/<slug:slug>/',
views.image_detail, name='detail'),

Edit the models.py file of the images application and add the get_absolute_url() method to the Image model, as follows:

from django.urls import reverse

class Image(models.Model):
# ...
def get_absolute_url(self):
return reverse('images:detail', args=[self.id, self.slug])

Remember that the common pattern for providing canonical URLs for objects is to define a get_absolute_url() method in the model.

Finally, create a template inside the /images/image/ template directory of the images application and name it detail.html. Add the following code to it:

{% extends "base.html" %}

{% block title %}{{ image.title }}{% endblock %}

{% block content %}
<h1>{{ image.title }}</h1>
<img src="{{ image.image.url }}" class="image-detail">
{% with total_likes=image.users_like.count %}
<div class="image-info">
<div>
<span class="count">
{{ total_likes }} like{{ total_likes|pluralize }}
</span>
</div>
{{ image.description|linebreaks }}
</div>
<div class="image-likes">
{% for user in image.users_like.all %}
<div>
<img src="{{ user.profile.photo.url }}">
<p>{{ user.first_name }}</p>
</div>
{% empty %}
Nobody likes this image yet.
{% endfor %}
</div>
{% endwith %}
{% endblock %}

This is the template to display the detail of a bookmarked image. We make use of the {% with %} tag to store the result of the QuerySet, counting all user likes in a new variable called total_likes. By doing so, we avoid evaluating the same QuerySet twice. We also include the image description and iterate over image.users_like.all to display all the users who like this image.

Using the {% with %} template tag is useful to prevent Django from evaluating QuerySets multiple times.

Now, bookmark a new image using the bookmarklet. You will be redirected to the image detail page after you post the image. The page will include a success message, as follows:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.204.201