Skip to content

Instantly share code, notes, and snippets.

@jesusnoseq
Last active February 7, 2022 00:32
Show Gist options
  • Save jesusnoseq/4645052 to your computer and use it in GitHub Desktop.
Save jesusnoseq/4645052 to your computer and use it in GitHub Desktop.
Como hacer un menú de categorías en django.
<nav class="container mainMenu">
<ul>
<li class="active"><a href="/">Home</a></li>
{% for c in categorias %}
<li><a class="btn" href="{{c.get_absolute_url}}">{{c.nombre}}</a></li>
{% empty %}
<li>No existen categorias creadas.</li>
{% endfor %}
</ul>
</nav>
from django.db import models
class Categoria(models.Model):
slug = models.SlugField(blank=False,unique=True)
nombre = models.CharField(max_length=250,unique=True)
# no es el mejor modo de retornar la URL pero es facil de entender :D
def get_absolute_url(self):
return "/categoria/%s/" % self.slug
def __unicode__(self):
return u'%s' % self.nombre
from django import template
from Principal.models import Categoria
register = template.Library()
@register.inclusion_tag('menu.html')
def getCategorias():
cat = Categoria.objects.all()
return {'categorias':cat}
{% load principal_extras %} <!-- Cargamos el tag -->
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Prueba</title>
</head>
<body>
<div class="container">
{% getCategorias %} <!-- llamamos al tag que hemos creado -->
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment