Django表单ChoiceField数据库查询传递参数

t9aqgxwy  于 2023-02-06  发布在  Go
关注(0)|答案(1)|浏览(138)

我想创建一个Django表单ChoiceField。选项将从外部数据库中查询,并且应该通过参数{company_id}进行过滤。如何传递此参数?
views.py

if request.method == 'GET':
            
   company_id = 1
   site_id = 3
            
   return render(request, 'sites/new-column.html',
                          {
                              'company_id': company_id,
                              'site_id': site_id,
                              'form_newcolumn': NewColumn(company_id),
                          })

forms.py

class NewColumn(forms.Form):

    def __init__(self, *args, **kwargs):
        company_id = kwargs.pop('company_id')
        super(NewColumn, self).__init__(args, kwargs)
        self.company_id = company_id  # Add it as an instance variable

    engine = db.engine("Database")
    connection = engine.raw_connection()
    cursor = connection.cursor()
    cursor.execute(f"SELECT * FROM table WHERE id = '{company_id}' ; ")
    all_rows = cursor.fetchall()

    choices = forms.ChoiceField(
        choices=[(row[0], row[1]) for row in all_rows],
        help_text='Make your Choice'
    )

如何传递{company_id}只查询需要的选项?

rjee0c15

rjee0c151#

我在以下位置找到了适合我的解决方案:
Django Form ChoiceField set choices in View in Form initial
我在www.example.com中放置了select语句,并设置了“choices”和“initial”的形式views.py而没有在类定义中使用任何definit

相关问题