django-template 中的不同模型

Posted

技术标签:

【中文标题】django-template 中的不同模型【英文标题】:Different models in django-template 【发布时间】:2017-12-27 11:08:12 【问题描述】:

我是 Django 的新手,找不到解决方案。如何在 1 个模板中传递来自不同模型的 2 个查询集?我使用 mptt 类别并与之堆叠一段时间。我知道我必须用views.py 做点什么,但是我怎样才能组合这些查询集呢?这是我的 Models.py

from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse
from mptt.models import MPTTModel, TreeForeignKey


class Variant(MPTTModel):
 category = models.CharField(max_length=500)
 logo = models.ImageField(upload_to='images/', null=True, blank=True)
 slug = models.SlugField(max_length=160, blank=True, null=True)
 parent = TreeForeignKey('self', null=True, blank=True, 
  related_name='children', db_index=True,
                        on_delete=models.CASCADE)

class MPTTMeta:
    order_insertion_by = ['category']

class Meta:
    verbose_name = 'категория'
    verbose_name_plural = 'категории'

def get_absolute_url(self):
    return reverse('cosmetics:details', kwargs='pk': self.pk)

def __str__(self):
    return self.category

def is_second_node(self):
        return True if (self.get_ancestors().count() == 1) else False



class Pic_Discription(models.Model):
 variant = TreeForeignKey('Variant', null=True, blank=True)
 model = models.CharField(max_length=500)
 pic_title = models.ImageField(upload_to='images/', null=True, blank=True)
 description = models.TextField(default='')
 price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
 slug = models.SlugField(max_length=160,blank=True, null=True)
 available = models.BooleanField(default=True)

class Meta:
    verbose_name = 'Продукт'
    verbose_name_plural = 'Продукты'

def __str__(self):
    return self.model

def get_absolute_url(self):
    return reverse('cosmetics:details', kwargs='pk': self.pk)

Views.py

class CategoryView(generic.ListView):
model = Variant
template_name = 'cosmetics/homepage.html'

def get_context_data(self, *, object_list=None, **kwargs):
    """Get the context for this view."""
    queryset = object_list if object_list is not None else self.object_list
    page_size = self.get_paginate_by(queryset)
    context_object_name = self.get_context_object_name(queryset)
    if page_size:
        paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
        context = 
            'paginator': paginator,
            'page_obj': page,
            'is_paginated': is_paginated,
            'object_list': queryset
        
    else:
        context = 
            'paginator': None,
            'page_obj': None,
            'is_paginated': False,
            'object_list': queryset
        
    if context_object_name is not None:
        context[context_object_name] = queryset
    context.update(kwargs)
    context['nodes'] = context.get('object_list')
    return super().get_context_data(**context)

我也尝试为模型添加另一个类视图,但它不起作用

class ProductsView(generic.ListView):
model = Pic_Discription
template_name = 'cosmetics/homepage.html'

def get_queryset(self):
    return Pic_Discription.objects.all()

我的网址:

urlpatterns = [
#/cosmetics/
url(r'^$', views.CategoryView.as_view(), name='homepage'),
#/cosmetics/5/
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='details'),

url(r'^products/$', views.ProductsView.as_view(), name='products'),
]

这是一个模板:

% load mptt_tags %

% block body %
   <div class="container-fluid2">
    <div class="col-md-2 col-sm-2">

       <div class="panel panel-default" id="categories">
         <div class="panel-header" id="cat-head">Категории</div>
         <div class="panel-body" id="content-cat">
           % recursetree nodes %
                            <div class="
                                    % if node.is_root_node %
                                    root
                                    % elif node.is_child_node and not 
                                  node.is_leaf_node or node.is_second_node%
                                    child
                                    % elif node.is_leaf_node and not 
                                    node.is_root_node%
                                    leaf
                                    %endif%">
                                    node.category
                                </div>
                                % if not node.is_leaf_node%
                                <ul>children</ul>
                                % endif %
               % endrecursetree %
       </div>
       </div>
    </div>



        % for cosmetic in object_list %
            <div class="col-md-3 col-sm-4">
                <div class="thumbnail">
                    <a href="% url 'cosmetics:details' cosmetic.id %">
                        % if cosmetic.pic_title %
                            <img src=" cosmetic.pic_title.url " class="img-responsive">
                        % else %
                            <h3>Изображение отсутствует</h3>
                        % endif %
                    </a>
                    <div class="caption" id="textyInfo">
                        <h2> cosmetic.model </h2>
                        <!-- View Details -->
                        <a href="% url 'cosmetics:details' cosmetic.id %" class="btn btn-primary btn-sm" role="button">
                            Подробнее
                        </a>
                    </div>
                </div>
            </div>
            % cycle '' '' '' '' '' '<div class="clearfix visible-lg"></div>' %
        % endfor %



</div>
% endblock %

【问题讨论】:

【参考方案1】:

只使用上下文:

from .models import MyModel

...
context['my_model'] = MyModel.objects.all()
....

例如在您的模板中

% for m in my_model %
    % m.myfield %
% enfor %

【讨论】:

以上是关于django-template 中的不同模型的主要内容,如果未能解决你的问题,请参考以下文章

django-template层

直接从 django-template 发送电子邮件

VSCode 自定义代码格式和语言自动缩进(Django-Template 缩进)

Django-template模板语言

如何在脚本中使用 django-template 而不是 jinja2?

TEM:基于树模型构建可解释性推荐系统