从 Django 表单 ChoiceField 中检索选定的选项

Posted

技术标签:

【中文标题】从 Django 表单 ChoiceField 中检索选定的选项【英文标题】:Retrieve selected choices from Django form ChoiceField 【发布时间】:2018-11-30 20:17:00 【问题描述】:

我正在尝试在我的 Django Web 应用程序上创建搜索功能。这个想法是,用户将进入首页并能够从属性的下拉列表中进行选择(即操作系统、编译器等),然后提交他们的搜索,该搜索应返回匹配构建的列表。我已经设置了 ChoiceField 表单,并且我知道我需要运行的代码才能在我的下一个视图中获得正确的构建。我不知道如何将用户在点击提交时选择的值传递到下一个视图,以便我可以根据这些选择进行过滤。有什么帮助吗?

forms.py

from .models import * 

class BuildForm(forms.Form):
    build_OPTIONS = Builds.objects.values().distinct()
    ...
    Build_type = forms.ChoiceField(widget=forms.Select(), choices=build_OPTIONS)

views.py

from .forms import BuildForm

def index(request):
    builds = BuildForm()
    return render(request, 'ReportGenerator/index.html', 
"builds":builds)

templates/App/index.html

% if builds %
     <h2>Pick a Build</h2>
     <form method="POST" class="build-form">% csrf_token %
        builds.as_p 
     </form>
% else %
    <p>No reports are available.</p>
% endif %

【问题讨论】:

【参考方案1】:

对于您用作选择的 build_OPTIONS,最好在模型中定义它们,例如 this。然后你可以像这样在你的表单类中引用它们:

models.py

class Builds(models.Model):
    CHOICE1 = "Choice 1"
    CHOICE2 = "Choice 2"
    BUILD_OPTIONS_CHOICES = (
        (CHOICE1, 'Choice 1'),
        (CHOICE2, 'Choice 2'),
        (<value>, <human readable name>),
    )
    ...fields...

forms.py

from .models import * 

class BuildForm(forms.Form):
    ...
    Build_type = forms.ChoiceField(widget=forms.Select(), choices=Builds.BUILD_OPTIONS_CHOICES)

这是视图的示例。如果form.is_valid() 返回True,那么您可以访问form.cleaned_data['my_form_field_name'] 中的表单值

views.py

def index(request):
    # 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 = BuildForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # can access the form data in cleaned_data['form_field_name']
            print form.cleaned_data['build_type'] 

            # redirect to a new URL:
            return HttpResponseRedirect('/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = BuildForm()

    return render(request, 'index.html', 'form': form)

至于表单字段名,大概是build_options和build_type。通常它使用表单类中的任何变量名。为了让生活更轻松,我会将所有小写字符标准化,变量名称带有下划线,类名称大写首字母,常量全部大写等。有关更多信息,请参阅this 页面,其中描述了as_p() 的工作原理。

【讨论】:

以上是关于从 Django 表单 ChoiceField 中检索选定的选项的主要内容,如果未能解决你的问题,请参考以下文章

从视图中,如何将自定义“选择”传递到表单的 ChoiceField?

Django Form 将 ChoiceField 选项设置为 Form 被调用

Django 表单 ChoiceField 依赖于另一个 ChoiceField

Django 表单。使前端 <select> 需要 ChoiceField

基于选择的 Django 模板/ChoiceField 显示字段

带有Queryset的Django Form ChoiceField