2016-10-10 75 views
0

我想用Flask實現搜索欄,但是當我輸入url/search時,出現了405錯誤,方法不允許Flask應用搜索欄

這是我的代碼片段。任何幫助,將不勝感激!

forms.py

from wtforms import StringField 
from wtforms.validators import DataRequired 

class SearchForm(Form): 
    search = StringField('search', [DataRequired()]) 
    submit = SubmitField('Search', 
         render_kw={'class': 'btn btn-success btn-block'}) 

views.py

from flask_login import login_required 
from forms import SearchForm 
from models import User 

@app.route('/') 
def index(): 
    if current_user.is_authenticated: 
    return redirect(url_for('profile')) 
    return render_template('index.html') 

@app.route('/profile', methods=['GET', 'POST']) 
@login_required 
def profile(): 
    # some code to display user profile page 

@app.route('/search', methods=['POST']) 
@login_required 
def search(): 
    form = SearchForm() 
    if not form.validate_on_submit(): 
    return redirect(url_for('index')) 
    return redirect((url_for('search_results', query=form.search.data))) 

@app.route('/search_results/<query>') 
@login_required 
def search_results(query): 
    results = User.query.whoosh_search(query).all() 
    return render_template('search_results.html', query=query, results=results) 

models.py

from flask_sqlalchemy import SQLAlchemy 
from flask_whooshalchemy import whoosh_index 
from app import app 

db = SQLAlchemy() 

class User(db.model): 
    __searchable__ = ['name'] 
    id = db.Column(db.Integer, primary_key=True) 
    name = db.Column(db.String(64)) 

whoosh_index(app, User) 

search.html

{% extends 'layouts/base.html' %} 
{% set page_title = 'Search' %} 
{% block body %} 
    <div> 
     {{ render_form(url_for('search'), form) }} # note: render_form is some marco from another .html file 
    </div> 
{% endblock %} 

回答

2

由於當手動您使用GET方法加載網頁,但僅POST被允許用於search控制器。您需要更改

@app.route('/search', methods=['POST']) 

@app.route('/search', methods=['GET', 'POST']) 

UPDATE

所以基本上這是更好地改變你的search控制器。因爲它沒有使用search.html而且工作不正確。

@app.route('/search', methods=['GET', 'POST']) 
@login_required 
def search(): 
    form = SearchForm() 
    if request.method == 'POST' and form.validate_on_submit(): 
     return redirect((url_for('search_results', query=form.search.data))) # or what you want 
    return render_template('search.html', form=form) 

也使縮進4個空格,因爲它在PEP-8

+0

感謝說,但是當我加''GET'',我現在得到302錯誤。在views.py中看到index()可能會有所幫助,因此我只是添加了它 – PSNR

+0

302不是錯誤。這是您在「搜索」中發送的重定向。 – dirn

+0

是的,但我得到** ERR_TOO_MANY_REDIRECTS **和搜索欄不會顯示在搜索頁面 – PSNR