Incorrect redirection for a single post category

99 Views Asked by At

I'm developing my personal blog; it has only two categories and I would like to have a specific list of posts for both categories.

For this reason I've expand get_absolute_url as you can see below:

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

CATEGORY_CHOICES = (
    ('G.I.S.', 'G.I.S.'),
    ('Sustainable Mobility', 'Sustainable Mobility'),
)

class Blog(models.Model):
    """
    Blog's post definition
    """
    title = models.CharField(
                max_length=70,
                unique=True,
                )
    slug = models.SlugField(
            unique=True,
            )
    contents = models.TextField()
    publishing_date = models.DateTimeField()
    category = models.CharField(
                    max_length=50,
                    choices=CATEGORY_CHOICES,
                    )

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        if Blog.objects.filter(category="G.I.S."):
            return reverse("gis_single_post", kwargs={"slug": self.slug})
        if Blog.objects.filter(category="Sustainable Mobility"):
            return reverse("sumo_single_post", kwargs={"slug": self.slug})

Below you can see views.py; it has different model based on a category:

from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView

from .models import Blog


class GisSinglePost(DetailView):
    model = Blog
    queryset = Blog.objects.filter(category="G.I.S.")
    context_object_name = 'post'
    template_name = "gis_single_post.html"


class GisListPost(ListView):
    model = Blog
    queryset = Blog.objects.filter(category="G.I.S.")
    context_object_name = 'posts'
    template_name = "gis_list_post.html"


class SuMoSinglePost(DetailView):
    model = Blog
    queryset = Blog.objects.filter(category="Sustainable Mobility")
    context_object_name = 'post'
    template_name = "sumo_single_post.html"


class SuMoListPost(ListView):
    model = Blog
    queryset = Blog.objects.filter(category="Sustainable Mobility")
    context_object_name = 'posts'
    template_name = "sumo_list_post.html"

And below there is urls.py with its four path:

from django.urls import include, path
from .views import GisSinglePost, GisListPost, SuMoListPost, SuMoSinglePost

urlpatterns = [
        path("gis/", GisListPost.as_view(), name="gis_list_post"),
        path("gis/<slug:slug>/", GisSinglePost.as_view(), name="gis_single_post"),
        path("sustainable-mobility/", SuMoListPost.as_view(), name="sumo_list_post"),
        path("sustainable-mobility/<slug:slug>/", SuMoSinglePost.as_view(), name="sumo_single_post"),
]

When I click on a single post of GIS's category it's shown the relative details without problem. But when I click on a post of the other category it's shown to me this:

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/gis/erova-mobilita/ Raised by: blog.views.GisSinglePost

No Articolo found matching the query

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

I've been stuck on this problem for many days. How I can resolve?

2

There are 2 best solutions below

2
On BEST ANSWER

You should redefine your get_absolute_url method. Since your Blog instances with category G.I.S exist you are never reaching second if for Blog instances with category Sustainable Mobility.

def get_absolute_url(self):
    if self.category == "G.I.S.":
        return reverse("gis_single_post", kwargs={"slug": self.slug})
    elif self.category == "Sustainable Mobility":
       return reverse("sumo_single_post", kwargs={"slug": self.slug})
0
On

Try to redefine your get_absolute_url(self) in the next way:

def get_absolute_url(self):
    if self.category == "G.I.S.":
        return reverse("gis_single_post", kwargs={"slug": self.slug})
    if self.category == "Sustainable Mobility":
        return reverse("sumo_single_post", kwargs={"slug": self.slug})