Django app - Page detail

Hi everyone,
I am still a learner for python django. I am trying to create a site where user can Add the a new command and should be able to see the details of the latest added product in another page. I am able to achieve the first part i.e the Add Command page. But i need help as to how to get the detail page correct. Request the guidance.
My model.py is as follows:

from django.db import models
from django.urls import reverse  


    class Commande(models.Model):
        numero_commande = models.CharField(max_length=100, help_text='Numéro de commande', null=True)
        Objet = models.CharField(max_length=200, help_text='Objet de la commande')
        enseigne = models.CharField(max_length=100, help_text='Nom du magasin/site internet', null=True)
        Date_commande = models.DateField(null=True, blank=True)
        Date_livraison = models.DateField(null=True, blank=True)
        Montant = models.CharField(max_length=200, help_text='Montant de la commande')
        Lieu_reception = models.CharField(max_length=200, help_text='Lieu de réception de la commande')
        Transporteurs = (
            ("1", "DPD"),
            ("2", "LaPoste"),
            ("3", "GLS"),
            ("4", "Chronoposte"),
            ("5", "DHL"),
            ("6", "UPS"),
            ("7", "FEDEX"),
            ("8", "MondialRelay"),
            ("9", "RelayColis"),
            ("10", "N/A")
        )
        Transporteur = models.CharField(
            max_length=20,
            choices=Transporteurs,
            default='2'
        )
        numero_suivi = models.CharField(
            max_length=20,
            help_text='Numero de suivi',
            blank=True
        )

        Payeurs = (
        ("1", "Joseph"),
        ("2", "Luc"),
        )
        Payeur = models.CharField(
            max_length=100, help_text='Qui a payé?',
            choices=Payeurs,
            default= '1'
        )

        Etats = (
            ("En cours de livraison", "En cours"),
            ("Commande réceptionnée", "Réceptionné"),
            ("Commande retournée", "Retournée")
        )
        Etat = models.CharField(
            max_length=100,
            choices=Etats,
            default='En cours de livraison'
        )

        def __str__(self):
            return self.numero_commande

        def get_absolute_url(self):
            """Cette fonction est requise pas Django, lorsque vous souhaitez détailler le contenu d'un objet."""
            return reverse('commande-detail', args=[str(self.id)])

My views.py looks as follows:

# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import reverse
from django.db.models import Avg, Max, Min, Sum
from .forms import CommandeForm
from catalog.models import Book, Author, BookInstance, Commande
from django.shortcuts import redirect

def commande_detail(request, pk):
    return render(request, 'catalog/commande_detail.html', {'commande': Commande})


def commande_new(request):
        if request.method == "POST":
            form = CommandeForm(request.POST)
            if form.is_valid():
                Commande = form.save(commit=False)
                #post.author = request.user
               # post.published_date = timezone.now()
                Commande.save()
            return redirect('commande-detail', pk=Commande.pk)

        else:
            form = CommandeForm()
        return render(request, 'catalog/post_edit.html', {'form': form})


def index(request):
    """View function for home page of site."""
    query_results = Commande.objects.all()

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()
    # Number of visits to this view, as counted in the session variable.
    num_visits = request.session.get('num_visits', 0)
    request.session['num_visits'] = num_visits + 1

    #Toutes les commandes
    num_commandes = Commande.objects.all().count()

    #Montant de toutes les commandes
    total_commandes = Commande.objects.all().aggregate(Sum('Montant'))

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
        'num_commandes' : num_commandes,
        'total_commandes' : total_commandes,
        'query_results' : query_results,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)

My urls.py looks as follows:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('commandes/', views.CommandeListView.as_view(), name='commandes'),
    path('commande/<int:pk>/', views.commande_detail, name='commande-detail'),
    path('commande/new/', views.commande_new, name='commande_new'), 
] 

I created a commande_list.html where I can see all my commandes.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {% extends "base_generic.html" %}

{% block content %}

    <h1>Commande List</h1>

  {% if commande_list %}
  <ul>
    {% for commande in commande_list %}
      <li>
          <a href="{% url 'commande-detail' pk=commande.pk %}">{{ commande.numero_commande }}</a> {{ commande.Montant }}
      </li>

    {% endfor %}
  </ul>
  {% else %}
    <p>There are no books in the library.</p>
  {% endif %}
{% endblock %}
</head>
<body>
</body>
</html>>

And I created a commande_detail.html in which I want to show the latest added product details :

{% extends "base_generic.html" %}

{% block content %}
  <h1>{{ commande.numero_commande }}</h1>
  <p>{{ commande.Objet }} </p> 
  <p>{{ commande.Montant }} </p>

{% endblock %}

Currently on adding a new commande, i can see product in the localhost:8000/catalog/commandes/ page. But after clicking on a command, i see a blank page localhost:8000/catalog/commande/3/

Thanks in advance for all the help and guidance

Hi Vinloup.

Here you’re passing the Commande model in the context, not the instance of your model.

You could get the commande instance using the pk

def commande_detail(request, pk):
    my_commande = Commande.objects.get(pk=pk)
    return render(request, 'catalog/commande_detail.html', {'commande': my_commande})
3 Likes

It works ! Thanks a lot @marcorichetta

1 Like