How add categories in my website with django?

262 Views Asked by At

I'm a beginner in django and I'm trying to make a website. I want to filter the categories in my website but I have a error (UnboundLocalError) when I introduce the URL in browser.

models.py

from django.db import models
from django.contrib.auth.models import User

class Categoria(models.Model):
    nombre=models.CharField(max_length=50)
    created=models.DateTimeField(auto_now_add=True)
    updated=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name='categoria'
        verbose_name_plural='categorias'

    def __str__(self):
        return self.nombre

class Post(models.Model):
    titulo=models.CharField(max_length=50)
    contenido=models.TextField()
    imagen=models.ImageField(upload_to='blog', null=True, blank=True)
    autor=models.ForeignKey(User, on_delete=models.CASCADE)
    categorias=models.ManyToManyField(Categoria)
    created=models.DateTimeField(auto_now_add=True)
    updated=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name='post'
        verbose_name_plural='posts'

    def __str__(self):
        return self.titulo

urls.py

from django.urls import path
from . import views


urlpatterns = [

     path('',views.blog, name='Blog'),
     path('categoria/<int:categoria_id>/', views.categoria, name='categoria'),
]

views.py

from django.shortcuts import get_object_or_404, render
from blog.models import Categoria, Post


def blog(request):
    posts=Post.objects.all()
    return render(request, 'blog/blog.html', {'posts':posts})

def categoria(request, categoria_id):
    categoria=get_object_or_404(Categoria, id=categoria_id)
    return render(request, 'blog/categorias.html', {'categoria':categoria, 'posts':posts})

blog.html

{% extends 'ProyectoWebApp/base.html' %}
{% load static %}
{% block content %}
{% for post in posts %}
    <div class="intro">
      <img class="intro-img img-fluid mb-3 mb-lg-0 rounded" src="{{post.imagen.url}}" alt="" style="width: 50%;">
      <div class="intro-text left-0 text-center bg-faded p-5 rounded">
        <h2 class="section-heading mb-4" >
          <span class="section-heading-lower">{{post.titulo}}</span>
          <span class="section-heading-upper">{{post.contenido}}</span>
        </h2>   

        <div style="text-align: left; font-size: 0.8em;">
           
           Autor: {{post.autor}}
        
        </div>        
     </div>
    </div>

  </div>
</section>


{% endfor %}
  <div style="width: 75%; margin: auto; text-align: center; color: white;">
  
  
     Categorias:

     {% for post in posts %}

        {% for categoria in post.categorias.all %}

           {{categoria.nombre}} &nbsp;&nbsp;&nbsp;

        {% endfor %}
     {% endfor %}
  </div>

I created an exact same copy of my 'blog.html' for the time of filtering the categories, but I don't know how to formulate the loops so that the categories pass through and display without showing the error. Maybe, that's the problem. Please if anyone can help me I would appreciate it.

2

There are 2 best solutions below

0
On

in your categoria view:

 return render(request, 'blog/categorias.html', {'categoria':categoria, 'posts':posts})

the context 'posts':posts is not coming from anywhere,so Django throw the error UnboundLocalError ,you probably want to do something like:

def categoria(request, categoria_id):
  categoria=get_object_or_404(Categoria, id=categoria_id)
  posts = Post.objects.filter(categoria__in=categoria)
  return render(request, 'blog/categorias.html', {'categoria':categoria, 'posts':posts})

so you could display a category and all the posts of that category

0
On

An UnboundLocalError is raised when a local variable is referenced before it has been assigned as in this case posts is being used in line return render(request, 'blog/categorias.html', {'categoria':categoria, 'posts':posts}) update your method as below:

def categoria(request, categoria_id):
    categoria=get_object_or_404(Categoria, id=categoria_id)
    posts=Post.objects.all()
    return render(request, 'blog/categorias.html', {'categoria':categoria, 'posts':posts})