【问题标题】:How can I get and display ForeignKey data in a Django template如何在 Django 模板中获取和显示 ForeignKey 数据
【发布时间】:2021-12-29 20:26:26
【问题描述】:

我正在尝试仅显示基于 category_name 的卡片。

例如。我有 2 个简单的模型,产品和类别:

class Category(models.Model):
    category_name = models.CharField(max_length=254, blank=False, null=False)
    url_name = models.SlugField(max_length=254, unique=True)
    category_image = models.ImageField(
        null=False, blank=False, default='', upload_to='category_images', help_text='This will be the category image')
    category_description = RichTextField(default='')

    class Meta:
        verbose_name = 'Categories'

    def __str__(self):
        return self.category_name

    def get_category_name(self):
        return self.category_name


class Product(models.Model):
    main_product_image = models.ImageField(
        null=False, blank=False, default='', upload_to='product_images', help_text='This will be the main image in the carousel.')
    alternative_image_1 = models.ImageField(
        null=True, blank=True, upload_to='product_images', help_text='This will be the first image in the carousel.')
    alternative_image_2 = models.ImageField(
        null=True, blank=True, upload_to='product_images', help_text='This will be the second image in the carousel.')
    category = models.ForeignKey(
        'Category', null=True, blank=True, help_text='Assign product to category', on_delete=models.CASCADE)
    created_by = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='product_creator', null=True)

    sku = models.CharField(max_length=254, null=True, blank=True)
    name = models.CharField(max_length=254)
    product_display_description = RichTextField(default='')
    spice_rating = models.CharField(max_length=1, null=True, blank=True)
    has_sizes = models.BooleanField(default=False, null=True, blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, default='0')
    add_to_carousel = models.BooleanField(default=False)
    in_stock = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = 'Products'
        ordering = ('-created',)

    def __str__(self):
        return self.name

然后我想根据它们的类别名称在前端显示这些产品卡片。

使用类似这样的简单方法:

{% for product in products_processor|slice:':4' %}
{% if product.category.category_name == 'sauces' %}
<div class="item"></div>
{% endif %}
{% endfor %}

views.py:

def all_products(request):
    """Shows and displays all products."""
    products = Product.objects.all()
    query = None
    categories = None
    sort = None
    direction = None

    if request.GET:

        # Handles sorting by price, rating etc...
        if 'sort' in request.GET:
            sortkey = request.GET['sort']
            sort = sortkey
            if sortkey == 'name':
                sortkey = 'lower_name'
                products = products.annotate(lower_name=Lower('name'))
            if sortkey == 'category':
                sortkey = 'category__name'
            if 'direction' in request.GET:
                direction = request.GET['direction']
                if direction == 'desc':
                    sortkey = f'-{sortkey}'
            products = products.order_by(sortkey)

        # Handles categories
        if 'category' in request.GET:
            categories = request.GET['category'].split(',')
            products = products.filter(category__url_name__in=categories)
            categories = Category.objects.filter(url_name__in=categories)

        # Handles Searches
        if 'q' in request.GET:
            query = request.GET['q']
            if not query:
                messages.error(request, 'Please enter a search query!')
                return redirect(reverse('products'))

            queries = Q(name__icontains=query) | Q(
                product_display_description__icontains=query)
            products = products.filter(queries)

    current_sorting = f'{sort}_{direction}'

    product_context = {
        'products': products,
        'search_term': query,
        'current_categories': categories,
        'current_sorting': current_sorting,
    }

    return render(request, 'products/products.html', product_context)


def product_detail(request, product_id):
    """Displays individual products."""
    product = get_object_or_404(Product, pk=product_id)

    product_context = {
        'product': product,
    }

    return render(request, 'products/product_detail.html', product_context)

此方法似乎不起作用。如果有人能指出我正确的方向,将不胜感激。

【问题讨论】:

  • 您是否遇到任何错误?看起来它应该是正确的,但是如果您输入的模板与您发布的内容完全相同,那么您只是在页面上放置了一些空的 div 标签。
  • 嗨,Nathan,在 div 标签中有一张产品卡,我只是出于空间目的将其剪掉。我认为这也应该有效,但不幸的是,它没有显示任何内容。不,没有错误。
  • 您能否也显示创建此页面的视图?
  • 当然,我已经用 views.py 文件编辑了问题

标签: django django-models django-templates


【解决方案1】:

根据我在您的观点中看到的。在您的模板中,您正在执行{% for product in products_processor|slice:':4' %},其中products_processor 似乎应该是您的上下文的一部分。我看到的问题是您视图中的上下文对象不包含products_processor,只有products。也许尝试在您的模板中将products_processor 替换为products

【讨论】:

  • 对冗长的回复深表歉意,仅此而已!感谢内森的帮助。
  • 不客气,很高兴我能帮上忙。
猜你喜欢
  • 2015-01-26
  • 2013-09-22
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2020-08-09
相关资源
最近更新 更多