使用来自模型外部的数据填充 Django 表单下拉列表

时间:2021-06-28 22:10:27

标签: python django

我想使用来自 3rd 方 API(即,不是来自模型)的数据填充 Django 应用程序中的下拉列表,该数据取决于视图中的参数。

我读过的所有博客/文章都依赖于模型,但不会从另一个数据集(或在直接模型查询之外计算或生成的数据)更新。

我想要做的伪代码是这样的:

forms.py

class myform(forms.Form):
    # load the form with no choices because they will be populated dependent on what is in the view
    dropdown1=forms.ChoiceField(label="Dropdown 1",choices=[])

views.py

from .forms import myform

def get_dropdown_choices(person_id):
    # go to external data source and get a list of items as a function of the person_id
    return choices_list

def index(request,person_id):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = myform(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a form
    # populated with the choices based on who is in the view
    else:
        choices_list=get_dropdown_choices(person_id)
        #
        # this is where I am confused
        #
        form = myform(dropdown1.choices=choices_list)

    return render(request, 'name.html', {'form': form})

下拉列表中的数据(即 selections_list 列表)不是任何 Django 模型中的东西,也不是可以从它们中查询的东西。

任何帮助将不胜感激。

0 个答案:

没有答案
相关问题