python-3.x 为什么我尝试提交表单时返回“不是有效的日期时间值”

ss2ws0br  于 2022-12-15  发布在  Python
关注(0)|答案(4)|浏览(142)

I created a form that allowed a user to select a desired date and time but when the form is submitted I got this error message

Not a valid datetime value

I tried including the desired format or the standard datetime format but I got the same result

#Form.py
class AddPostForm(FlaskForm):
    post_title = StringField('Share Title', validators=[DataRequired()])
    description = StringField('Description', validators=[DataRequired()])
    share_date = DateTimeField('Share Date', validators=[DataRequired()])

#views.py

@posts_blueprint.route('/add', methods=['GET', 'POST'])
@login_required
def add_post():
    form = AddPostForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            new_post = Post(form.post_title.data, form.description.data, 
                            current_user.id, form.share_date)

            db.session.add(new_post)
            db.session.commit()
            flash('New shared Item, {}added!'.format(new_post.post_title), 
                  'success')
            return redirect(url_for('posts.user_posts'))
       else:
           flash_errors(form)
           flash('ERROR! Recipe was not added.', 'error')

   return render_template('add_post.html', title='Add Item', form=form)

#add_post.html
{% from "_form_macros.html" import render_errors %}
{% import "bootstrap/utils.html" as utils %}
{% import "bootstrap/wtf.html" as wtf %}
{% extends "layout.html" %}
{% block body %}

<div class="content-section">
  <div class="page-header">
    <h2>Add a New Post</h2>
</div>

<div class="container">
  <form action="{{ url_for('posts.add_post') }}" method="post" 
                  enctype="multipart/form-data">
      {{ form.csrf_token }}
<div class="form-group row">
  <legend for="post_title" class="col-form-legend col-sm-3">Title</legend>
  <div class="col-sm-6">
    <input type="text" class="form-control" id="post_title" 
    name="post_title" placeholder="Enter Post title...">
    {{ render_errors(form.post_title) }}
  </div>
</div>

<div class="form-group row">
  <legend for="description" class="col-form-legend col-sm- 
  3">Description</legend>
  <div class="col-sm-6">
    <input type="text" class="form-control" id="description" 
    name="description" placeholder="Enter post description...">
    {{ render_errors(form.description) }}
  </div>
</div>

<div class="form-group row">
<legend for="share_date" class="col-form-legend col-sm-3">Sharing 
Date</legend>
<div class="col-sm-6">
  <input type="datetime-local" class="form-control" id="share_date" 
  name="share_date" placeholder="Sharing Date...">
  {{ render_errors(form.share_date) }}
 </div>
 </div>

<div class="center">
  <div class="offset-sm-2 col-sm-10">
    <button type="submit" class="btn btn-success">Add post</button>
  </div>
</div>
</form>
</div>
</div>
{% endblock %}

The user should be able to input the desired date and time and submit the form successfully

wgx48brx

wgx48brx1#

数据库所需的数据与表单所发送的数据之间似乎存在冲突。请尝试查看模型中使用的日期格式,并尝试将表单数据打印到控制台,以查看它提供的数据。此外,请尝试查看wtforms的文档,以查看它使用的日期类型,并将其与数据库模型中的日期字段相匹配。

ee7vknir

ee7vknir2#

You may need to check the format of the entered date matches what the DateTimeField is expecting.
See: DateTimeField Docs
Where the default format is: '%Y-%m-%d %H:%M:%S'
If you know the format you're submitting, you can provide it when you create the field object:

share_date = DateTimeField('Share Date', format='your-format', validators=[DataRequired()])
ubby3x7f

ubby3x7f3#

If you are using type="datetime-local" in you template you need to first makeing sure you're importing DateTimeLocalField not DateTimeField and then in my case i was also imported incorrectly:

from wtforms.fields import DateTimeLocalField

Instead of:

from wtforms import DateTimeLocalField

Its now working fine and not returning None to BackEnd!

template.html

<div class="form-floating mb-3">
  {{ form.dateTime(class="form-control", type="datetime-local") }}
  { form.dateTime.label(class="form-label") }}
</div>

myapp.py

from wtforms.fields import DateTimeLocalField
...

class PostEditor_form(FlaskForm):
    title = StringField('Enter The Title')
    dateTime = DateTimeLocalField(
        'Date Time', 
        format = "%Y-%m-%d %H:%M:%S", # secend needeed or its returning None
        default= datetime.utcnow
        )
    SendPost = SubmitField('Post')

@app.route("/Upload", methods=['GET', 'POST'])
@flask_login.login_required
def PostEditor(country):
    ...

    if form.validate_on_submit():
        dateTime = form.dateTime.data

form = PostEditor_form()

Image_path = ''
btn_sendpost = ''

print(form.dateTime.data)
# 2022-08-28 21:29:42.294706

#*  Upload-Image & Send-Data
if form.validate_on_submit():
    title = form.title.data
    bodyContent = form.bodyContent.data
    dateTime = form.dateTime.data        

    #* Upload Image Clicked
    if form.UploadImage.data:
        pfile = request.files['postImgae']
        filename = secure_filename(pfile.filename)
        Image_path = os.path.join("image/postImage/", f"{current_user.username}{datetime.utcnow().timestamp()}{filename}") 
        pfile.save(os.path.join(file_dir , 'static/'+Image_path))
        # flush_msg(message='Image Uploaded!', type='success')
        btn_sendpost = form.SendPost( class_="btn btn-primary col-3")

    #* Send Data
    if form.SendPost.data: 
        # Send to another api
        ...

        # Claering Data
        form.title.data = ''
        form.bodyContent.data = ''
        form.dateTime.data = ''
        
        flush_msg(message='Posted Successfully....! )', type='success')
    
if form.errors: print(form.errors)

return render_template(
    'Post-Editor.html',
    form=form, btn_sendpost=btn_sendpost)
gev0vcfq

gev0vcfq4#

我也遇到了同样的问题。我通过将窗体中DateLocalField的格式更改为以下格式来修复它:

outage_start = DateTimeLocalField(
        label="Outage Date",
        format="%Y-%m-%dT%H:%M",
        validators=[Optional()],
    )

相关问题