我有一个网站帖子创建者/编辑者正在撰写文章。我已经成功地创建了帖子(保存到json),从同一个数据库中获取了已发布帖子的下拉菜单列表(第二,所有posts.json,这是帖子列表的来源。),以及元素表中填充了上述信息。然后,我可以保存它,并且它确实正在写入文件。问题是,保存的帖子中文本字段中的数据没有更新。它保存与multidict一起传递的原始数据。我可以手动将其更新为:例如。 form.title.data =“ New Title”,它以这种方式保存,因此我知道它在保存端正确处理了所有内容。如果有人对如何从表单字段获取更新的信息有任何想法,请多谢。谢谢。
第103行的构造函数 码: https://hastebin.com/lafavifike.py
from flask import Flask, render_template, request, flash, redirect, url_for
from QFlask import QFlask
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired
from wtforms.fields import Field, TextAreaField, TextField, SelectField
from wtforms.widgets import TextArea
import os, json
from werkzeug.datastructures import MultiDict
app = Flask(__name__)
app.config['SECRET_KEY'] = "test"
class editPostForm(FlaskForm):
id_pos = ['blog_posts', 'security_posts', 'game_posts','music_posts','project_posts']
file_path_all = str(os.getcwd()) + "\\static\\allposts.json"
with open(file_path_all, 'r') as post_edit:
all_posts = json.load(post_edit)
posts = [('default', 'Choose Post To Edit')]
for key in all_posts.keys():
if key not in id_pos:
posts.append((all_posts[key]['id'], all_posts[key]['title']))
loadform = SelectField('Choose Post', choices=posts)
loadposts = SubmitField('Load')
class PostForm(FlaskForm):
#Actual form fields
categories = [('blog_posts','Blog Post'), ('security_posts','Security Post'),('game_posts','Games Post'),('music_posts','Music Post'),('project_posts','Projects Post')]
category = SelectField('Category', choices = categories, validators = [DataRequired()])
title = StringField('Title', validators=[DataRequired()])
date = StringField('Date', validators=[DataRequired()])
content = TextAreaField('Content', validators=[DataRequired()], widget=TextArea())
submit = SubmitField('Submit')
@app.route('/', methods=['POST', 'GET'])
def index():
file_path = str(os.getcwd()) + "\\static\\posts.json"
with open(file_path, 'r+') as post_edit:
data = json.load(post_edit)
positions = {}
for key in data['id_pos'].keys():
positions[key] = data['id_pos'][key]
#Create Post Form
prefixs = {'1':'blog_posts','2':'security_posts',"3":"game_posts","4":"music_posts","5":"project_posts"}
form = PostForm()
edit_form = editPostForm()
if request.method == 'POST':
print(edit_form.loadform.data)
if edit_form.loadform.data != 'None':
return redirect('/edit_post/'+ edit_form.loadform.data)
else:
form.validate()
category = form.category.data
title = form.title.data
date = form.date.data
content = form.content.data
post_id = str(int(positions[category]) +1)
post = {
"id": post_id,
"title": title,
"date": date,
"content": content
}
#Update data structure, and save back to the file
data['id_pos'][category] = post_id
data[category][post_id] = post
#SAVE POST
data['index_posts'][post_id] = post
with open(file_path, 'w') as post_edit:
json.dump(data, post_edit)
print('Post Saved')
flash('Post Saved')
file_path_all = str(os.getcwd()) + "\\static\\allposts.json"
with open(file_path_all, 'r+') as file:
data = json.load(file)
with open(file_path_all, 'w') as file:
data[post_id] = post
json.dump(data, file)
return redirect(url_for('index'))
return render_template('post_editor.html', title="Post Creator", form=form, edit_form = edit_form)
@app.route('/edit_post/<id>', methods=['GET','POST'])
def edit_post(id):
#Load data from JSON Files. posts= categorized posts, allposts is all posts key'd by id.
file_path_all = str(os.getcwd()) + "\\static\\allposts.json"
file_path = str(os.getcwd()) + "\\static\\posts.json"
with open(file_path, 'r+') as post_edit:
data = json.load(post_edit)
with open(file_path_all, 'r') as post_edit:
all_posts = json.load(post_edit)
posts = [('default', 'Choose Post To Edit')]
for key in all_posts.keys():
posts.append((all_posts[key]['id'], all_posts[key]['title']))
#Auto filling category and data for fields
prefixs = {'1':'blog_posts','2':'security_posts',"3":"game_posts","4":"music_posts","5":"project_posts"}
category = prefixs[id[0]]
form = PostForm(MultiDict([("id", id),("title", data[category][str(id)]['title']) ,("date", data[category][str(id)]['date']),("content" , data[category][str(id)]['content'])]))
if request.method == "POST":
form.validate()
data[category][str(id)] = {
'id': str(id),
'title': form.title.data,
'date': form.date.data,
'content': str(form.content.data)
}
all_posts[str(id)] = {
'id': str(id),
'title': form.title.data,
'date': form.date.data,
'content': str(form.content.data)
}
#Write to file.
print('Saving the edited post..')
with open(file_path_all, 'w') as file:
json.dump(all_posts,file)
print('File Saved ')
with open(file_path, 'w') as file:
json.dump(data,file)
flash('File Saved')
return redirect('/')
return render_template('edited_post.html', title="Post Editor", form = form)
if __name__ == '__main__':
QFlask(app).run(title="Web Post Editor", zoom=0, width=600, height= 600)
posteditor.html
<html>
<head><title> Post Editor</title>
<style src="{{url_for('static', filename='css/bootstrap.min.css')}}"></style>
<style>
pre{
content-align: left;
}
body{
color: grey;
background-image: url({{url_for('static', filename='img/editor-bg.jpg')}});
}
</style>
<script src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
<script src="{{url_for('static', filename='js/popper.js')}}"></script>
<script src="{{url_for('static', filename='js/bootstrap.min.js')}}"></script>
</head>
<body>
<div class="container">
{% with message = get_flashed_messages()%}
<ul class="flashes">
{{message}}
</ul>
{% endwith%}
{{ form.csrf_token }}
<form method="POST" action="" id="selection">
<fieldset class="form-group">
<div class="form-group">
{{edit_form.loadform.label(class="form-control-label")}}
{{ edit_form.loadform(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ edit_form.loadposts(class="btn btn-outline-info")}}
</div>
</fieldset>
</form>
<form method="POST" action="">
<fieldset class="form-group">
<div class="form-group">
{{ form.category.label(class="form-control-label")}}
{{ form.category(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.title.label(class="form-control-label")}}
{{ form.title(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.date.label(class="form-control-label")}}
{{ form.date(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.content.label(class="form-control-label")}}
{{ form.content(cols="50", rows="20",class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</fieldset>
</form>
</div>
</body>
</html>
editedpost.html:
<html>
<head><title> Post Editor</title>
<style src="{{url_for('static', filename='css/bootstrap.min.css')}}"></style>
<style>
pre{
content-align: left;
}
body{
color: grey;
background-image: url({{url_for('static', filename='img/editor-bg.jpg')}});
}
</style>
<script src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
<script src="{{url_for('static', filename='js/popper.js')}}"></script>
<script src="{{url_for('static', filename='js/bootstrap.min.js')}}"></script>
</head>
<body>
<div class="container">
{% with message = get_flashed_messages()%}
<ul class="flashes">
{{message}}
</ul>
{% endwith%}
<form method="POST" action="">
{{ form.csrf_token }}
<fieldset class="form-group">
<div class="form-group">
{{ form.category.label(class="form-control-label")}}
{{ form.category(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.title.label(class="form-control-label")}}
{{ form.title(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.date.label(class="form-control-label")}}
{{ form.date(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.content.label(class="form-control-label")}}
{{ form.content(cols="50", rows="20",class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</fieldset>
</form>
</div>
</body>
</html>
答案 0 :(得分:0)
我找到了答案(在某些IRC人士的帮助下)。问题是表单数据总是从初始化版本中提取。它从未从页面请求更新。在data [category] [str(id)] =中,应通过request.form.get('title')
更新值