CRUD in Django, create detail page or show

We are going to create one of the fundamental CRUDs processes in our Django application, which is to display a detail page (the Read or show); for this, we are going to need to do 3 steps

  1. Create the function in the view, views.py of our app.
  2. Create the route at the application level.
  3. Create the template.

With this we are ready.

Create the function in the view, views.py of our application

def show(request,pk):
   product = get_object_or_404(Product, id=pk)
   
   """try:
       product = Product.objects.get(pk=pk)
   except Product.DoesNotExist:
       #return HttpResponse(status=404)
       return HttpResponseNotFound()"""

   return render(request, 'show.html', { 'product' : product })

The above function all it does is look for a record (Product in this case) given the pk; for that we use the function called get_object_or_404, which allows us to search for a record, if it does not exist it returns a 404 page; for this, we can also do it manually:

try:
       product = Product.objects.get(pk=pk)
   except Product.DoesNotExist:
       #return HttpResponse(status=404)
       return HttpResponseNotFound()

Which looks for a record, and if it doesn't exist returns a 404 exception, but get_object_or_404 does all of that for us.

Create the route at the application level

For the route, we create it, with a parameter called pk of type integer and give it a name.

app_name="gestion"
urlpatterns = [
   path('',views.index),
   path('detail/<int:pk>',views.show, name="show"),
]

Create the template

In our template, we show the content, the normal, the title, price, category and description:

{% extends "base.html" %}
{% block title %}
   {{product.title}}
{% endblock title %}
{% block content %}
<h1>{{product.title}}</h1>
   <p>{{product.price}}$</p>
   <p>{{product.category.title}}</p>
   <p>{{product.description}}</p>
   
{% endblock %}

Conclusion

With this, we can generate a basic loop to display the content of a record, in short, we create a route to pass an ID to it, we search for the record and display it in a template.

- Andrés Cruz

En español
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.