0

views.py

def search(request):
    reportlist = []
    loc_id = request.POST.get('location')
    if loc_id:
        location_list = ReportLocation.objects.filter(title=loc_id)
        for locaton in location_list:                       
            reportlist.append(locaton.report)

forms.py

class SearchFilterForm(Form):
    location = forms.ChoiceField(widget=forms.Select(), choices='',required=False, initial='Your name')

    def __init__(self,user_id, *args, **kwargs):
        super(SearchFilterForm, self).__init__(*args, **kwargs)
        self.fields['location'] = forms.ChoiceField(choices=[('','All Location types')]+[(loc.id, str(loc.title)) for loc in Location.objects.filter(user=user_id).exclude(parent_location_id=None)])

models.py

class ReportLocation(models.Model):   
    report = models.ForeignKey(Report)    
    title = models.CharField('Location', max_length=200)

How to filter the title field in ReportLocation field with the selected choice.I tried with above filter query in views.py,but it is not showing any filtered data.Need help

1
  • Your title contains the id field? This is weird... Commented Aug 17, 2013 at 0:06

1 Answer 1

1

Your form is using location ids for its value keys, not location titles. ChoiceFields use the first part of each tuple in choices as the value which gets POSTed and the second part of each tuple is just the name of the choice as the user sees it. Add a print statement to check the value of your loc_id and you'll see what I mean.

So you'll want to look up a location title for the location id in request.POST. If your ReportLocation model has a ForeignKey to Location you can do something like

location_list = ReportLocation.objects.filter(location__id=loc_id)

but if that doesn't work with your schema you might have to look up the title as a separate query. Here's a simplistic example:

def search(request):
    reportlist = []
    loc_id = request.POST.get('location')
    if loc_id:
        # This will cause an error if loc_id isn't found,
        # it's just here as an example
        loc_title = Location.objects.get(id=loc_id).title
        location_list = ReportLocation.objects.filter(title=loc_title)
        for locaton in location_list:                       
            reportlist.append(locaton.report)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.