0

现在我有一个 Flask 的下拉菜单,允许某人选择一个符号。我想要的符号是一个复选框,如 APPL、FB、TSLA 和其他,您可以在其中选择多个复选框。如果需要,他们可以检查其他内容,然后会出现一个文本框。然后将这些结果提交到数据库中。您可以在数据库中检查多个,但不能只选择一个。

write_db.py

class Stock(db.Model):
     __tablename__ = 'stocks'
     id = db.Column(db.Integer, primary_key=True)
     name = db.Column(db.String)
     symbol = db.Column(db.String)
     startDate = db.Column(db.String)
     endDate = db.Column(db.String)
     updated = db.Column(db.String)

    def __init__(self, name, symbol, startDate, endDate, updated):
         self.name = name
         self.symbol = symbol
         self.startDate = startDate
         self.endDate = endDate
         self.updated = updated

 # form for add_record and edit_or_delete
 # each field includes validation requirements and messages
class AddRecord(FlaskForm):
     # id used only by update/edit
     id_field = HiddenField()
     name = StringField('Name', [ InputRequired(),
         Length(min=3, message="Invalid name length")
         ])
     symbol = SelectField('Choose stock symbol', [ InputRequired()],
         choices=[ ('', ''), ('apple', 'APPL'),
         ('facebook', 'FB'),
         ('tesla', 'TSLA'),
         ('other', 'Other') ])
     startDate = StringField('Start Date (MM/DD/YYYY)', [ InputRequired(),
         Regexp(r'^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)'
                r'(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)'
                r'0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|'
                r'(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)'
                r'(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$', message="Invalid date"),
         Length(min=10, max=10, message="Invalid date length")
         ])
     endDate = StringField('End Date (MM/DD/YYYY)', [ InputRequired(),
         Regexp(r'^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)'
                r'(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)'
                r'0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|'
                r'(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)'
                r'(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$', message="Invalid date"),
         Length(min=10, max=10, message="Invalid date length")
         ])
     # updated - date - handled in the route
     updated = HiddenField()
     submit = SubmitField('Add/Update Record')

然后我想将符号或多个符号添加到数据库中。这是我的数据库现在的样子

 # add a new stock to the database
 @app.route('/add_record', methods=['GET', 'POST'])
 def add_record():
     form1 = AddRecord()
     if form1.validate_on_submit():
         name = request.form['name']
         symbol = request.form['symbol']
         startDate = request.form['startDate'] #todo startDate
         endDate = request.form['endDate'] #todo
         # get today's date from function, above all the routes
         updated = stringdate()
         # the data to be inserted into Sock model - the table, socks
         record = Stock(name, symbol, startDate, endDate, updated) #todo symbol, startDate
         # Flask-SQLAlchemy magic adds record to database
         db.session.add(record)
         db.session.commit()
         # create a message to send to the template
         message = f"The data for user {name} has been submitted."
         return render_template('add_record.html', message=message)
     else:
         # show validaton errors
         # see https://pythonprogramming.net/flash-flask-tutorial/
         for field, errors in form1.errors.items():
             for error in errors:
                 flash("Error in {}: {}".format(
                     getattr(form1, field).label.text,
                     error
                 ), 'error')
         return render_template('add_record.html', form1=form1)

这是我的 add_record 的 HTML 代码

add_record.html

{% extends 'bootstrap/base.html' %}
{% import "bootstrap/wtf.html" as wtf %}


{% block styles %}
{{ super() }}
    <style>
        body { background: #e8f1f9; }
    </style>
{% endblock %}


{% block title %}
Add a Stock
{% endblock %}


{% block content %}

<div class="container">
    <div class="row pb-5">
        <div class="col-md-10 col-lg-8 mx-lg-auto mx-md-auto">

        <h1 class="pt-5 pb-2">Add a New Stock</h1>

        {% if message %}

            <!-- the form was submitted and message exists -->
            <p class="lead"><strong>{{ message }}</strong></p>

            <!-- links -->
            <p><a href="{{ url_for('add_record') }}">Submit another stock.</a></p>

            <p><a href="{{ url_for('index') }}">Return to the index.</a></p>

        {% else %}

            <!-- the form is displayed when template opens via GET not POST -->

            <p class="lead alert alert-primary">Add a new stock to our inventory.</p>

            <p class="ml-4"><a href="{{ url_for('index') }}">Return to the index.</a></p>

            <!-- show flash - based on WTForms validators
                 see https://pythonprogramming.net/flash-flask-tutorial/
                 get_flashed_messages() exists here because of flash()
                 in the route function
                 -->
            {% with errors = get_flashed_messages() %}
                {% if errors %}
                    {% for err in errors %}
                        <div class="alert alert-danger alert-dismissible" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
                        {{ err }}
                        </div>
                    {% endfor %}
                {% endif %}
            {% endwith %}
            <!-- end of flash -->

            <!-- the form, thanks to WTForms -->
            {{ wtf.quick_form(form1) }}

        {% endif %}

        </div>
    </div>
</div>

{% endblock %}

谢谢!

4

0 回答 0