You can see , My navigation bar has a search box
This search box can be used to search for articles by title and display the article details page , When we enter an article title that is in the database , After clicking search, you can jump to the article details page . Without this article , Just jump back to the home page , And display in the box find_nothing
The font of ,OK Don't talk much , Open the door !
obviously , This function is not difficult to implement , With the foundation of the previous registration and login , Actually, this function can't be checked very much , The data in the input box is marked with post
To the background , And then go backstage filter Method to go to the object list , Then display on the details page
As for the Input box placeholder Show find_nothing
, This is because redirection is required , Redirection can't be like render In that way, we can pass values by dictionary , There are two ways to do it online :
The method of caching is very convenient , and url clean , Nothing else , But it is a cache data after all , Just like login information , He will keep it for a while , When you don't need to search things for a while , And run to other pages , that find_nothing It will still be displayed on the input box , This is obviously not what we want , What we need is to jump out the word when we can't find it , And has no effect on other pages
therefore , I decided get Method pass value
def sousuo(request):
try:
sou = request.POST.get('sousuo')
if request.method == 'POST':
article = Article.objects.filter(title=sou)
if article.exists():
detail_info = article[0]
else:
return redirect('/?error=find_nothing')
denglu = request.session.get('name', ' tourists ')
return render(request, 'blogmuban/xiangqing.html', {
'detail_info':detail_info,'denglu':denglu})
except Exception as e:
print(e)
Such as code : I use filter Method to retrieve the data whose title contains the contents of the search box , Whether there is this data or not ,filter Methods are stored in article, Then we can judge whether this finger exists , because article It's a list of objects , So there is detail_info = article[0]
If article non-existent , We will redirect to the home page , Then start what I said above get Method pass value :
return redirect('/?error=find_nothing')
So if we enter an error value in the input box , Our route shows this very well :
So how do I get it at the front end find_nothing This word ?
placeholder="{
{ request.GET.error }}"
hold placeholder Just write this for the contents
If you have any better method of redirection and value transfer, please make comments in the comment area