Issue
in models.py
class Person(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField(blank=True, null=True)
in views.py
def index(request):
entry = Person.objects.all()
context = {'entry':entry}
return render(request, 'searching/index.html', context)
def detail(request, pk):
entry = Person.objects.get(id=pk)
context = {'entry':entry}
return render(request, 'searching/detail.html', context)
in urls.py
path('name/', views.index, name='index'),
path('name/<str:pk>/', views.detail, name='detail'),
I am stuck, i want to make a search bar where if you search the exact id, example my model has id of 1 if i search 1 in the box it should return mysite.com/name/1 instead of getting a page with results of queries that contain the 1 i want the exact one i searched for.
I have looked so hard but i can't find a solution, it seems like a simple question and i feel so dumb. Is there an easy solution that i am missing?
Solution
I think what you're looking for is a way to redirect from the index page with a search parameter to the detail page. If you insert a check in your index page like this it should now take an ID submitted through the search field and redirect to the page. This will leave all error handling for missing IDs to your detail
view.
from django.shortcuts import redirect
def index(request):
pk = request.GET.get('q') # /name/?q=1
if pk:
return redirect('detail', pk=pk)
entry = Person.objects.all()
context = {'entry': entry}
return render(request, 'searching/index.html', context)
You will need to update 'q'
to the name of your search field. If your url names are in a namespace you will need to add that to the redirect
call. If your search form submits using <form method="POST">
you'll need to change request.GET
to request.POST
.
Answered By - Jacinator
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.