Hi, i just follwed the TechwothTim’s tutorial on Flask web app and encountered a pair of errors, some just typos but others were due to syntax updates. Now I’ve finished the app but have one last error that I can’t understand due to javascript. Here’s the code:
{% for note in user.notes %}
<li class="list-group-item">
{{ note.data }}
<button type="button" class="close" onClick="deleteNote({{ note.id }})">
<span arial-hidden="true">×</span>
</button>
</li>
{% endfor %}
</ul>
the errors are (button line):
Property assignment expected(before note.id) and ‘,’ expected
js code:
fetch('/delete-note', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ noteId: noteId })
}).then((res) => {
// to refresh the page //
window.location.href = '/';
});
}
last code:
from flask import Blueprint, render_template, request, flash, jsonify
from flask_login import login_user, login_required, logout_user, current_user
from .models import Note
from . import db
import json
views = Blueprint('views', __name__)
@views.route('/', methods=['GET', 'POST'])
@login_required
def home():
if request.method == 'POST':
note = request.form.get('note')
if len(note) < 1:
flash('Note is too short', category='error')
else:
new_note = Note(data=note, user_id=current_user.id)
db.session.add(new_note)
db.session.commit()
flash('Note added', category='success')
return render_template('home.html', user=current_user)
@views.route('/delete-note', methods=['POST'])
def delete_note():
#we're looking for id sent to us
#also we're sending the request not as a form, so the request is coming as data parameter, so we need to load it as json
note = json.loads(request.data)
noteId = note['noteId']
note = Note.query.get(noteId)
if note:
if note.user_id == current_user.id:
#this is only a security check to prevent users to delete other user notes
db.session.delete(note)
db.session.commit()
return jsonify({})
If you need more information:
TechwithTim’s Git project