Home > other >  Please how can I create url using slug in my url.py django 3?
Please how can I create url using slug in my url.py django 3?

Time:10-17

I am sorry for long explanation I am newbie to Django and come across a book titled "Tango with Django" version 1.9 but I am coding mine in the latest version of Django i.e 3.2. But when I came to chapter 6 I get stucked because slug. I tried my level best to resolve but merely spent hours without anything. So this is a brief of what I want to do, I have a django project called tango_with_django_project, and I created new app called rango so inside the rango app in mode.py I created my models including slug. The problem I am getting is whenever I write the route in urls.py it raises an exception of

 TypeError at /rango/category/other-frameworks/
cannot unpack non-iterable Category object
Request Method: GET
Request URL:    http://127.0.0.1:8000/rango/category/other-frameworks/
Django Version: 3.2.7
Exception Type: TypeError
Exception Value:
cannot unpack non-iterable Category object Exception Location: C:\Users\Userpc\code\env\lib\site-packages\django\db\models\sql\query.py, line 1283, in build_filter Python Executable: C:\Users\Userpc\code\env\Scripts\python.exe Python Version: 3.8.5 Python Path:
['C:\Users\Userpc\code\tango_with_django_project', 'C:\Program Files (x86)\Python38-32\python38.zip', 'C:\Program Files (x86)\Python38-32\DLLs', 'C:\Program Files (x86)\Python38-32\lib', 'C:\Program Files (x86)\Python38-32', 'C:\Users\Userpc\code\env', 'C:\Users\Userpc\code\env\lib\site-packages'] Server time: Sat, 16 Oct 2021 14:20:06 0000

#my urls.py from django.urls import path from rango import views

    urlpatterns = [
        path('', views.index, name='index'),
        path('about/', views.about),
        path('index/', views.index),
        path('category/<slug:category_name_slug>/',views.show_category, name='show_category'),
    ]

 



   
   

    #views.py
    from django.shortcuts import render
    from rango.models import Category, Page
    from rango.models import Page
    
    
    def show_category(request, category_name_slug):
        context_dict = {}
    
        try:
            category = Category.objects.get(slug=category_name_slug)
            pages = Page.objects.filter(category)
    
            context_dict['pages'] = pages
            context_dict['category'] = category
        except Category.DoesNotExist:
            context_dict['category'] = None
            context_dict['pages'] = None
            
            return render(request, 'rango/category.html', context_dict)
    
    def index(request):
        category_list = Category.objects.order_by('-likes')[:5]
        context_dict = {'categories': category_list}
        return render(request, 'rango/index.html', context=context_dict)  
    
    
    def about(request):
        context_dict = {'mss': "This tutorial has been put together by Yusuf"}
        return render(request,'rango/about.html', context=context_dict)
   
    
   <!DOCTYPE html>
<html>
<head>
        <title>Rango</title>
</head>
<body>
    <div>
        {% if category %}
          <h1>{{ category.name }}</h1>
            {% if pages %}
                  <ul>
                   {% for page in pages %}
                      <li><a href="{{ page.url }}">{{ page.title }}</a></li>
                   {% endfor %}
                   </ul>
                {% else %}
                   <strong> No pages curently in category.</strong>
                {% endif %}
        {% else %}
            The specified category does not exist!
        {% endif %}
    </div>
</body>
</html>


#MODEL.PY

from django.db import models
from django.template.defaultfilters import slugify

class Category(models.Model):
    name = models.CharField(max_length=128,unique=True)
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    slug = models.SlugField(null=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)
        

    class Meta:
        verbose_name_plural = 'categories'
        


    def __str__(self):
        return self.name


class Page(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    title = models.CharField(max_length=128)
    url = models.URLField()
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)

    def __str__(self):
        return self.title

CodePudding user response:

You can not use category to filter in pages = Page.objects.filter(category). It is not clear for what field you would filter the page, you thus need to specify the field that links to the category, and filter with:

category = Category.objects.get(slug=category_name_slug)
pages = Page.objects.filter(category=category)

In your view you should render the page outside the try-except block, so:

def show_category(request, category_name_slug):
    context_dict = {}
    try:
        category = Category.objects.get(slug=category_name_slug)
        pages = Page.objects.filter(category=category)
        context_dict['pages'] = pages
        context_dict['category'] = category
    except Category.DoesNotExist:
        context_dict['category'] = None
        context_dict['pages'] = None
    # outside the try-except ↓
    return render(request, 'rango/category.html', context_dict)
  • Related