Django: Search Multiple Fields of A Django Model with Multiple Input field (with Drop Down) in HTML












0















How can I implement a Drop-Down search in Django where users can search through a listing of second hand cars. The HTML search page will have 3 dropdown search input for Brand, Colour, Year. Once users select a choice of brand, colour and year, the listings will return a list of cars that matches that requirement.



class SecondHandCar(models.Model):
brand = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
colour = models.CharField(Category, on_delete=models.CASCADE)
year = models.IntegerField(blank=False)


I would appreciate any ideas on what I need to do. I had a look at Q lookups, django haystack, but I'm unsure which would fit my needs. I think I would appreciate seeing how I could integrate this with the HTML side of things to pass the query from multiple input fields to Django.










share|improve this question



























    0















    How can I implement a Drop-Down search in Django where users can search through a listing of second hand cars. The HTML search page will have 3 dropdown search input for Brand, Colour, Year. Once users select a choice of brand, colour and year, the listings will return a list of cars that matches that requirement.



    class SecondHandCar(models.Model):
    brand = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True)
    colour = models.CharField(Category, on_delete=models.CASCADE)
    year = models.IntegerField(blank=False)


    I would appreciate any ideas on what I need to do. I had a look at Q lookups, django haystack, but I'm unsure which would fit my needs. I think I would appreciate seeing how I could integrate this with the HTML side of things to pass the query from multiple input fields to Django.










    share|improve this question

























      0












      0








      0








      How can I implement a Drop-Down search in Django where users can search through a listing of second hand cars. The HTML search page will have 3 dropdown search input for Brand, Colour, Year. Once users select a choice of brand, colour and year, the listings will return a list of cars that matches that requirement.



      class SecondHandCar(models.Model):
      brand = models.CharField(max_length=250, unique=True)
      slug = models.SlugField(max_length=250, unique=True)
      description = models.TextField(blank=True)
      colour = models.CharField(Category, on_delete=models.CASCADE)
      year = models.IntegerField(blank=False)


      I would appreciate any ideas on what I need to do. I had a look at Q lookups, django haystack, but I'm unsure which would fit my needs. I think I would appreciate seeing how I could integrate this with the HTML side of things to pass the query from multiple input fields to Django.










      share|improve this question














      How can I implement a Drop-Down search in Django where users can search through a listing of second hand cars. The HTML search page will have 3 dropdown search input for Brand, Colour, Year. Once users select a choice of brand, colour and year, the listings will return a list of cars that matches that requirement.



      class SecondHandCar(models.Model):
      brand = models.CharField(max_length=250, unique=True)
      slug = models.SlugField(max_length=250, unique=True)
      description = models.TextField(blank=True)
      colour = models.CharField(Category, on_delete=models.CASCADE)
      year = models.IntegerField(blank=False)


      I would appreciate any ideas on what I need to do. I had a look at Q lookups, django haystack, but I'm unsure which would fit my needs. I think I would appreciate seeing how I could integrate this with the HTML side of things to pass the query from multiple input fields to Django.







      python html django






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 23 '18 at 7:20









      moonfairymoonfairy

      346




      346
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You can do this with a new endpoint where you can search the cars based on the required filters. I dont know if you want all of them combined to select cars or either one of which to be satisfied, because of which I have mentioned both.



          Solution:



          url(r'^search_cars/$'. views.search_cars, name='search-cars')

          def search_cars(request, *args, **kwargs):
          content_type = 'application/json'

          # I think you only need ajax, but you can choose to remove this
          if request.is_ajax():
          brand = request.GET.get('brand')
          colour = request.GET.get('colour')
          year = request.GET.get('year')

          # checking if all 3 are present
          if brand is None or color is None or year is None:
          return HttpResponse({
          'success': False,
          'message': 'Required fields are missing.'
          }, content_type=content_type)

          # depending on how you want to filter
          # this will choose cars which have either brand, colour or year
          filters = Q(Q(brand=brand) | Q(color=colour) | Q(year=year))
          second_hand_cars = SecondHandCars.objects.filter(filters)

          # or
          # you can choose cars which satisfy all three of these together
          filters = {'brand': brand, 'colour': colour, 'year': year}
          second_hand_cars = SecondHandCars.objects.filter(**filters)

          # serialize the objects and return the json response
          data =
          for car in second_hand_cars:
          data.append({
          'brand': car.brand,
          'colour': car.colour,
          'year': car.year,
          'description': car.description,
          'slug': car.slug
          })

          return HttpResponse({
          'success': True,
          'data': data,
          }, content_type=content_type)
          else:
          return HttpResponse({
          'success': False,
          'message': 'Only AJAX method is allowed.'
          }, content_type=content_type)

          // JavaScript code to make an ajax request
          // when all three dropdowns are selected with appropriate values.
          // assuming you are using jQuery.

          // add a common class to all 3 dropdowns to monitor changes
          $(document).on('change', '.filter-dropdown', function() {
          # all three will provide attribute `value` of `option` tag.
          var brand = $('#brandDropdown').children('option:selected').val();
          var colour = $('#colourDropdown').children('option:selected').val();
          var year = $('#yearDropdown').children('option:selected').val();

          # add a default selected `option` tag with value `""`
          if (brand !== "" && colour !== "" && year !== "") {
          var data = {
          'brand': brand,
          'colour': colour,
          'year': year
          }

          $.ajax({
          url: '/search_cars/',
          type: 'GET',
          data: data,
          dataType: 'json',
          success: function(response) {
          if (response.success) {
          // render cars from `response.data`
          } else {
          // show message from `response.message`
          }
          },
          error: function(errorResponse) {
          // show error message
          }
          });
          } else {
          return;
          }
          });


          Ref:

          * AJAX Docs

          * How to make an AJAX request without jQuery

          * Q queries in Django






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53442223%2fdjango-search-multiple-fields-of-a-django-model-with-multiple-input-field-with%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You can do this with a new endpoint where you can search the cars based on the required filters. I dont know if you want all of them combined to select cars or either one of which to be satisfied, because of which I have mentioned both.



            Solution:



            url(r'^search_cars/$'. views.search_cars, name='search-cars')

            def search_cars(request, *args, **kwargs):
            content_type = 'application/json'

            # I think you only need ajax, but you can choose to remove this
            if request.is_ajax():
            brand = request.GET.get('brand')
            colour = request.GET.get('colour')
            year = request.GET.get('year')

            # checking if all 3 are present
            if brand is None or color is None or year is None:
            return HttpResponse({
            'success': False,
            'message': 'Required fields are missing.'
            }, content_type=content_type)

            # depending on how you want to filter
            # this will choose cars which have either brand, colour or year
            filters = Q(Q(brand=brand) | Q(color=colour) | Q(year=year))
            second_hand_cars = SecondHandCars.objects.filter(filters)

            # or
            # you can choose cars which satisfy all three of these together
            filters = {'brand': brand, 'colour': colour, 'year': year}
            second_hand_cars = SecondHandCars.objects.filter(**filters)

            # serialize the objects and return the json response
            data =
            for car in second_hand_cars:
            data.append({
            'brand': car.brand,
            'colour': car.colour,
            'year': car.year,
            'description': car.description,
            'slug': car.slug
            })

            return HttpResponse({
            'success': True,
            'data': data,
            }, content_type=content_type)
            else:
            return HttpResponse({
            'success': False,
            'message': 'Only AJAX method is allowed.'
            }, content_type=content_type)

            // JavaScript code to make an ajax request
            // when all three dropdowns are selected with appropriate values.
            // assuming you are using jQuery.

            // add a common class to all 3 dropdowns to monitor changes
            $(document).on('change', '.filter-dropdown', function() {
            # all three will provide attribute `value` of `option` tag.
            var brand = $('#brandDropdown').children('option:selected').val();
            var colour = $('#colourDropdown').children('option:selected').val();
            var year = $('#yearDropdown').children('option:selected').val();

            # add a default selected `option` tag with value `""`
            if (brand !== "" && colour !== "" && year !== "") {
            var data = {
            'brand': brand,
            'colour': colour,
            'year': year
            }

            $.ajax({
            url: '/search_cars/',
            type: 'GET',
            data: data,
            dataType: 'json',
            success: function(response) {
            if (response.success) {
            // render cars from `response.data`
            } else {
            // show message from `response.message`
            }
            },
            error: function(errorResponse) {
            // show error message
            }
            });
            } else {
            return;
            }
            });


            Ref:

            * AJAX Docs

            * How to make an AJAX request without jQuery

            * Q queries in Django






            share|improve this answer




























              1














              You can do this with a new endpoint where you can search the cars based on the required filters. I dont know if you want all of them combined to select cars or either one of which to be satisfied, because of which I have mentioned both.



              Solution:



              url(r'^search_cars/$'. views.search_cars, name='search-cars')

              def search_cars(request, *args, **kwargs):
              content_type = 'application/json'

              # I think you only need ajax, but you can choose to remove this
              if request.is_ajax():
              brand = request.GET.get('brand')
              colour = request.GET.get('colour')
              year = request.GET.get('year')

              # checking if all 3 are present
              if brand is None or color is None or year is None:
              return HttpResponse({
              'success': False,
              'message': 'Required fields are missing.'
              }, content_type=content_type)

              # depending on how you want to filter
              # this will choose cars which have either brand, colour or year
              filters = Q(Q(brand=brand) | Q(color=colour) | Q(year=year))
              second_hand_cars = SecondHandCars.objects.filter(filters)

              # or
              # you can choose cars which satisfy all three of these together
              filters = {'brand': brand, 'colour': colour, 'year': year}
              second_hand_cars = SecondHandCars.objects.filter(**filters)

              # serialize the objects and return the json response
              data =
              for car in second_hand_cars:
              data.append({
              'brand': car.brand,
              'colour': car.colour,
              'year': car.year,
              'description': car.description,
              'slug': car.slug
              })

              return HttpResponse({
              'success': True,
              'data': data,
              }, content_type=content_type)
              else:
              return HttpResponse({
              'success': False,
              'message': 'Only AJAX method is allowed.'
              }, content_type=content_type)

              // JavaScript code to make an ajax request
              // when all three dropdowns are selected with appropriate values.
              // assuming you are using jQuery.

              // add a common class to all 3 dropdowns to monitor changes
              $(document).on('change', '.filter-dropdown', function() {
              # all three will provide attribute `value` of `option` tag.
              var brand = $('#brandDropdown').children('option:selected').val();
              var colour = $('#colourDropdown').children('option:selected').val();
              var year = $('#yearDropdown').children('option:selected').val();

              # add a default selected `option` tag with value `""`
              if (brand !== "" && colour !== "" && year !== "") {
              var data = {
              'brand': brand,
              'colour': colour,
              'year': year
              }

              $.ajax({
              url: '/search_cars/',
              type: 'GET',
              data: data,
              dataType: 'json',
              success: function(response) {
              if (response.success) {
              // render cars from `response.data`
              } else {
              // show message from `response.message`
              }
              },
              error: function(errorResponse) {
              // show error message
              }
              });
              } else {
              return;
              }
              });


              Ref:

              * AJAX Docs

              * How to make an AJAX request without jQuery

              * Q queries in Django






              share|improve this answer


























                1












                1








                1







                You can do this with a new endpoint where you can search the cars based on the required filters. I dont know if you want all of them combined to select cars or either one of which to be satisfied, because of which I have mentioned both.



                Solution:



                url(r'^search_cars/$'. views.search_cars, name='search-cars')

                def search_cars(request, *args, **kwargs):
                content_type = 'application/json'

                # I think you only need ajax, but you can choose to remove this
                if request.is_ajax():
                brand = request.GET.get('brand')
                colour = request.GET.get('colour')
                year = request.GET.get('year')

                # checking if all 3 are present
                if brand is None or color is None or year is None:
                return HttpResponse({
                'success': False,
                'message': 'Required fields are missing.'
                }, content_type=content_type)

                # depending on how you want to filter
                # this will choose cars which have either brand, colour or year
                filters = Q(Q(brand=brand) | Q(color=colour) | Q(year=year))
                second_hand_cars = SecondHandCars.objects.filter(filters)

                # or
                # you can choose cars which satisfy all three of these together
                filters = {'brand': brand, 'colour': colour, 'year': year}
                second_hand_cars = SecondHandCars.objects.filter(**filters)

                # serialize the objects and return the json response
                data =
                for car in second_hand_cars:
                data.append({
                'brand': car.brand,
                'colour': car.colour,
                'year': car.year,
                'description': car.description,
                'slug': car.slug
                })

                return HttpResponse({
                'success': True,
                'data': data,
                }, content_type=content_type)
                else:
                return HttpResponse({
                'success': False,
                'message': 'Only AJAX method is allowed.'
                }, content_type=content_type)

                // JavaScript code to make an ajax request
                // when all three dropdowns are selected with appropriate values.
                // assuming you are using jQuery.

                // add a common class to all 3 dropdowns to monitor changes
                $(document).on('change', '.filter-dropdown', function() {
                # all three will provide attribute `value` of `option` tag.
                var brand = $('#brandDropdown').children('option:selected').val();
                var colour = $('#colourDropdown').children('option:selected').val();
                var year = $('#yearDropdown').children('option:selected').val();

                # add a default selected `option` tag with value `""`
                if (brand !== "" && colour !== "" && year !== "") {
                var data = {
                'brand': brand,
                'colour': colour,
                'year': year
                }

                $.ajax({
                url: '/search_cars/',
                type: 'GET',
                data: data,
                dataType: 'json',
                success: function(response) {
                if (response.success) {
                // render cars from `response.data`
                } else {
                // show message from `response.message`
                }
                },
                error: function(errorResponse) {
                // show error message
                }
                });
                } else {
                return;
                }
                });


                Ref:

                * AJAX Docs

                * How to make an AJAX request without jQuery

                * Q queries in Django






                share|improve this answer













                You can do this with a new endpoint where you can search the cars based on the required filters. I dont know if you want all of them combined to select cars or either one of which to be satisfied, because of which I have mentioned both.



                Solution:



                url(r'^search_cars/$'. views.search_cars, name='search-cars')

                def search_cars(request, *args, **kwargs):
                content_type = 'application/json'

                # I think you only need ajax, but you can choose to remove this
                if request.is_ajax():
                brand = request.GET.get('brand')
                colour = request.GET.get('colour')
                year = request.GET.get('year')

                # checking if all 3 are present
                if brand is None or color is None or year is None:
                return HttpResponse({
                'success': False,
                'message': 'Required fields are missing.'
                }, content_type=content_type)

                # depending on how you want to filter
                # this will choose cars which have either brand, colour or year
                filters = Q(Q(brand=brand) | Q(color=colour) | Q(year=year))
                second_hand_cars = SecondHandCars.objects.filter(filters)

                # or
                # you can choose cars which satisfy all three of these together
                filters = {'brand': brand, 'colour': colour, 'year': year}
                second_hand_cars = SecondHandCars.objects.filter(**filters)

                # serialize the objects and return the json response
                data =
                for car in second_hand_cars:
                data.append({
                'brand': car.brand,
                'colour': car.colour,
                'year': car.year,
                'description': car.description,
                'slug': car.slug
                })

                return HttpResponse({
                'success': True,
                'data': data,
                }, content_type=content_type)
                else:
                return HttpResponse({
                'success': False,
                'message': 'Only AJAX method is allowed.'
                }, content_type=content_type)

                // JavaScript code to make an ajax request
                // when all three dropdowns are selected with appropriate values.
                // assuming you are using jQuery.

                // add a common class to all 3 dropdowns to monitor changes
                $(document).on('change', '.filter-dropdown', function() {
                # all three will provide attribute `value` of `option` tag.
                var brand = $('#brandDropdown').children('option:selected').val();
                var colour = $('#colourDropdown').children('option:selected').val();
                var year = $('#yearDropdown').children('option:selected').val();

                # add a default selected `option` tag with value `""`
                if (brand !== "" && colour !== "" && year !== "") {
                var data = {
                'brand': brand,
                'colour': colour,
                'year': year
                }

                $.ajax({
                url: '/search_cars/',
                type: 'GET',
                data: data,
                dataType: 'json',
                success: function(response) {
                if (response.success) {
                // render cars from `response.data`
                } else {
                // show message from `response.message`
                }
                },
                error: function(errorResponse) {
                // show error message
                }
                });
                } else {
                return;
                }
                });


                Ref:

                * AJAX Docs

                * How to make an AJAX request without jQuery

                * Q queries in Django







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 '18 at 8:03









                SachinSachin

                2,0951717




                2,0951717
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53442223%2fdjango-search-multiple-fields-of-a-django-model-with-multiple-input-field-with%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                    Alcedinidae

                    RAC Tourist Trophy