Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7857959
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T21:12:19+00:00 2026-06-02T21:12:19+00:00

I’m looking to build a search form using a ModelForm class, that allows a

  • 0

I’m looking to build a search form using a ModelForm class, that allows a user to search for values in a Model by specific fields instead of a single field keyword search. I also want empty fields to be ignored.

I’ve looked into search engine options such as Haystack and Djapian, as well as approaching the problem manually in Django, but I don’t seem to be able to get results back when querying with multiple fields.

This is what I have so far for the view, based partially on answers to some similar questions on this site, in addition to what’s documented:

def search(request):
    error = False
    form = InfoForm()
    if 'field1' or 'field2' or 'field3' in request.GET:
        form = InfoForm(request.GET)
        if form.is_valid():
            cd = form.cleaned_data
            field1 = cd['field1']
            field2 = cd['field2']
            field3 = cd['field3']
            if not(field1 or field2 or field3):
                error = True
            else:
                query = Q()
                if request.GET['field1']:
                    query &= Q(field1__icontains=request.GET['field1'])
                if request.GET['field2']:
                    query &= Q(field2__icontains=request.GET['field2'])
                if request.GET['field3']:
                    query &= Q(field3__icontains=request.GET['field3'])

                results = PersonInfo.objects.filter(query).distinct()

                return render_to_response('search/personsearch.html',
                        {'query': query,
                         'field1': field1,
                         'field2': field2,
                         'field3': field3,
                         'results': results,
                        },
                    context_instance=RequestContext(request))

    return render_to_response('search/infosearch.html',
            {'error': error,
             'form': form},
        context_instance=RequestContext(request))

I also tried this complex query straight from the documentation:

query = InfoModel.objects.get(
    Q(field1__icontains=field1) |
    Q(field2__icontains=field2) |
    Q(field3__icontains=field3)
)

In both cases, the query string ?field1=&field2=&field3= appears appended to the URL, and the page returns with the supplied field values in the field, as expected; but neither return a result or generate an error if all fields are left blank.

I’m obviously missing something, but for the life of me I can’t figure out what. Has anyone else encountered this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T21:12:21+00:00Added an answer on June 2, 2026 at 9:12 pm

    While debugging the search view, I found that the initial if condition against request.GET only returned True for one field, even if all the fields listed were in fact in the form.

    From there, the simplest method to achieve my multi-field search was to string .filter() methods together. Empty fields in the search form are ignored, as hoped for, but if all fields are empty, it returns you to the search form with a properly handled error.

    def search(request):
        errors = []
        if 'field1' in request.GET:
            field1 = request.GET['field1']
            field2 = request.GET['field2']
            field3 = request.GET['field3']
            if not ((field1 or field2) or field3):
                errors.append('Enter a search term.')
            else:
                results = MyModel.objects.filter(
                    field1__icontains=field1
                ).filter(
                    field2__icontains=field2
                ).filter(
                    field3__icontains=field3
                )
                query = "Field 1: %s, Field 2: %s, Field 3: %s" % (field1, field2, field3)
                return render_to_response('search/search_results.html',
                        {'results': results, 'query': query})
        return render_to_response('search/search_form.html',
                {'errors': errors})
    

    The query string here now simply returns a formatted list of search terms, which you can drop into your template. But you can also return the variables directly and place them in another form on the search results page, if you want.

    Pagination also works nicely on the search results, which is essential for any real-world application. Rename results above to results_list, and the code from the Django documentation on Pagination can be plugged into your view. One caveat I found, you have to add a new variable that contains your search string and include that at the front of your pagination links, or you get returned to the search form when you click the ‘next’ or ‘previous’ links as defined in the docs.

    Lastly, it seems to work best when you build the form in HTML instead of relying on Django’s ModelForm class. That way you don’t have to pull your hair out trying to debug form validation errors, and can define your own validation rules inside your view function.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I am reading a book about Javascript and jQuery and using one of the
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.