保存时,textarea中的换行符数量加倍 [英] Newlines in textarea are doubled in number when saved
问题描述
我正在使用Django Wiki应用程序.用户可以在文本区域中输入降价文本来创建或编辑条目.但是,无论何时发生这种情况,文本之间的换行符数量都会加倍.例如,如果用户在文本区域中输入了4个换行符,则保存的markdown文件将具有8个换行符.
I am working on a Django wiki app. The user can enter markdown text in a textarea to either create or edit an entry. Whenever this happens though, the number of newlines between text are doubled. For example if the user entered 4 newlines in the textarea, the saved markdown file will have 8 newlines.
'''
# in views.py
class ContentForm(forms.Form):
content = forms.CharField(
required=True,
widget=forms.Textarea,
label="Contents")
def edit(request, title):
if request.method == 'POST':
# save_entry saves the markdown text to the given title.md
save_entry(title, request.POST['content'])
# redirect the user to the updated wiki page
return HttpResponseRedirect(reverse('entry', args=(title,)))
else:
# get_entry returns markdown text for a title
content = get_entry(title)
form = ContentForm(request.POST or None, initial={'content': content})
return render(request, "encyclopedia/edit.html", {
"title": title,
"content": content,
"form": form
})
# in edit.html
<h1>Edit {{ title }}</h1>
<form action="{% url 'edit' title %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Save Changes">
</form>
# save_entry and get_entry definitions
def save_entry(title, content):
"""
Saves an encyclopedia entry, given its title and Markdown
content. If an existing entry with the same title already exists,
it is replaced.
"""
filename = f"entries/{title}.md"
if default_storage.exists(filename):
default_storage.delete(filename)
default_storage.save(filename, ContentFile(content))
def get_entry(title):
"""
Retrieves an encyclopedia entry by its title. If no such
entry exists, the function returns None.
"""
try:
f = default_storage.open(f"entries/{title}.md")
return f.read().decode("utf-8")
except FileNotFoundError:
return None
'''
在这种情况下,我使用了textarea小部件,但在此之前,我仅使用了textarea html标记,但也没有用.同样,要创建一个新页面,我没有使用小部件,并且也正在做同样的事情.我已经尝试修复了多个小时.可能出什么问题了?
In this case I used a textarea widget, but before this I had just used the textarea html tag and that was not working either. To create a new page as well, I am not using a widget and that is doing the same thing too. I've been trying to fix this for many hours. What could be going wrong?
推荐答案
在将其传递给保存功能之前,我通过使用bytes(content,'utf8')修复了此问题.
I fixed this by using bytes(content, 'utf8') before passing it to the save function.
请参阅: bytes()为什么解决了我的换行问题?
if request.method == 'POST':
save_entry(title, bytes(request.POST['new_content'], 'utf8'))
return HttpResponseRedirect(reverse('encyclopedia:entry', args=(title,)))
这篇关于保存时,textarea中的换行符数量加倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!