从Django表单ChoiceField检索选择的选项

时间:2018-11-30 20:17:00

标签: django

我正在尝试在Django Web应用程序上进行搜索。这样的想法是,用户将转到首页,并能够从属性(即OS,编译器等)的下拉列表中进行选择,然后提交搜索,该搜索应返回匹配的构建列表。我已经设置了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 个答案:

答案 0 :(得分: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页,其中介绍了{{1 }}。