1

I was first using Flask bootstrap and it worked

{% import "bootstrap/wtf.html" as wtf %}
<form method="POST" action="{{url_for('edit_ad', id=ad.id)}}" enctype="multipart/form-data">
    {{ form.hidden_tag() }}
    {{ wtf.form_field(form.title) }}
    {{ wtf.form_field(form.body) }}
    {{ wtf.form_field(form.img_url) }}
    {{ wtf.form_field(form.price) }}
    <div>
        <p>
            <button class="" type="submit" value="Edit">Edit</button>
        </p>
    </div>
</form>

But I wanted to change it to Bootstrap Flask and use render_form. I'm having trouble with url_for

{% from 'bootstrap/form.html' import render_form %}
{{ render_form(form, action="{{url_for('edit_ad', id=ad.id)}}", method="POST", button_map={'edit_button': 'primary'}) }}

Here is my view:
@app.route('/edit_ad/<string:id>', methods=['GET', 'POST'])
@login_required
def edit_ad(id):

# more code
    return render_template('edit_ad.html', form=form, ad=ad)

How should I pass id? Thanks

Grey Li
  • 11,664
  • 4
  • 54
  • 64
ble
  • 287
  • 1
  • 5

2 Answers2

0

You can pass the variable like this,

{% from 'bootstrap/form.html' import render_form %}
{{ render_form(form, action="/edit_ad/{{ ad.id }}", method="POST", button_map={'edit_button': 'primary'}) }}
Harris Minhas
  • 702
  • 3
  • 17
  • thanks, I tried that but it redirects to http://127.0.0.1:5000/edit_ad/%7B%ad.id%7D%7D I ended up using wtf forms again and I'm using bootstrap as recommended in accepted comment here [link](https://stackoverflow.com/questions/54257732/how-can-i-use-bootstrap-4-while-using-flask-for-python-3) – ble Jun 24 '21 at 18:15
  • Is ```ad.id``` a legitimate variable passed from flask in the jinja template? Because if it is, then the above mentioned code should work. You can test my syntax with passing an integer like this. ```action="/edit_ad/2``` – Harris Minhas Jun 24 '21 at 18:22
  • yes, if I just send a number it works and if I render it on page with e.g. `

    {{ad.id}}

    ` it renders correct number
    – ble Jun 24 '21 at 18:27
  • If the ```{{ ad.id }}``` variable gets displayed and ```action="/edit_ad/2"``` works, then```action="/edit_ad/{{ ad.id }}``` should also work within the same file. Its basic jinja. You can try to change the url of view to, ```@app.route('/edit_ad/', methods=['GET', 'POST'])``` – Harris Minhas Jun 24 '21 at 18:36
  • 1
    thanks I tried it, but I still get the same thing. It works with /edit_ad/2 because it calls http://127.0.0.1:5000/edit_ad/2, but when I use {{ad.id}} it doesn't see it as value.. I found a workaround.. but thanks anyways – ble Jun 24 '21 at 20:15
0

You can't and don't need to use Jinja delimiters inside other delimiters (i.e. nest the curly brackets {{ {{...}} }}).

Just pass the url_for call to the action keyword directly. No curly brackets, no quotes:

{{ render_form(form, action=url_for('edit_ad', id=ad.id), method="POST", button_map={'edit_button': 'primary'}) }}
Grey Li
  • 11,664
  • 4
  • 54
  • 64