2015-05-03 48 views
0

我有一個表格,需要輸入1 integer的值。該整數值將是與htmltable中的行相關聯的標識。如何在WTForms中設置隱藏的整型值的值

template.html

{% block content %} 
<div id="formContainer" class="center top"> 
    <p class="lead">Select simulation session </p> 
    {% if simulationSessions %} 
    <table class="table table-striped"> 
    <thead> 
     <tr> 
     <th></th> 
     <th>#</th> 
     <th>Label</th> 
     <th>Date</th> 
     </tr> 
    </thead> 
    <tbody> 
    {% for simulationSession in simulationSessions %} 
     <tr> 
     <td><input id="id-{{ simulationSession.id }}" name="idRadio" type="radio" value="{{ simulationSession.id }}"> </td> 
     <td>{{ simulationSession.id }}</td> 
     <td>{{ simulationSession.label }}</td> 
     <td>{{ simulationSession.date.strftime('%d-%m-%y %H:%M') }}</td> 
     </tr> 
    {% endfor %} 
    </tbody> 
    </table> 
    <button type="button" class="btn btn-sm btn-success">Analyse</button> 
    {% else %} 
    <div class="alert alert-danger" role="alert"> 
     <strong>Oopsadazy!</strong> No simulations are registered in the database for this user. You need to run a simulation session before analyzing it! 
    </div> 
    {% endif %} 
</div> 
{% endblock %} 

每個錶行都有一個單選按鈕,並從選擇的按鈕值將是我的表格要求的唯一的事情。我決定用一個隱藏的IntegerField而不是RadioField。有可能做後者,但是我必須解決動態創建選擇的問題(當我參考我的view.py中的表單時,我無法將該列表作爲參數傳遞給我時,我決定採取相反的行動)。

form.py

class SimulationSessionSelectionForm(Form): 
    simulationSessoinId = IntegerField('simulationSessoinId', validators=[DataRequired()], widget=HiddenInput()) 

我的問題是我怎麼可以從所選擇的單選按鈕的值,並以此作爲對隱藏的整數字段中的數據,一旦提交表單?

這可能可以通過類似於html內部的腳本來完成。 (這不編譯)

{% set form.id.data %} 
    this.value 
{% endset %} 

的看法會是這個樣子:

view.py

@app.route('/dashboard', methods=['GET', 'POST']) 
@login_required 
def dashboard(): 
    form = SimulationSessionSelectionForm() 
    if form.validate_on_submit(): 
    redirect('/somewhere') 
    userkey = models.User.query.filter_by(id = current_user.get_id()).first().userKey 
    userSimulationSessions = models.SimulationSession.query.filter_by(userKey = userkey).all() 
    simulationSessions = [] 
    simulationSessionIds = [] 
    for simulation in userSimulationSessions: 
    simulationSessions.append({'id' : simulation.sessionID, 'label' : simulation.label, 'date' : simulation.date}) 
    simulationSessionIds.append(simulation.sessionID) 
    return render_template("dashboard.html", simulationSessions = simulationSessions, form = form) 

回答

0

此行模板增加了隱藏字段(和捷克斯洛伐克代幣)到

{{ form.hidden_tag() }} 

我想I co只要單選按鈕更改事件觸發,只需通過一些jquery腳本設置隱藏的IntegerField的值。爲此,我使用了以下代碼:

<script> 
    $(document).ready(function() { 
     $('input[type=radio][name=idRadio]').change(function() { 
     $('#simulationSessoinId').val(this.value)  
     }); 
    }); 

</script>