在 <textarea> 内呈现降价添加换行符
Rendering markdown inside of <textarea> adds newline
我正在使用 Django 实现类似维基百科的网络应用程序。不同条目的数据存储在服务器上的 Markdown 文件中。我使用 markdown2 进行转换。一切正常,但是当我尝试编辑现有条目时 运行 遇到了问题。服务器向客户端提供“edit.html”,传递一个填充了现有数据的 Django 表单。
views.py
class EditPageForm(forms.Form):
title = forms.CharField(widget=forms.HiddenInput, label="title")
content = forms.CharField(widget=forms.Textarea, label="content"
def edit(request):
if request.method == "POST":
form = SearchForm(request.POST) ## a form with only a "title" input
if form.is_valid():
title = form.cleaned_data["title"]
content = util.get_entry(title) ## read the existing file.md
form = EditPageForm(initial={
"title": title,
"content": content
})
return render(request, "encyclopedia/edit.html", {
"title": title,
"form": form
})
edit.html
<h1>Edit content for "{{ title }}"</h1>
<form action="{% url 'save' %}" method="post">
{% csrf_token %}
{{ form }} ## undesired newlines added here
<input type="submit" value="Save">
</form>
当浏览器呈现包含要编辑的数据的文本区域时,在未经我同意的情况下插入换行符。每次我编辑文本时,这种行为都会循环,以便添加越来越多的换行符。我真的不明白发生了什么。有人有想法吗?
我喜欢认为它是转换器中的一个bug/feature。我有同样的问题,文本区域中的空行在重复提交(在编辑视图中)后呈指数增长。找不到此行为的任何原因。
如果您尝试自己转换为 HTML,您可能会得到不同的结果,但我自己真的不想经历正则表达式的痛苦。
然而,当我提交项目时,该项目仍然获得及格分数。
Python repr()
允许在转义每个特殊字符的同时打印字符串,非常方便调试!
我发现我的代码 - 出于某种不明原因 - 通过添加序列 \r\r\n
在换行符上加倍。所以最后我只是使用正则表达式在每次编辑时删除所有不需要的字符。因此,我在 views.py 中修改了以下内容:
# read the existing file.md and substitute all undesired characters
content = re.sub('(\r\r\n)+', '\n', util.get_entry(title))
希望对以后的人有所帮助!
我正在使用 Django 实现类似维基百科的网络应用程序。不同条目的数据存储在服务器上的 Markdown 文件中。我使用 markdown2 进行转换。一切正常,但是当我尝试编辑现有条目时 运行 遇到了问题。服务器向客户端提供“edit.html”,传递一个填充了现有数据的 Django 表单。
views.py
class EditPageForm(forms.Form):
title = forms.CharField(widget=forms.HiddenInput, label="title")
content = forms.CharField(widget=forms.Textarea, label="content"
def edit(request):
if request.method == "POST":
form = SearchForm(request.POST) ## a form with only a "title" input
if form.is_valid():
title = form.cleaned_data["title"]
content = util.get_entry(title) ## read the existing file.md
form = EditPageForm(initial={
"title": title,
"content": content
})
return render(request, "encyclopedia/edit.html", {
"title": title,
"form": form
})
edit.html
<h1>Edit content for "{{ title }}"</h1>
<form action="{% url 'save' %}" method="post">
{% csrf_token %}
{{ form }} ## undesired newlines added here
<input type="submit" value="Save">
</form>
当浏览器呈现包含要编辑的数据的文本区域时,在未经我同意的情况下插入换行符。每次我编辑文本时,这种行为都会循环,以便添加越来越多的换行符。我真的不明白发生了什么。有人有想法吗?
我喜欢认为它是转换器中的一个bug/feature。我有同样的问题,文本区域中的空行在重复提交(在编辑视图中)后呈指数增长。找不到此行为的任何原因。
如果您尝试自己转换为 HTML,您可能会得到不同的结果,但我自己真的不想经历正则表达式的痛苦。
然而,当我提交项目时,该项目仍然获得及格分数。
Python repr()
允许在转义每个特殊字符的同时打印字符串,非常方便调试!
我发现我的代码 - 出于某种不明原因 - 通过添加序列 \r\r\n
在换行符上加倍。所以最后我只是使用正则表达式在每次编辑时删除所有不需要的字符。因此,我在 views.py 中修改了以下内容:
# read the existing file.md and substitute all undesired characters
content = re.sub('(\r\r\n)+', '\n', util.get_entry(title))
希望对以后的人有所帮助!