简体   繁体   English

Django-替换视图中的字符后,将字符串正确传递到模板的问题

[英]Django - Issues passing String correctly to template after replacing characters in view

I'm having a bizarre issue with passing a particular string from a view to a template. 我在将特定字符串从视图传递到模板时遇到了一个奇怪的问题。

The string originates from a form, and contains text that I want to simplify into a split-able string later. 该字符串源自表单,并且包含我想在以后简化为可拆分字符串的文本。 So, I substitute potential separator characters with a comma like so: 因此,我用逗号替换潜在的分隔符,如下所示:

# views.py

mystring = myform.cleanedData['mystring']
mystring = str(mystring)  # convert from unicode
mystring = mystring.replace("\n", ",").replace("\r\n", ",").replace(" ", ",").replace(";", ",")

# Then I pass it to the template:
return render(request, 'html/mytemplate.html', {'mystring': mystring})

Now, take this form data for example: 现在,以以下表单数据为例:

%15
%16

If I print out mystring to a file just before rendering the template, it looks like this: 如果我在渲染模板之前将mystring打印到文件中,它看起来像这样:

%15,%16

All good so far. 到目前为止一切都很好。 The problem, though, comes from trying to render this string into the template. 但是,问题出在试图将此字符串呈现到模板中。 If I try to render the string like this: 如果我尝试像这样渲染字符串:

{{ mystring }}

The result is this (leading spaces included): 结果是这样的(包括前导空格):

    %15
,%16

It preserves the comma, but adds some other funky stuff, which I don't want because it makes some of my JS get pretty darn confused. 它保留了逗号,但是添加了一些其他时髦的东西,这些是我不想要的,因为这使我的JS变得有些混乱。 I've tried to prevent escaping with the safe filter, but it doesn't seem to change anything in this case. 我试图防止使用安全过滤器进行转义,但是在这种情况下,它似乎没有任何改变。 Another thing to note is that if the original form data is already correctly formatted, ie "%15,%16", it works just fine and passes the string as intended. 要注意的另一件事是,如果原始表单数据已经正确格式化,即“%15,%16”,则可以正常工作并按预期传递字符串。

Any ideas? 有任何想法吗? I've done quite a bit of logging inside my views, but it seems to be fine up until I render it to the template. 我已经在视图中进行了很多日志记录,但是在将其呈现到模板之前似乎还可以。

Well, after looking at my own example code here, I realized what the issue was. 好了,在这里查看我自己的示例代码后,我意识到了问题所在。

I needed to swap the order of replace("\\n", ",") with replace("\\r\\n", ",") , ensuring that the latter occurs first. 我需要将replace("\\n", ",") replace("\\r\\n", ",")的顺序, replace("\\n", ",")确保后者先出现。 The issue was caused by the \\n escapes being replaced, and then not being able to find any occurrences of \\r\\n , therefore leaving all of the \\r s in the text. 造成此问题的原因是替换了\\n转义符,然后找不到任何出现的\\r\\n ,因此将所有\\r保留在文本中。

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

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