如何在Django模板上解决字符串到数据的转换问题



我在Django模板上遇到了字符串到数据的转换问题。我试着取一个(日期的(字符串,计算自那个日期以来的天数;所以上面写着"1个月,2周(从有史以来的最高日期("。字符串到日期的转换工作正常,问题出在Django模板上。该模板目前只显示for循环中返回的每个项的json数据请求的最后日期。显然,我需要转换和显示每个特定记录的日期。

我已经将json数据请求中的字符串格式化为日期对象。

当前,只有列表中的最后一项作为days_since_ath_formatted变量发送。

这是Django视图def:

coin_list_url = f"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page={per_page_limit}&page=1&sparkline=false"
request_coin_list = requests.get(coin_list_url)
results_coin_list = request_coin_list.json()
crypto_data_geckco = []

#string to date conversion
def to_string(time):
return time.strftime('%Y %M %d')
def from_string(date, formatting):
dt = datetime.datetime.strptime(date, formatting)
return dt
#for loop
for currency_gecko in results_coin_list:
days_since_ath = currency_gecko['ath_date']
days_since_ath_formatted = from_string(days_since_ath[:-14], "%Y-%m-%d")
print('days since ath formatted', days_since_ath_formatted)
crypto_data_geckco.append(currency_gecko)
print("crypto_data_geckco", crypto_data_geckco)

return render(request, 'crypto/latest.html', { 'crypto_data_geckco': crypto_data_geckco, 'days_since_ath_formatted': days_since_ath_formatted} )

然后在Django模板上:

{% for currency in crypto_data_geckco %}
All-Time Percentage: {{ currency.ath_change_percentage|intword }}%
and passing the "days_since_ath_formatted" variable only accesses the last item in the list:
Days since ATH: {{ days_since_ath_formatted|timesince }}
{% endfor %}

{{ days_since_ath_formatted|timesince }}应该为for循环中返回的每个项目显示不同的日期。目前,它只显示for循环中每个项目的json列表中的最后一个项目。

在这个列表上循环时,看起来并没有实际存储days_since_ath_formated的值,您可能想存储在dict:中

for currency_gecko in results_coin_list:
currency = {}
currency['ath_change_percentage'] = currency_gecko.ath_change_percentage
currency['days_since_ath_formatted'] = from_string(days_since_ath[:-14], "%Y-%m-%d")
print('days since ath formatted', days_since_ath_formatted)
crypto_data_geckco.append(currency)
print("crypto_data_geckco", currency)

return render(request, 'crypto/latest.html', { 'crypto_data_geckco': crypto_data_geckco, 'days_since_ath_formatted': days_since_ath_formatted} )

然后在模板中,你会想要这样的东西:

{% for currency in crypto_data_geckco %}
All-Time Percentage: {{ currency.ath_change_percentage|intword }}%
and passing the "days_since_ath_formatted" variable only accesses the last item in the list:
Days since ATH: {{ currency.days_since_ath_formatted|timesince }}
{% endfor %}

我不能确切地说,但我猜你的results_coin_list是一个查询集,在这种情况下,你也可以直接向模型添加属性

最新更新