How to save markdown from a WTForm in a database using SQLAlchemy?

Viewed 739

I have a blog I am making where I create posts in the 'edit' route using markdown in a text area box. However, when I save the post, it converts some of my formatting in weird ways. For instance, when I have an apostrophe, such as in the word doesn't it does this:

doesn't

Here is the form code:

class Item(db.Model):
    __tablename__= 'item'
    id = db.Column(db.Integer,primary_key=True)
    title = db.Column(db.String(80),unique=False)
    content = db.Column(db.String(80),unique=False)
    x = db.Column(db.Float)
    y = db.Column(db.Float)
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    order = db.Column(db.Integer)

    def __init__(self,title,content,x,y,category_id,order):
        self.title = title
        self.content = content
        self.x = x
        self.y = y
        self.category_id = category_id
        self.order = order

Here is my edit route which handles saving the object in sqlalchemy:

@app.route('/edit/<itemid>',methods=('GET','POST'))
@requires_auth
def edit(itemid):
    item = Item.query.get(itemid)
    c = Category.query.get(item.category_id)
    form = ItemForm()
    form.title.data=item.title
    category = c.name
    form.content.data=item.content
    if request.method == 'POST':
        if request.form.get('title'):
            item.title = request.form['title']
            item.content = request.form['content']
            print item.content, 'conetnt'
            db.session.add(item)
            db.session.commit()
            return redirect(url_for('view',itemid=item.id))
        else:
            flash('Title and Content and Category are required.','danger')
    return render_template('edit.html',item=item,form=form, category=category)

and here is the template:

<div id="container" style="padding:10px">
        <form method="POST" action="{{ url_for('edit',itemid=item.id) }}" id="text-input">
            {{ form.csrf_token }}
            <div style="margin-left:30px;margin-top:20px;">
                Title: {{ form.title }} {{ category }}
            </div>
            <br>

            <div id="editor">
            {{ form.content( **{':value':'input','@input': 'update'}) }}
                <div id="preview" v-html="compiledMarkdown"></div>
            </div>
            <br>
            <input type="submit" value="Save" class="btn btn-secondary" >
        </form>
</div>

as you can see I have an editor which is filled with content using {{ form.content( **{':value':'input','@input': 'update'}) }} Then I am using vue.js to create a markdown preview of the text - which interestingly shows things formatted correctly until it opens a saved file. I believe that the template is passing the data to the server incorrectly. This is because when I print the content in the server code before saving it in the database, it is formatted incorrectly.

How do I do this correctly?

0 Answers
Related