python - SelectForm in Flask with variable choices - Stack Overflow

admin2025-05-02  0

I started a project in flask, and I need a selection field than refresh with a words than any column in a table. So I create the conection with the data base, and executed the query for get the data, then I create a list with the values of the columns in the data, all it´s ok The next step is create a class form and in this class pass the list with the values than I need in the select field, so,this work if all the code is in the same file. But I need the form in other file, so I don´t know how pass the list to the class form(SelectionForm). I show my code a part of my code.

query=Query.consultingData()
RAW_QUERY=ManageResources.queryExecute(db,query)
Unique_Posibilitieslist=list(RAW_QUERY[1])
class SelectionForm(Form):
   Default_value=["Selecciona una empresa"]
   unique_names=Default_value+Unique_Posibilitieslist
   protocol = SelectField("protocol",
                            choices=[(i,i) for i in unique_names])

formulario=SelectionForm()

I want create other file called fileForms with the class Selection Form, and import in the main file, I show my code.

from fileForms import SelectionForm
query=Query.consultingData()
RAW_QUERY=ManageResources.queryExecute(db,query)
Unique_Posibilitieslist=list(RAW_QUERY[1])

formulario=SelectionForm(Unique_Posibilitieslist).GetSelection()

I tried this in the fileForms:

class SelectionForm(Form):
    def __init__(self,Unique_Posibilitieslist:list,formdata = None, obj = None, prefix = "", data = None, meta = None, *, extra_filters = None, **kwargs):
        super().__init__(formdata, obj, prefix, data, meta, extra_filters=extra_filters, **kwargs)
        self.Unique_Posibilitieslist=Unique_Posibilitieslist
    
    def GetSelection(self):
        Default_value=["Selecciona una empresa"]
        unique_names=Default_value+self.Unique_Posibilitieslist
        protocol = SelectField("protocol",
                           choices=[(i,i) for i in unique_names])
        return protocol

But this not work, I get this error "jinja2.exceptions.UndefinedError: 'wtforms.fields.core.UnboundField object' has no attribute 'protocol' Traceback (most recent call last)"

in the html file the code is the follow:

{% extends './layout.html' %}

{% block title %}
Lay Out Final
{% endblock %}

{% block css %}
    <link rel="stylesheet" href="{{url_for('static',filename='css/general_style.css')}}">
{% endblock %}


{% block body %}
<h1>ConsultaExitosa</h1>
{% from './macro.html' import render_field %}

<div class="row justify-content-center my-5">
    <div class="col-lg-6">
        <form action="GetResources" method="post">
            {{render_field(form.protocol,class="form-control")}}
            <br>
            <button class="btn btn-primary w-100 py-2" type="submit">Send</button>
        </form>
    </div>

    
</div>
{% endblock %}
转载请注明原文地址:http://anycun.com/QandA/1746138476a92106.html