【问题标题】:How do I pass the database id from flask html into a post form with python如何使用 python 将烧瓶 html 中的数据库 id 传递到 post 表单中
【发布时间】:2020-05-15 02:56:10
【问题描述】:

更新: 我觉得我的问题太混乱了。总结一下,没有下面的所有垃圾。如何将 HTML 链接中的参数传递到我的 python 文件的 POST 函数中?我需要将该 HTML 参数作为我对数据库的提交的一部分。到目前为止我的搜索还没有成功。

我已经填充了一个 html 页面 event_details.html,其中包含与表 events_id 行匹配的所有表 events 条目。在这个页面中,我有一个链接按钮来添加另一个 html 页面add_events_details.html 以向数据库添加一个新条目。

此链接将用户带到另一个带有 wtform 的页面,我想将相同的 events_id 数据库行传递给表单,以保存用户输入此数据。

所以,设置是,我将条目的 event_id 传递给add_events_details.html。但是我只能将这个event_id 传递给get 而不能传递给post 函数,它在我需要event_id 数据的post 函数中,所以我可以将它添加到数据库中。

如何将该 event_id 传递到我的 views.py post 函数中,以便我可以将其添加到数据库中?提前谢谢你。

event_details.html

<div class="jumbotron">
    {% if current_user.is_authenticated %}
    <h1>{{ current_user }}</h1>
    <p> This is the event details page </p>
    <a href="{{url_for('events.add_event_details', event_id=event_id)}}" class="btn btn-outline-primary" role="button">Add Schedule</a>
</div>      
....more code... to show entries

add_event_details.html

<div class="jumbotron">
    {% if current_user.is_authenticated %}
    <h1>{{ current_user }}</h1>
    <p> This is the event details page </p>
    <a href="{{url_for('events.add_event_details', event_id=event_id)}}" class="btn btn-outline-primary" role="button">Add Schedule</a>
</div>      

views.py 是

class AddEventDetailsView(MethodView):

    decorators = [login_required]
    template_file = 'add_event_details.html'
    form_class = EventForm

    def get(self, event_id):
        return render_template(self.template_file, form=self.form_class())

    def post(self):
        form = self.form_class()
        print(form.errors)

        if form.validate_on_submit():
            #  I added this print to find out its type
            print(type(form.events_id.data))
            # This form returns the class model, so I just have to ask it for the \
            #  specific column that I want it to return

            # events_id = form.events_id.data.id
            user_id = current_user.id # This assumes that the person logged in is the company
            eventdetails = Eventdetails(
                schedule_name=form.schedule_name.data,
                event_id=event_id,
                user_id=user_id,
                naics=form.naics.data
            )
            print(f"The user id is {user_id}")
            db.session.add(eventdetails)
            db.session.commit()
            flash("Thank you for registering your event.")
            return redirect(url_for('events.event_details', event_id=event_id))

【问题讨论】:

    标签: python html flask-sqlalchemy flask-wtforms


    【解决方案1】:

    我想我想通了。我可以将相同的参数传递给我的POST 请求并以这种方式使用它,它工作正常。

    所以,而不是

    def get(self, event_id):
    

    我能做到

    def post(self, event_id):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多