2017-09-24 68 views
0

我學習使用瓶,神社,WTForms語言創建測驗樣的Web應用程序,SQLAlchemy的等一旦用戶通過存儲在所有級別成功完成去這樣的語言課程JSON文件我希望應用程序爲他提供練習模式,用戶將在其中回答隨機選擇的級別。validate_on_submit()失敗時,單選按鈕選擇是動態生成

當我運行應用程序,我可以看到從隨機水平值產生的,因爲我想單選按鈕,但是當我選擇任何答案並提交,form.validate_on_submit()返回False和form.errors返回{ 'practiceform':[u'Not一個有效的選擇']}。當我將值硬編碼爲currentLevel變量時,它可以正常工作。

views.py

@user_blueprint.route('/courses/<course>/quiz/practice',methods=['GET','POST']) 
@login_required 
def practice(course): 
    courseClass = class_for_name("project.models", course.capitalize()) 
    courses = courseClass.query.filter_by(email=current_user.email).first() 
    maxLevel = courseClass.query.filter_by(email=current_user.email).first().get_maxLevel() 
    currentLevel = randint(0, maxLevel-1) # If this value is hard-coded or fetched from db, it works correctly 

    dic = generateQuestion(course, currentLevel) 
    display = dic["display"] 
    correct = dic["correct"] 
    options = dic["options"] 

    form = PracticeForm(request.form) 
    form.practiceform.choices = [(option, option) for option in options] 


    if form.validate_on_submit(): 
     practiceForm = form.practiceform.data 

     if ((practiceForm == correct) and courses): 
      # Do something 
      flash("Nice job", 'success') 
      return redirect(url_for('user.practice', course=course)) 

     else: 
      # Do something else 
      flash("Wrong answer", 'danger') 
      return redirect(url_for('user.practice', course=course)) 

    return render_template('courses/practice.html', form=form, display=display) 

forms.py

class PracticeForm(Form): 

    practiceform = RadioField('practice') 

practice.html

{% extends "_base.html" %} 
{% block content %} 

<form action='' method='POST' role='form'> 
    <p> 
     <!-- Tried put form.csrf, form.csrf_token, form.hidden_tag() here --> 
     {{ form.practiceform() }} 
    </p> 
    <input type="submit" value="submit" /> 
</form> 
{% endblock %} 

那麼,要我想念那裏?是什麼讓差異可以說,硬編碼的25級,其工作正常,或25號randint內隨機生成的?

回答

0

所以我發現,randint()問題引起的因爲實踐(當然)方法被調用的GET和POST行爲而導致有兩個不同的整數 - >兩種不同形式的大部分時間。所以我重構了代碼。保留我們採取行動的做法(當然)方法,並創建了處理POST操作的新方法,這解決了這個問題。

0

我的猜測是optionint,bug WTForms從request.form得到str

當數據從它被WTForms視爲string請求,除非你用coerce kwarg的wtforms.fields.*Field構造函數的顯式指定類型回來:

practiceform = RadioField('practice', coerce=int)