Search code examples
htmldjangomarkdownnewline

Rendering markdown inside of <textarea> adds newline


I am implementing a Wikipedia-like webapp with Django. Data for the different entries is stored in Markdown files on the server. I use markdown2 for the conversions. Everything works just fine but I run into a problem when I try to edit an existing entry. The server serves "edit.html" to the client, passing a django form populated with the existing data.

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>

When the browser renders the textarea which includes the data to be edited, newlines are inserted without my consent. This behaviour loops everytime I edit a text so that more and more newlines are added. I don't really understand what is going on. Does anyone have an idea?


Solution

  • The Python repr() allows to print a string while escaping every special character, very handy for debugging! I discovered that my code - for some obscure reason - was doubling up on newlines by adding the sequence \r\r\n. So in the end I just used regex to get rid of all the undesired characters at every edit. I consequently modified the following in views.py:

    # read the existing file.md and substitute all undesired characters
    content = re.sub('(\r\r\n)+', '\n', util.get_entry(title))
    

    Hope it will benefit someone in the future!