简体   繁体   English

如何将日期格式从python中的视图传递到<script> in html page

[英]How to pass a date format from view in python to a <script> in html page

I set a field where the user can choose date range (Start, End): 我设置了一个字段,用户可以在其中选择日期范围(开始,结束):

if request.method == 'POST':
            fecha = (request.POST.get('datefilter')).split(' - ')
            start = datetime.strptime(
                fecha[0].strip(), "%Y-%m-%d").date()
            end = datetime.strptime(
                fecha[1].strip(), "%Y-%m-%d").date()

when I print the variable start after selecting the date range I get the correct date which was chose by the user. 当我在选择日期范围后打印变量start时,我得到了用户选择的正确日期。 Now I have to take both of them (start and end) and send them to HTML page where I am going to use them but when I try to send them like this: 现在,我必须同时使用它们(开始和结束)并将它们发送到要使用它们的HTML页面,但是当我尝试像这样发送它们时:

return render(request, "path/page.html", {"start": start, "end": end})

and get them like this inside the script in the HTML page 并在HTML页面的脚本中将它们像这样

<script>

var start = {{start | safe}};              
        console.log(start);

var end = {{end | safe}};              
        console.log(end);

</script>

I am getting an integer instead of the date which I am trying to send from the view. 我得到一个整数而不是我试图从视图发送的日期。

for example. 例如。 If I want to call data from 25-01-17 to 25-01-18 如果我想从25-01-17到25-01-18调用数据

25-01-17 would be the start date and 25-01-18 the end date so when I print those variables in the view to be shown in the console I get the correct date chose by the user. 25-01-17是开始日期,25-01-18是结束日期,因此当我在要在控制台中显示的视图中打印这些变量时,我会得到用户选择的正确日期。

print(start)
print(end)

output:

25-01-17
25-01-18

but when I try to print those same variables in the script inside html page, I get something different 但是当我尝试在html页面内的脚本中打印那些相同的变量时,我得到了一些不同的东西

console.log(start);
console.log(end);

output:

7
6

I realized that what is happening is a math operation. 我意识到正在发生的事是数学运算。 25 - 01 = 24 - 17 = 7. 25-01 = 24-17 = 7。

How can I solve this problem ? 我怎么解决这个问题 ?

Try just wrapping them in quotes, if they should be strings, like this: 如果它们应该是字符串,请尝试将它们用引号引起来,如下所示:

<script>

var start = "{{start | safe}}";              
        console.log(start);

var end = "{{end | safe}}";              
        console.log(end);

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM