ShellRox ShellRox - 1 month ago 12
Python Question

Django: Make query using url ( Assigning variable using url )

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?

Answer

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"):