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?

2
  • 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 wiki article to find out more about query parameters. Commented Nov 7, 2016 at 12:21
  • 2
    Did you have a look at this question already? stackoverflow.com/questions/150505/… The official documentation on how to handle GET-parameters in Django can be found here: docs.djangoproject.com/en/1.10/ref/request-response/… Commented Nov 7, 2016 at 12:22

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

I knew the first method, but didn't find it as good design, second method is what i needed.
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"):

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.