Newlines in textarea are doubled in number when saved

Viewed 525

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

'''

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?

1 Answers

I fixed this by using bytes(content, 'utf8') before passing it to the save function.

See: Why did bytes() solve my newlines problem?

if request.method == 'POST':
    save_entry(title, bytes(request.POST['new_content'], 'utf8'))
    return HttpResponseRedirect(reverse('encyclopedia:entry', args=(title,)))
Related