0

I am trying to make a query system for my website, i think the best way and the most compact would be to assign search variable using url pattern.

So for example, i want to search objects of model User:


User sends HttpRequest to following url:

https://127.0.0.1/search/q="admin"

Now HttpRequest is also sent to search view, we somehow get q variable data.

def search(request):
    for query in User.objects.all():
        if q in query: # < We somehow need to get data of 'q'.
           return HttpResponse(q)

Since i have admin in User.objects.all(), this should return HttpResponse of 'admin'.


How can this url pattern be made? So i can assign q variable from the url and then send it to system to find it?

ShellRox
  • 2,532
  • 6
  • 42
  • 90
  • 3
    You can use query parameters, but for this your url should look like the following: `https://127.0.0.1/search/?q=admin` (note the question mark). Then, in your view, you can access all of your query parameters using `request.GET[param]` (in your case `request.GET['q']`). You can read [this](https://en.wikipedia.org/wiki/Query_string) wiki article to find out more about query parameters. – iulian Nov 07 '16 at 12:21
  • 2
    Did you have a look at this question already? http://stackoverflow.com/questions/150505/capturing-url-parameters-in-request-get The official documentation on how to handle GET-parameters in Django can be found here: https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.GET – maennel Nov 07 '16 at 12:22

2 Answers2

1

You can capture named strings from URLs like this:

urls.py:

urlpatterns = [
    url(r'^blog/page(?P<num>[0-9]+)/$', views.page),
]

views.py:

def page(request, num="1"):
Lauri Elias
  • 1,231
  • 1
  • 21
  • 25
1

I have problems with this URL:

https://127.0.0.1/search/q="admin"

There is no ? in the URL, so there is no query string, it's all part of the "path". Using characters like = and " in there will confuse a lot of things, if it works at all.

Either just do

https://127.0.0.1/search/admin

With an URL pattern like r'^search/(?P<querystring>.+)$', or

https://127.0.0.1/search/?q=admin

In this case the query string will be in request.GET['q']; it's also possible to use Django forms to process query parameters (e.g. for validating them).

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79