在Django中提交并保存Markdown文件后,出现额外的空行。

huangapple go评论59阅读模式
英文:

Extra blank lines in markdown file after submitting and saving in Django

问题

Sure, here's the translated content:

我在保存用户提交的信息方面遇到了问题。我的网站的一个页面应该有一个用于Markdown文本的文本框。用户在此区域输入的数据应该在提交后保存到一个单独的文件中。但是,当我在提交后打开保存的文件时,会出现额外的空行。下面是来自views.py和HTML表单的函数。

from django.shortcuts import render
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage

def index(request):
    if request.method == "POST":
        save_data(request.POST.get("title"), request.POST.get("content"))   
    return render(request, "my_app/page.html")

def save_data(title, content):
    filename = f"files/{title}.md"
    if default_storage.exists(filename):
        default_storage.delete(filename)
    default_storage.save(filename, ContentFile(content))
<form method="post">
    {% csrf_token %}
    <label for="title">输入标题:</label><br>
    <input id="title" type="text" name="title">
    <br><br><label for="textarea">输入信息:</label><br>
    <textarea id="textarea" name="content"></textarea><br><br>
    <input type="submit" value="保存页面">
</form>

如果我尝试在文本框中输入以下文本:

# 我的文件

这是Markdown文件。
这个文件是我问题的示例。

我在提交后看到的是:

# 我的文件



这是Markdown文件。

这个文件是我问题的示例。

请问您能帮助我解决这个问题吗?先谢谢了!


问题解决方案:

好的,问题的实质变得清晰,如果尝试使用 print(repr(request.POST['content'])),执行此命令后,您会得到 # My file\r\n\r\nThis is markdown file.\r\nThis file was created as an example for my question.。因此,问题在于Windows和Linux/Mac OS中的新行编码的差异。请在下面的答案中了解更多信息。

英文:

I have a problem with saving information submitted by the user. One of my website's pages should have a textarea for markdown text. Data entered by the user in this area should be saved in a separate file after submitting. But when I open saved file after submitting, there are extra blank lines. Functions from views.py and HTML form are presented below.

from django.shortcuts import render
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage


def index(request):
    if request.method == &quot;POST&quot;:
        save_data(request.POST.get(&quot;title&quot;), request.POST.get(&quot;content&quot;))   
    return render(request, &quot;my_app/page.html&quot;)


def save_data(title, content):
    filename = f&quot;files/{title}.md&quot;
    if default_storage.exists(filename):
        default_storage.delete(filename)
    default_storage.save(filename, ContentFile(content))
&lt;form method=&quot;post&quot;&gt;
    {% csrf_token %}
    &lt;label for=&quot;title&quot;&gt;Enter a title:&lt;/label&gt;&lt;br&gt;
    &lt;input id=&quot;title&quot; type=&quot;text&quot; name=&quot;title&quot;&gt;
    &lt;br&gt;&lt;br&gt;&lt;label for=&quot;textarea&quot;&gt;Enter the information:&lt;/label&gt;&lt;br&gt;
    &lt;textarea id=&quot;textarea&quot; name=&quot;content&quot;&gt;&lt;/textarea&gt;&lt;br&gt;&lt;br&gt;
    &lt;input type=&quot;submit&quot; value=&quot;Save Page&quot;&gt;
&lt;/form&gt;

If I try, for example, to type in the textarea the following text:

# My file

This is markdown file.
This file was created as an example for my question.

I see this after submitting:

# My file

This is markdown file.
This file was created as an example for my question.

Could you help me solve this problem, please? Thank you in advance!


Problem solution:

OK, the essence of the problem becomes clear if you try to use print(repr(request.POST[&#39;content&#39;])). After execution this command you will get # My file\r\n\r\nThis is markdown file.\r\nThis file was created as an example for my question.. So, the problem is the difference in new line encoding in Windows and Linux/Mac OS. Read more in the answer below.

答案1

得分: 1

这似乎是换行符编码方式的差异。Windows 使用 回车符 (\r) 接着是 换行符 (\n),而Linux和Mac OS X 只使用换行符 (\n)。通常某些系统也会将其解释为新行。但这是渲染,而不是内容。你查看文件的编辑器可能已将行尾设置为 \n 或 LF 或 Linux。

然而,你可以在保存之前清理输入:

def index(request):
    if 'title' in request.POST and 'content' in request.POST:
        save_data(
            request.POST['title'], request.POST['content'].replace('\r\n', '\n')
        )
    return render(request, "my_app/page.html")

注意: 请使用 request.POST['content'] 而不是 request.POST.get('content')。使用 .get(...) 通常只是消除错误而不解决问题:如果键确实丢失,它会正常工作。但如果该键的值真的是必需的,那么在后续过程中它只会导致更多麻烦。

英文:

This looks to me like a difference in how new lines are encoded. Indeed, Windows uses a carriage return (\r)&nbsp;<sup>[wiki]</sup> and then a line feed (\n)&nbsp;<sup>[wiki]</sup>, whereas Linux and Mac OS X use a line feed (\n) only. Now often certain systems will then also interpret this as a new line. But this is rendering, not the content. Likely the editor in which you look at the file has set the line endings on \n or LF or Linux.

You can however clean the input before saving it with:

<pre><code>def index(request):
if 'title' in request.POST and 'content' in request.POST:
save_data(
request.POST['title'], request.POST['content']<b>.replace('\r\n', '\n')</b>
)
return render(request, &quot;my_app/page.html&quot;)</code></pre>


> Note: Please use request.POST[&#39;content&#39;] over request.POST.get(&#39;content&#39;). Using <code>.get(&hellip;)</code> often only silences the error, but not the problem: indeed it will work if the key is missing. But if the value for that key is really required, it will only result in more trouble later in the process.

huangapple
  • 本文由 发表于 2023年5月15日 00:15:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76248513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定