简体   繁体   中英

Why I can't pass categories to my template in Django

I have a header.html file in my partials under template directory. I have a section for categories which I need to fetch from database. Therefore, I've created a custom templatetag in my app folder. I have written the tag for the latest dropdown article and categories. Well, somehow the articles are being fetched from the database but categories are not.

models.py

from django.db import models
from django.utils.text import slugify
from django.urls import reverse
from ckeditor_uploader.fields import RichTextUploadingField
from datetime import datetime

class Category(models.Model):
    label = models.CharField(max_length=15, unique=True)

    def __str__(self):
        return self.label


class Article(models.Model):
    title = models.CharField(max_length=80, unique=True, help_text='Max Length: 80')
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    banner_image = models.ImageField(upload_to='photos/%Y/%m/%d/', help_text='Banner Image', default=None)
    description = models.TextField(max_length=200 ,help_text='Short descirption about the post')
    content = RichTextUploadingField(help_text='Site Content')
    published = models.BooleanField(default=True)
    date_created = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    views = models.BigIntegerField(default=0)
    featured = models.BooleanField(default=False)

    def __str__(self):
       return self.title

    def get_absolute_url(self):
        return reverse('article', kwargs={'category': self.category, 'post': self.title})

my custom tempalte tag

from django import template
from articles.models import Article, Category

register = template.Library()
@register.inclusion_tag('partials/_header.html')
def recent():
    category = Category.objects.all() #not being fetched
    recents = Article.objects.filter(published=True).order_by('-date_created')[:9]
    trendings = Article.objects.filter(published=True).order_by('-views')[:9]

    return {
        'recents': recents,
        'trendings': trendings,
        'category': category, 
    }

** my header.html file **

<div id="asmCategoryContents" class="asm-Category_Contents">
             {% for cat in category %}
                 <a href=""> {{ cat }}</a>
                            {% empty %}
                            <h2>Not found</h2>
                        {% endfor %}

                    </div>

I'm using MYSQL as my database. I've run all the migrations and have created label fro categories however, It's always displaying Not found for categories. However, it's working fine for articles.

Actually you do not need a template tag. Instead you need a custom template context processor . You can write one like this:

# filename your_app/context_processors/recent.py

from articles.models import Article, Category


def recent(request):
    category = Category.objects.all() #not being fetched
    recents = Article.objects.filter(published=True).order_by('-date_created')[:9]
    trendings = Article.objects.filter(published=True).order_by('-views')[:9]

    return {
        'recents': recents,
        'trendings': trendings,
        'category': category, 
    }

Then add it to context_processors like this:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['./templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # rest of the context processors
                

            ],
         }
    }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM