1

I'm trying to do something fairly simple. Allow a user to type in a text field the searchterm, and select the search field from a drop down box. But I seem to be getting the above error.

Template

<form method='post' action=''>
<input type='text' id='searchterm'>
<select id='searchfield'>
    <option value='username'>Username</option>
    <option value='status'>Status</option>
</select>
</form>

View

def existing(request):
        if request.method == 'POST':
                searchterm = request.POST['searchterm']
                searchfield = request.POST['searchfield']
                records = User.objects.filter(searchfield=searchterm)
        else:
                records = User.objects.all()
        return render_to_response('gpon_table.html',locals())

Models

class User(models.Model):
    username = models.CharField(max_length=50)
    status = models.CharField(max_length=50)

Perhaps I am doing something wrong in the view.

Any help much appreciated.

4

1 回答 1

5

I believe the problem might be with how you're asking User.objects to search data. Since you're trying to pass in a dynamic keyword into the filter, you might have to pass it in as a **kwargs instead of directly as a filter parameter. I suspect that Django is reading "searchfield" as the literal keyword field name to search for rather than reading its value.

This link might provide more clarity on a possible solution. https://stackoverflow.com/a/659419/1011998

Here's an example of how you might implement the dynamic field with your current code setup.

As always, sanitize and restrict user input, otherwise a malicious user may be able to expose sensitive data other than that which is intended for filtering. (note: this hasn't been tested locally)

searchterm = request.POST.get('searchterm')
searchfield = request.POST.get('searchfield', 'username')

# Better to replace/populate this with form field choices
available_fields = ['username', 'status']

if not searchfield in available_fields:
    searchfield = 'username'

kwargs = {'{0}__{1}'.format(searchfield, 'icontains'): searchterm}
records = User.objects.filter(**kwargs)
于 2013-04-19T00:47:34.950 回答