[英]Pass parameters from Django template to view
I pull data from an external API and show it in my template.我从外部 API 中提取数据并将其显示在我的模板中。 I would like to give users a few options for parameterizing these API requests.
我想为用户提供一些参数化这些 API 请求的选项。 What is the best way to go about doing that?
go 关于这样做的最佳方法是什么?
For instance, I am rendering a game schedule and I want to let user select the league
or date
params and pull from API the data according to user user choice.例如,我正在渲染一个比赛时间表,我想让用户 select 获得
league
或date
参数,并根据用户的选择从 API 中提取数据。
view看法
def games(request):
""" View to return games page """
if request.method == "GET":
day = request.GET.get('date')
params = {"league": "nba", "date": day}
results = requests.request("GET", URL, headers=headers,
params=params).json()
template with the form for user input:带有用户输入表单的模板:
<form method="GET">
{% csrf_token %}
<input type="hidden" id="date" name="tomorrow" value="
{{tomorrow|date:'Y-m-d'}}">
<button class="btn tomorrow-btn light-blue" type="submit">
Tomorrow's Games
</button>
</form>
I updated the code to show the correct answer.我更新了代码以显示正确的答案。 I had the wrong form method, should have been GET.
我的表单方法错误,应该是 GET。
Then I assigned the form value to a variable and passed that variable to the API parameters.然后我将表单值分配给一个变量,并将该变量传递给 API 参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.