gpt4 book ai didi

python - 如何将 for 循环(字典)的输出从模型检索到 View ?

转载 作者:太空宇宙 更新时间:2023-11-03 21:33:50 26 4
gpt4 key购买 nike

我有这个模型:

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

我想知道如何正确执行此操作,以及我应该阅读/学习哪些特定资源(文档和/或文章)来理解我的问题。

如果有任何帮助,我将不胜感激。

最佳答案

我认为您没有在这里对基于类的正确 View 进行子类化。您收到的错误是,您正在调用 get 方法,但您提供的 View 不支持该方法。为了简单起见,让我们使用 DetailsView它支持get请求,所以你可以尝试这样:

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 - 如何将 for 循环(字典)的输出从模型检索到 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53361493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com