在 django 中过滤结果的下拉列表

VT_*_*rew 1 python django

我想要一个基本的下拉框和我的 Django 页面上的提交按钮。当用户从下拉列表中选择某些内容并点击提交时,它会过滤结果。这应该很容易,但我花了几个小时却找不到我想要做的事情的例子。如何从POST获取数据?许多人建议不要使用原始 POST 数据并使用 form.is_valid() 代替,但是在这种情况下我没有使用 forms.py(不确定我是否需要使用 forms.py 来使用 form.is_valid??甚至如果我可以使用 forms.is_valid 如何提取用户选择的内容?)。

这是我的 views.py

def dashboard(request):
    plants = Plant.objects.all().order_by('IMS_plant')

    if request.POST:
        #selectedplant = #need to figure out how to get the value from the form in the template
        sightings = Sighting.objects.all().filter(IMS_plant=selectedplant)
        context =  {'sightings':sightings, 'plants': plants}
    else:
        sightings = Sighting.objects.all().order_by('date')    
        context =  {'sightings':sightings, 'plants': plants}

    return render_to_response('dashboard.html', context, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

这是我的模板

def dashboard(request):
    plants = Plant.objects.all().order_by('IMS_plant')

    if request.POST:
        #selectedplant = #need to figure out how to get the value from the form in the template
        sightings = Sighting.objects.all().filter(IMS_plant=selectedplant)
        context =  {'sightings':sightings, 'plants': plants}
    else:
        sightings = Sighting.objects.all().order_by('date')    
        context =  {'sightings':sightings, 'plants': plants}

    return render_to_response('dashboard.html', context, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

小智 6

使用 Django 方式。使用表格。

表格.py:

class FilterForm(forms.Form):
    selectedplant = forms.ModelChoiceField(queryset=Plant.objects.all().order_by('IMS_plant'), required=True)
Run Code Online (Sandbox Code Playgroud)

视图.py:

def dashboard(request):
    form = FilterForm()
    sightings = []
    if request.POST:
        form = FilterForm(request.POST)
        if form.is_valid():
            selectedplant = form.cleaned_data['selectedplant']
            sightings = Sighting.objects.filter(IMS_plant=selectedplant)
        else:
            sightings = Sighting.objects.all().order_by('date')  
    else:
        sightings = Sighting.objects.all().order_by('date')    

    context =  {'sightings':sightings, 'form': form}

    return render_to_response('dashboard.html', context, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

然后在模板中渲染 {{ form }}