python - dropdown that filters results in django -



python - dropdown that filters results in django -

i basic dropdown box , submit button on django page. when user selects dropdown , hits submit filters results. should pretty easy, have spent hours , can't find illustration of trying do. how info post? many people suggest not utilize raw post info , utilize form.is_valid() instead, not using forms.py in case (not sure need utilize forms.py utilize form.is_valid?? if can utilize forms.is_valid how extract user selected?).

here views.py

def dashboard(request): plants = plant.objects.all().order_by('ims_plant') if request.post: #selectedplant = #need figure out how value form in 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} homecoming render_to_response('dashboard.html', context, context_instance=requestcontext(request))

and here template class="snippet-code-html lang-html prettyprint-override"><form action="/dashboard/" method="post"> {% csrf_token %} <select name="plant"> <option selected="selected">all plants</option> {% plant in plants %} <option value="{{ plant.ims_plant }}">{{ plant.ims_plant }}</option> {% endfor %} </select> <input type="submit" value="select plant"> </form> <p> {% sighting in sightings %} <a href="/dashboard/sighting/{{ sighting.slug }}/ ">{{ sighting.date|date:"m/d/y" }} {{ sighting.brand }} ${{ sighting.price|intcomma }} </a> <br>{% endfor %}

use django-way. utilize forms.

forms.py:

class filterform(forms.form): selectedplant = forms.modelchoicefield(queryset=plant.objects.all().order_by('ims_plant'), required=true)

view.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} homecoming render_to_response('dashboard.html', context, context_instance=requestcontext(request))

and render {{ form }} in template

python django

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -