2013-12-18 2 views
0

TextField 및 DateField가 포함 된 flask wtform을 사용하여 양식을 만들었습니다.flask-wtforms의 TextField가 날짜를 입력 한 후에도 빈 문자열을 반환합니다.

class SubmitReportForm(Form): 
    projectName=TextField('Name of Project', [Required('Please enter name of the project')]) 
    workDone=TextAreaField('work', [Required('Please state your progress')]) 
    fromDate=DateField('fromDate', [Required('Please mention a start date')]) 
    toDate=DateField('toDate', [Required('Please mention an end date')]) 
    submit=SubmitField('Submit') 

이 양식을 다루는 내보기 기능은 다음과 같습니다 : 내가 제출 버튼을 클릭 지금

@app.route('/user/<userName>/submit', methods=['GET', 'POST']) 
@login_required 
def submit(userName): 
    form=SubmitReportForm() 
    if request.method=='GET' : 
     return render_template("submit.html", userName=userName, form=form) 
    elif request.method =='POST' : 
     if form.is_submitted(): 
      print 'submitted' 
      if form.validate(): 
       print 'validated' 
      print form.errors 
      if form.validate_on_submit(): 
       project=form.projectName.data 
       fromDate=form.fromDate.data 
       toDate=form.toDate.data 
       progress=form.workDone.data 
       report=writeToFile(current_user.userName, project, fromDate, toDate, progress) 
       recipient=['[email protected]'] 
       subject="Monthly report by : " + current_user.userName 
       msg = Message(subject, sender =(current_user.userName, '[email protected]'), recipients = recipient) 
       msg.body= "Please find the attached report by "+ current_user.userName 
       with app.open_resource(report.name) as fp: 
        msg.attach(report.name, "text/plain", fp.read()) 
       mail.send(msg) 
       return render_template('successSubmit.html') 
    else: 
     flash(u'Please fill all the fields', 'error') 
     return render_template("submit.html", userName=userName, form=form) 

의 form.validate_on_submit()는 항상 false를 돌려 여기 내 양식 클래스입니다. 일부 디버깅을 한 후에 양식이 제출되었지만 유효성이 확인되지 않았습니다. 양식에 날짜를 입력 한 후에도 form.fromDate.data가 항상 없음 유형 개체를 반환하기 때문입니다.

내 HTML 파일 :

{% extends 'base.html' %} 

{% block content %} 

    {% with messages = get_flashed_messages() %} 
     {% if messages %} 

      {% for message in messages %} 
       <p><span style="color: red;">{{ message }}</span></p> 
      {% endfor %} 

     {% endif %} 
    {% endwith %} 

    <form action ='{{url_for('submit', userName=userName)}}' method='POST'> 
     {{form.hidden_tag()}} 

     <p> 
      Project Name: {{form.projectName}} 
     </p> 
     <br> 
     <p> 
      <label>Start Date : </label> {{form.fromDate}} 
     </p> 
     <br> 
     <p> 
      <label>End Date : </label> {{form.toDate}} 
     </p> 
     <br> 
     <p> 
      Progress Done: {{form.workDone(style="width: 699px; height: 297px;")}} 
     </p> 
     <br> 
     <p> 
      <input type='submit' value='Send Report'> 
     </p> 
     <br> 

    </form> 
{% endblock %} 

내가 DateFields 대신에 텍스트 필드를 사용하는 경우에도, 나는 빈 문자열을 얻을. 그래서 내가 어디가 잘못되었는지 말해 주시겠습니까 ?? 고맙습니다.

+0

'fromDate = form.fromDate.data'는 괄호가 필요합니다 :'fromDate = form.fromDate.data()'이제 코딩 된 방식으로 반환하는 값 대신 함수를 참조하십시오. – Kraay89

+0

'toDate = form .toDate.data'와'progress = form.workDone.data'는 같은 문제를 겪고있는 것 같습니다 – Kraay89

+0

아니요, fromDate와 toDate 만 None을 반환합니다, progress = form.workDone.data는 올바른 데이터를 반환하므로 괄호로 인한 것이 아닙니다. . – Akshay

답변

-1

템플릿에 {{ form.csrf_token }}이 있습니까 (form에 넣을 수 있음). 그냥 시도 해보고, 어쩌면 일해보십시오. 당신이 해낸다면, 그때 ... 저는 방금 문제를 만났습니다. CSRF에 의해 생겼습니다. 그래서이 변수를 추가하면 효과가있었습니다.

+2

'{{form.hidden_tag()}}'은 CSRF 토큰 ([docs] (https://flask-wtf.readthedocs.org/en/latest/api.html#flask_wtf.Form.hidden_tag))을 처리합니다. – jonafato

0

다음 코드는 유용해야합니다 ('템플릿'폴더에)

from flask import Flask, render_template, request 
from wtforms import Form 
from wtforms.fields import DateField 
from wtforms.validators import Required 


app = Flask(__name__) 
app.config['DEBUG'] = True 


class TestForm(Form): 
    foo_date = DateField('Foo Date', 
         [Required('Foo Date is required')], 
         format='%Y-%m-%d', 
         description='Date format: YYYY-MM-DD') 

@app.route("/", methods=['GET', 'POST']) 
def index(): 
    submitted_date = None 
    if request.method == 'POST': 
     form = TestForm(request.form) 
     if form.validate(): 
      submitted_date = form.foo_date.data 
    else: 
     form = TestForm() 

    return render_template('tpl.html', form=form, submitted_date=submitted_date) 


if __name__ == "__main__": 
    app.run() 

템플릿 tpl.html :

<!DOCTYPE html> 
<html> 
<body> 
<form method='POST' action=''> 
    <p>{{ form.foo_date.label }}: {{ form.foo_date }} {{ form.foo_date.description }}</p> 
    <input type='submit' value='Send foo date'> 
</form> 
{% if submitted_date %} 
<p style="color: green">You submitted successfully the following date: {{ submitted_date }}</p> 
{% endif %} 
{% if form.errors %} 
<h2>Errors</h2> 
<p style="color: red">{{ form.errors }}</p> 
{% endif %} 
</body> 
</html> 

조심, 당신은 폼 클래스 제대로 초기화하지 않습니다 요청 메소드가 POST 일 때 (내 코드 참조).