python - 如何从模型到视图中检索 for 循环(字典)的输出?
问题描述
我有这个模型:
class ModelName(models.Model):
def my_dict(self):
for i in range(n):
…#some code
context_a = {‘a’: a}
return context_a
我需要像这样考虑上下文:
from .models import ModelName
class ViewName
model = ModelName
template_name = ’template_name.html’
def context_b(request):
context_b = ModelName.objects.get(context_a=context_a) #here I want to get context_a as a dictionary and pass it to context_b for further operations. I know that my syntax here is not correct.
return render(request, self.template_name, context_b)
如果我这样做,我会得到
Method Not Allowed: /
[18/Nov/2018 12:40:34] "GET / HTTP/1.1" 405 0
我想知道如何正确地做到这一点,以及我应该阅读/学习哪些特定资源(文档和/或文章)来理解我的问题。
我将不胜感激任何帮助。
解决方案
我认为您没有在这里继承适当的基于类的视图。您得到的错误是,您正在调用get
方法,但您提供的视图不支持该方法。为了简单起见,让我们使用支持获取请求的DetailsView,所以你可以这样尝试:
class YourView(DetailsView):
template_name = 'template_name.html'
model = MyModel
def get_context_data(self, **kwargs):
context = super(YourView, self).get_context_data(**kwargs)
context_a = self.object.my_dict() # here you will get the dictionary from model in view
# by the way, you can also access the your model object from context via context['object'] and in template via {{ object }}
return context
并像这样访问模板的字典:
{% for k, v in object.my_dict.items %}
{{ k }} - {{ v }}
{% endfor %}
还有网址
#urls
path('/someview/<int:pk>/', YourView.as_view(), name="your_view"),
推荐阅读
- python - 熊猫没有在列中列出每个唯一值
- python - 无法在 Docker 中为 arm64 安装或构建 statsmodels
- ruby-on-rails - Ruby on Rails - 无法在某些操作中设置 cookie
- python - R中的扩展窗口(时间序列预测)
- php - 如何在服务提供商的启动方法中从 Laravel 中的多个文件和文件夹中加载翻译?
- python - Sklearn - 序数数据的多类混淆矩阵
- bash - 过滤 github repos 更新和原始
- c - 在C中的Windows终端中屏蔽密码输入
- html - 悬停图像时有点卡在使用 scale() 属性
- tensorflow2.0 - 如何在 tensorflow 模型服务中保存 tensorflow hub 模型以进行服务