我是django的新手。
这是我从互联网上调用的api json值:
{'message': '',
'result': [{'name': 'ABC', <------
'Type': 'True', <-----
'Fee': 0.0005},
{'name': 'DEF', <-------
'Type': 'False', <------
'Fee': 0.004},
}
我想使用HTML将名称和类型放到网页上。
ABC True
DEF False
我需要修改models.py吗?请举个例子。谢谢 我知道的唯一想法是在HTML中使用for循环,但我不知道它是否有效?
答案 0 :(得分:1)
只需在模板中使用forloop。
{% for r in result %}
{{ r.name }} {{ r.Type }}
{% endfor %}
view
您的result
来自context
。
基本上,django view
将数据呈现给您自己的模板。 context_processors
为您执行此操作,并在settings.py
(TEMPLATES
- OPTIONS
- context_processors
)中定义。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
str(ROOT_DIR.path('templates')),
],
# 'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# you can add your own processors
'your_app.path.to.custom_processors',
],
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
},
},
]
以下是有关context
(official django docs)
这就是您可以在模板中使用request
,user
和其他上下文数据的原因。
如果要在所有模板中使用上下文,可以添加自己的context_processors
。但在很多时候,您只想在特定模板中使用上下文。 (就像你的情况一样)。
然后,您可以在views
。
如果您使用的是基于类的视图(我建议使用CBV),您可以按get_context_data()
添加。像这样。
class ProductView(ListView):
model = Product
template_name = 'best.html'
context_object_name = 'products'
def get_context_data(self, **kwargs):
context = super(ProductView, self).get_context_data(**kwargs)
context['test'] = 'test context data'
return context
您可以在现有context
中添加自己的上下文数据。
如果您正在使用FBV,则可以使用您的上下文渲染模板。有很多种呈现方式(render
,render_to_response
等等。您可以检查django文档。我猜您应该使用render
因为render_to_response
已弃用在django 2.0
)
from django.shortcuts import render
def my_view(request):
# View code here...
context = {'test': 'test coooontext data' }
return render(request, 'myapp/index.html', context)
通过在视图中传递您自己的上下文数据,您可以在模板中使用它。
因此,如果您只想传递'name'和'type',您可以传递您想要使用的数据,而不是全部。在视图模板中工作更有效。我希望它有所帮助。
答案 1 :(得分:0)
在view.py
中您可以返回
等数据url = 'xxx'
response = requests.get(url)
# if your response is like : {'message': '', 'result': [{'name': 'ABC', 'Type': 'True', 'Fee': 0.0005}, {'name': 'DEF','Type': 'False', 'Fee': 0.004}] }
# then
list_result = response['result']
render(request, 'template.html', {"list_result": list_result})
然后,您可以在HTML页面上发送list_result
并使用
render
from django.shortcuts import render
要在HTML页面上显示响应数据:
{% for data in list_result %}
{{ data.name }} {{ data.Type }}
{% endfor %}