Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

python - Flask Multiple Wtforms in single page and single view

I am using flask where two forms are used. One form in main page and other form in a bootstrap modal.

Html-

<form method="POST" action="" enctype="multipart/form-data">
    {{ form.hidden_tag() }}
    <fieldset class="form-group">
        <div class="form-group">
          <div class="dropdown">
              <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                {{ form.sn.label(class="form-control-label") }}
              </button>
              <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="ddb">
                {% for i in form.sn%}
                <p class="dropdown-item">{{ i }}{{ i.label }}</p>
                {% endfor %}
              </div>
             <span id="dst"></span>
          </div>
        </div>

        <div class="form-group">
            {{ form.rd.label(class="form-control-label") }}
                {{ form.rd(class="form-control form-control-lg") }}
        </div>
    </fieldset>
    <div class="form-group">
        {{ form.submit1(class="btn btn-outline-info") }}
    </div>
</form>
</div>
<!-- Modal -->
<div class="modal fade"  id="exampleModal" tabindex="-1" role="dialog" aria- 
labelledby="exampleModalCenterTitle" aria-hidden="true">
 <div class="modal-dialog modal-dialog-centered" role="document">
   <div class="modal-content">
    <div class="modal-header">
    <h5 class="modal-title" id="exampleModalCenterTitle">Create Study Name</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
        <form method="POST" action="" enctype="multipart/form-data">
        {{ form1.hidden_tag() }}
            <fieldset class="form-group">
                <div class="form-group">
                    {{ form1.sn.label(class="form-control-label") }}

                    {% if form1.sn.errors %}
                        {{ form1.sn(class="form-control form-control-lg is-invalid") }}
                        <div class="invalid-feedback">
                            {% for error in form1.studynames.errors %}
                                <span>{{ error }}</span>
                            {% endfor %}
                        </div>
                    {% else %}
                        {{ form1.sn(class="form-control form-control-lg") }}
                    {% endif %}
                </div>
            </fieldset>
            <div class="form-group">
                {{ form1.submit2(class="btn btn-outline-info") }}
            </div>
        </form>
      </div>
    </div>
  </div>
</div>

forms.py in flask

class studyForms(FlaskForm):
    studynames = StringField('Study Name')
    submit2 = SubmitField('Add')


class Raw(FlaskForm):
    choice = [value[0] for value in db.session.query(stt.snn)]
    print(choice)
    choices = []
    for i in choice:
        choices.append((i,i))
    print(choices)
    sn= checkbox("Study Name", choices=choices, validators=[DataRequired()])
    rd= FileField('Upload File', validators=[DataRequired()])
    submit1 = SubmitField('Submit')

    @classmethod
    def new(cls):
        # Instantiate the form
        form = cls()
        choice = [value[0] for value in db.session.query(stt.snn)]
        print(choice)
        choices = []
        for i in choice:
            choices.append((i,i))
        print(choices)

        # Update the choices for the agency field
        form.sn.choices = choices
        return form

routes.py

@app.route("/raw", methods=['GET', 'POST'])
@login_required(role="enduser")
def raw():
    form = Raw()
    if form.submit1.data and form.validate_on_submit():
        try:
            os.mkdir(os.path.join(os.getcwd(), 'ui', 'static', 'users', current_user.email, form.sn.data[0]))
        except Exception as e:
            print(e)
            print('study name is already created for the user')
        try:
            os.mkdir(os.path.join(os.getcwd(), 'ui', 'static', 'users', current_user.email, form.sn.data[0], 'RAW'))
        except:
            print('RAW is created already already for the user')
        f = form.rd.data
        print('f.fil', f.filename)
        filename = secure_filename(f.filename)
        print(os.path.isdir(os.path.join(os.getcwd(), 'ui', 'static', 'users', current_user.email, form.sn.data[0], 'RAW')))
        dt = datetime.datetime.now()
        filename = filename.split('.')[0]+"_dt_"+str(dt.day)+"_"+str(dt.month)+"_"+str(dt.year)+"_"+str(dt.hour)+"_"+str(dt.minute)+"_"+str(dt.second)+"."+filename.split('.')[1]
        print(filename)
        f.save(os.path.join(os.getcwd(), 'ui', 'static', 'users', current_user.email, form.sn.data[0], 'RAW', filename))
        flash('Your Info is Saved', 'success')
        return redirect(url_for('raw'))

    form1 = studyForms()
    if form1.submit2.data and form1.validate_on_submit():
        print(form1.sn.data)
        sn = study_names.query.filter_by(study_name=form1.sn.data).first()
        print(sn)
        if sn == None:
            user_info1 = study_names(
                    study_name=form1.sn.data,
                )
            db.session.add(user_info1)
            db.session.commit()
        else:
            print('study name is already registered')

    choice = [value[0] for value in db.session.query(stt.snn)]
    print(choice)
    choices = []
    for i in choice:
        choices.append((i,i))
    print(choices)

    form = Raw.new()
    home_links = [
                Markup("""<a class="nav-item nav-link" href="/raw" style=""><b>Upload RAW Data</b></a>"""),
                Markup("""<a class="nav-item nav-link" href="/adam">Generate ADAM</a>"""),
                Markup("""<a class="nav-item nav-link" data-toggle="modal" data-target="#exampleModal">
                    Add Study Name</a>"""),
                Markup('''<a class="nav-item nav-link" href="/logout">Logout</a>'''),                    
    ]
    return render_template('raw.html', form=form, form1=form1, home_links=home_links, role='enduser', title="Client Login", address="Client")

When I submit the form1 it works perfectly, but when I submit the form, sometimes it goes to form1.validate_on_submit() or does nothing instead of executing form.validate_on_submit().

I go through all the blogs, in that they are saying add {{form.hidden_tag}} or {{form.csrf_tken}}.

I even got two csrf_token has same id in html, I also tried to change the first form's csrf_token id in html, like - {{form.csrf_token(id="some text")}}

But, nothing works...

What is the issue, I have been trying to solve, help me, thanks

question from:https://stackoverflow.com/questions/65930884/flask-multiple-wtforms-in-single-page-and-single-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...