简体   繁体   中英

How can I make a search bar for my website functional?

The following code is the format in which the relevant data is stored inside of a MySQL database:

class Image(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title=db.Column(db.String(120), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
    img_location = db.Column(db.String(600), nullable=False)
    mimetype = db.Column(db.String(10))
    post_name = db.Column(db.String(150), nullable=False, unique=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    manga_name = db.Column(db.String(100), unique=False, nullable=False)

I used a python package to write the code for the database in the form of Python classes.

The following is the route info for the page:

@app.route("/", methods=["GET", "POST"])
def index():
    if current_user.is_authenticated:
        posts = Image.query.all()
        # for post in posts:
        #     print(post.post_name)
        # print(current_user.is_moderator)
        return render_template("index.html", current_user=current_user, posts=posts)
    else:
        posts = Image.query.all()
        return render_template("index.html", posts=posts)

The following is the code for the template:

<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="{{ url_for('static', filename='index.css') }}">

    </head>
    <body>
        <div id="first">
        <input type="text" id="searchBar" name="searchBar">
        {% if current_user.is_authenticated %}
            <a href="{{ url_for('user', username=current_user.username) }}"><img src="{{ url_for('static', filename='profile-icon.png') }}" alt="" id="profileIcon"></a>
            <a href="{{ url_for('logout') }}" id="logout-btn">Logout</a>

        {% else %}
            <a href="{{ url_for('login') }}"><img src="{{ url_for('static', filename='profile-icon.png') }}" alt="" id="profileIcon"></a>
        {% endif %}
        </div>
        <div style="display: flex; justify-content: center; align-items: center;">
            {% with messages = get_flashed_messages() %}
                {% if messages %}
                    {% for message in messages %}
                        <div class="flash-msg"><p style="font-weight: bold; font-family: sans-serif;">{{ message }}</p></div>
                    {% endfor %}
                {% endif %}
            {% endwith %}
        </div>
        <div id="content-1">
            {% for post in posts %}
                {% if loop.changed(post.post_name) %}
                    <div class="content-items">
                        <a href="{{ url_for('read', post_name=post.post_name) }}">
                        <img src="{{ url_for('static', filename='images/'+post.title) }}" alt="" class="content-images">
                        </a>
                    </div>
                {% endif %}
            {% endfor %}

        </div>
    </body>
</html> 

okay, so here is the thing I want to do.

As you can see, there is an input field with the id searchBar in this template. It is currently non-functional.

I want it to render all the posts with different post_name values but the same manga_name values basically, just return a template (for now) that contains all of the posts with the value equal to (be it in upper case or lower case) the manga_name value the user entered in the search bar whenever the user clicks the enter button.

In lay man's terms, I want to create a functional search bar

There are a lot of ways to create search functionality in Flask, but it sounds like you only need something very simple, so something like this could work.

If you don't want the user to be redirected to a new page you could simply have the form send a post request to the same URL which causes the posts displayed to update.

First update your search input to look something like this

<form action = "" method="POST" id="searchForm">
    <input type="text" id="searchBar" name="searchBar">
    <input id="submit" name="submit" type="submit" value="Search">
</form>

then update your route with the functionality to update the posts.

from flask import request

@app.route("/", methods=["GET", "POST"])
def index():

        posts = Image.query.all()

        if request.method == 'POST':
            search = request.form["searchBar"]
            posts = Image.query.filter_by(manga_name = search).all()

        return render_template("index.html", posts=posts)

I haven't had time to test it myself, so this may need a bit of fixing, but the overall idea should help. Let me know if this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM