8

I'm new to programming and Flask and I am stuck on this problem.

I am trying to implement a search function in a web application that will take data from a form and compare it to a value in the database and list results.

This is what I have so far:

views.py

@app.route('/search', methods=['GET', 'POST'])
def search():
    searchForm = searchForm()
    courses = models.Course.query.order_by(models.Course.name).all()
    if searchForm.validate_on_submit():
        for i in courses:
            if searchForm.courseName.data == i.name:
              searchResult = models.Course.filter(Course.name.like('%searchForm.courseName.data%'))
    return render_template('courselist.html', courses = courses, searchResult = searchResult)

form.py

class searchForm(Form):
    courseName = StringField('Search course', validators=[DataRequired(), Length(max=60)])

database models.py

class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(40), unique=True)
    courseCode = db.Column(db.String(10), unique=True)
    duration = db.Column(db.Integer)
    maxStudents = db.Column(db.Integer)
    startDate = db.Column(db.DateTime)
    prerequisites = db.Column(db.String(500))
    trainerID = db.Column(db.Integer, db.ForeignKey('trainer.id'))
    venueID = db.Column(db.Integer, db.ForeignKey('venue.id'))

    sessions = db.relationship('Session', backref='course', lazy='dynamic')
    bookings = db.relationship('Booking', backref='course', lazy='dynamic')

html file

{% extends "index.html" %}
{% block content %}
<h3>Courses:</h3>
<ul>
    {% for course in courses %}
    <li>
    <h4><a href="/viewcourse?id={{course.id}}">{{course.name}}</a>
    <a class="btn btn-success" href="/editcourse?id={{course.id}}">Book</a>
    <a class="btn btn-info" href="/editcourse?id={{course.id}}">Edit</a>
    <a class="btn btn-danger" href="/deletecourse?id={{course.id}}">Delete</a></h4>
    </li>
    {% endfor %}
</ul>
{% endblock %}

I think the general logic is right but I need some help adjusting it.

2
  • can you add at the end all() . like models.Course.filter(Course.name.like('%%s%'%searchForm.courseName.data)).all() Commented Mar 3, 2017 at 13:12
  • students = models.Student.query.all() - They all follow the same structure I don't see how that would help Commented Mar 3, 2017 at 13:16

2 Answers 2

15

Your logic in views.py seems a bit off. You're retrieving all Course objects from the database and looping through them. Then you check if the course name exactly matches the search input - and if so, try to find matching courses. I think it would be better constructed like this:

@app.route('/search', methods=['GET', 'POST'])
def search():
    searchForm = searchForm()
    courses = models.Course.query

    if searchForm.validate_on_submit():
        courses = courses.filter(models.Course.name.like('%' + searchForm.courseName.data + '%'))

    courses = courses.order_by(models.Course.name).all()

    return render_template('courselist.html', courses = courses)
Sign up to request clarification or add additional context in comments.

1 Comment

use ilike instead of like if you want search case insensitive data.
8

This is this is the simplest answer :

@app.route("/search", methods=['GET'])
def search():
    query = request.args.get("query") # here query will be the search inputs name
    allVideos = Videos.query.filter(Videos.title.like("%"+query+"%")).all()
    return render_template("search.html", query=query, allVideos=allVideos)

3 Comments

use ilike instead of like if you want search case insensitive data.
request.args.get() didn't help, but request.form.get(). Maybe this can help someone.
listen request.args.get() is used to get the url paramets line "search?query=flask&page=2", now request.args.get("query") will return "flask" and request.args.get("page") will return 2. request.form.get() is used mainly during the post requests.

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.