首页 > 解决方案 > 如何使用 python 将烧瓶 html 中的数据库 id 传递到 post 表单中

问题描述

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

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

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

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

如何将该 event_id 传递到我的 views.pypost函数中,以便将其添加到数据库中?先感谢您。

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))

标签: pythonhtmlflask-sqlalchemyflask-wtforms

解决方案


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

所以,而不是

def get(self, event_id):

我只能做

def post(self, event_id):

推荐阅读