1

Let's say I have the following form:

<form id="search-form" class="form-horizontal" method="GET" action="/results/" role="form">
    <input type="text" class="form-control" id="query" name="query">

    <button type="submit"  form="search-form" class="btn btn-primary">
        <span class="glyphicon glyphicon-search" aria-hidden="true"></span>       
    </button>
</form>

Currently, when the form is submitted, the url contains the query as a parameter, like so: www.<my-domain>.com/results?query=<some-query>. However, for SEO purposes, I want to convert this to a 'clean url', which would look more like this: www.<my-domain>.com/results/<some-query>.

I've made the following modifications to my urls.py:

urlpatterns = [
    ...
    url(r'^results/(?P<query>[a-zA-Z ]+)$', views.ResultsView.as_view(), name="results"),
    ...
]

So I should be able to grab the query value in my ResultsView like this:

class ResultsView(TemplateView):

    def dispatch(self, request, *args, **kwargs):

        query = kwargs.get('query')

How can I submit the form so it'll match with the corresponding url pattern? I've tried fiddling with the form action passing the input id to it, like this: action="/results/query/", but obviously, it thinks query is a literal string, and doesn't replace it with the value of the input.

Sam
  • 2,172
  • 3
  • 24
  • 43
  • You need to use Js for it because you can't paste input value as a part of url string like this `/results/query/` by standart django methods – amarynets Sep 05 '17 at 04:51
  • @marni Yeah, that makes sense. I'm not that great at JS though. If you can post a working example, I'll mark the answer as correct. – Sam Sep 05 '17 at 04:53
  • even if you work with SEO purposes, you should use the GET method, is cleaner and easier – Mauricio Cortazar Sep 05 '17 at 05:37

1 Answers1

1

You can easily do this with JQuery. When clicking the button, prevent default action, and define the url it should redirect to in the window.location.href.

<script>
    $(document).ready(function () {
        $("button").click(function (e) {
            e.preventDefault();
            query = $("#query").val();
            window.location.href = location.origin + "/results/" + query;
        });
    });
</script>

Don't forget to add dependency

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59