单击链接传递数据

2024-09-28 01:29:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个食谱数据库。我的问题是显示搜索结果。我可以按配料搜索数据库,并获得含有该配料的食谱列表。我在新页面上显示这些结果;我只显示配方的标题,并将其链接到“showrecipe”页面。但是我找不到方法将配方id发送到新页面,以便它知道要显示哪个配方。以下是迄今为止相关的代码位:

搜寻表格:

class SearchIngredientsForm(FlaskForm):
    ingredients_string = StringField('ingredients_string', validators=[InputRequired(), Length(min=1)])
    # search_string = StringField('Search string', [InputRequired()])
    submit = SubmitField('Search')

搜索路线:

@app.route('/search', methods=['GET','POST'])
def search():
    form = SearchIngredientsForm()
    if form.validate_on_submit():

        search_ingredients_string = form.ingredients_string
        search_ingredients_list = search_ingredients_string.data.split(',')
        recipe_ids = []
        ingredient_objects = []

        if search_ingredients_list:
            for ingredient_name in search_ingredients_list:
                ingredient_objects.extend( Ingredient.query.filter(Ingredient.line.like(f'%{ingredient_name}%')).all() )
                if ingredient_objects:
                    for ingredient in ingredient_objects:
                        recipe_ids.append(ingredient.recipe_id)
        session['recipe_ids'] = recipe_ids
        return redirect(url_for('results'))
    return render_template('search.html', form=form)

以及results.html

{% extends 'layout.html' %}
{% block content %}
    <h1>Results</h1>
    {% for result in recipe_objects %}
        <a href= "{{ url_for('showrecipe'), id=result.id }}">{{ result.title }} which serves: {{ result.serves }}</a>      
    {% endfor %}
{% endblock content %}

最后是showrecipe路线。我似乎无法通过身份证

@app.route('/showrecipe/<id>', methods=['POST', 'GET'])
def showrecipe(id):
    recipe = Recipe.query.get(id)
    return render_template('showrecipe.html', recipe=recipe)

当我点击结果页面上的配方标题时,我得到一个“未找到url”错误

提前感谢您的帮助

更新

以下是结果路线:

@app.route('/results')
def results():
    recipe_ids = session.get('recipe_ids')
    recipe_objects = []
    if recipe_ids:
        for recipe_id in recipe_ids:
            recipe_objects.append(Recipe.query.get(recipe_id)) 
    return render_template('results.html', recipe_objects=recipe_objects)

Tags: formididsforsearchstringifobjects

热门问题