【问题标题】:how display contexts of two different app and different view in one template in one project in django?如何在 django 的一个项目中的一个模板中显示两个不同应用程序和不同视图的上下文?
【发布时间】:2019-04-03 16:35:50
【问题描述】:

我有一个项目,上面有不同的视图和不同的功能。 我想在其他 html 应用程序中访问和显示其中一个视图的上下文。 这是我的代码

washer.views.py

def Product_list_view(request):
    product_list_view = Product.objects.all()
    best_post = Product.objects.order_by('timefield')[0:2]
    context = {
       "product_list_view": product_list_view,
       'best_post':best_post
    }
    template_name = "product_list_view.html"
    return render(request,template_name,context)

gasket.views.py

  def home(request):
     template= "base.html"
     return render(request,template,context={})

如何访问 product_list_view 的上下文并将其显示在 base.html 中? 我可以在不同的应用程序中将一个 html 设置为两个不同的视图吗?并访问他们俩的上下文? 我必须做什么? tnx 帮助我。

【问题讨论】:

    标签: python django templates jinja2


    【解决方案1】:

    我不确定你在这里实际想要实现什么,但你可以简单地将gasket.views.py 重写为

    def home(request):
         template= "base.html"
         context = {
             "product_list_view": Product.objects.all(),
             'best_post':Product.objects.order_by('timefield')[0:2]
         }
         return render(request,template,context={})
    

    显然您需要添加from washer.models import Product

    【讨论】:

    • 这是我的主要问题,当我在这个suituion垫片中的antoher应用程序中想要产品时,当我编写代码时你确实写了得到错误我去上目录:从垫片.washer.models导入产品得到这个错误: ModuleNotFoundError: No module named 'gasket.washer' 我知道如果我导入模型产品我可以解决我的问题。
    • 你把它包含在INSTALLED_APPS中了吗?
    • INSTALLED_APPS = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages' , 'django.contrib.staticfiles', 'cmets', 'washer', 'newsletters', 'taggit', ] 是的,我在对此有疑问之前就这样做了,我希望在基本页面中拥有最好的产品和时事通讯但我无法将它们导入基本应用程序并使用它们。
    • 文件结构是什么?你的错误是`没有名为'gasket.washer'的模块`但我不知道为什么有gasket
    • 无法访问产品,所以我转到垫圈垫圈的上级目录,但现在我收到此图片的错误:pasteboard.co/I8s43qj.png
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 2020-05-21
    • 2013-02-25
    • 2011-03-25
    • 2012-04-29
    相关资源
    最近更新 更多