Context
I'm trying to find out how can I use the button in my page as an action to a function in my app.py with its respective value.
Currently I have this code as my app.py
#app.route('/')
def home():
return render_template('home.html')
# For web app
#app.route('/search', methods=['POST'])
def search():
user_input = [str(i) for i in request.form.values()]
book_rec = search_result(user_input[0],search_define)
return render_template('home.html',data=book_rec)
Which yields something like this if you fill the input form and click Find. I want to make the Recommendation button clickable and will trigger and action in my app.py
Current Code
I generate the cards in the above picture with this html script, this is also my current html script I want to modify the button or form part. And as you can see, data is just a python dictionary.
<center>
<div class="row">
{% for i in data %}
<div class="column">
<div class="card">
<img src="{{data[i]['image_url_s']}}" class="card-img-top" alt="...">
<h2 style="color: #000000;">{{data[i]['book_title']}}</h2>
<p style="color: #000000;">{{data[i]['book_author']}}</p>
<p style="color: #000000;">{{data[i]['year_of_publication']}}</p>
<form action="{{ url_for('rec')}}" method="post">
<button type="submit" class="button btn-primary btn-block btn-large"><strong>Recommendation</strong></button>
</form>
</div>
</div>
{% endfor %}
</center>
Now I'm trying to connect the Recommendation button to this part of lines in my app.py
#app.route('/rec')
def rec():
#Use the {{data[i]['isbn_index']}} value from respective `Recommendation` button as an input
#Do something
#return something
Question
How should I setup my form or button in the HTML script so I can trigger /rec when I click on the Recommendation and use the respective isbn_index value as input?
Inside the jinja for loop, you can use your index of loop or the value of 'i' to create a distinctive name for your button element. For example,
<button type="submit" class="button btn-primary btn-block btn-large" name="button_{{i}}"><strong>Recommendation</strong></button>
and then in your route, you can create conditional statements to look for each button, if it was pressed; do something different.
if request.method == "POST":
for i in data:
button_name = f'button_{i}'
if button_name in request.form:
# do something interesting
print(f'I pressed this button: {button_name}')
Related
I have a template that contains a button.
I have a view for this template in a view file.
How can a part of the code be activated when this button is clicked - which is in the template?
How can you make this as easy as possible?
How can code be activated on click of a button in a Django view?
def click_button_summ(request):
context = {}
if request.POST.get("button_table_summ") == "button_table_summ":
///code///
return render(request, "click_button_summ.html", context)
<div class="ui container">
<div class="column">
<button type="submit" class="ui button" name="button_table_summ" value="button_table_summ">Button</button>
</div>
</div>`
In template:
<button id="choose-your-id-here" type="submit" class="ui button" name="button_table_summ" value="1">Button</button>
where value can be whatever you like, but ensure that all buttons have a unique value (so numbers are easiest -- and you don't actually use the value anyway) and are not the same as the name. With the solution above you can have multiple buttons on the same page:
<button id="choose-your-id-here" type="submit" class="ui button" name="button_table_foo" value="1">Button</button>
<button id="choose-your-id-here" type="submit" class="ui button" name="button_table_bar" value="2">Button</button>
and, in your one view (that handles everything), have code specific to each one with:
if request.POST.get("button_table_foo"):
# code here specific to this button being pressed as form submission
if request.POST.get("button_table_bar"):
# code here specific to this button being pressed as form submission
and/or you can put a formaction in your template to be handled by different views (as long as you have that view in your urls.py of course):
<button id="choose-your-unique-id" type="submit" class="ui button" name="button_table_summ" value="1" formaction="{% url 'valid url-in-urls.py-here' %}>Button</button>
I have two pages index.html having code as following
<form action="/" method="POST">
<div class="form-group">
<textarea class="form-control" name="text" placeholder="Enter Text" rows="6"></textarea>
</div>
<input type="submit" class="btn btn-primary">
</form>
<button>
</div>
<div class="col-md-3 col-sm-1"></div>
<input type=button onClick="location.href='upload.html'"
value='click here'>
</div>
<button>
It has js and css in head. As you can see there is a button to go to upload.html page, which contains code to upload file as following
<body>
<h1>File Upload</h1>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="file" accept=".pdf"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
If I open index.html page in a browser and click on click here button it redirects me to the intended page, But when I run Flask app and try to click on this button it gives 404 error. Right now I haven't created any Flask method for this file. I have tried to add absolute path to upload.html file and ./upload.html and almost every method to create a button mentioned here. I also tried to redirect it to a blank page and index.html itself but every time the error is same. It is only giving me error with local HTML files if I give an address of some website it redirects me to it. Can someone help me with what I need to do to make it work?
I think you need to create a route and point the input element to the new page. Right now that won't work within Flask because the app does not "see" the upload.html page.
so you would first create a route in your routes.py or app.py
#app.route(methods=["GET", "POST"])
def file_upload():
return render_template("upload.html")
and then in your index.html you would point the input to this route:
<input type=button href="{{url_for('file_upload')}}" value='click here'>
just remember, url_for as a function points to the function name, not the html template itself. So here you call url_for which in turn calls file_upload which in turn renders upload.html.
I need to get data from a bootstrap modal input. I'am using the following code :
#app.route('/rejets_modeles', methods=("POST","GET"))
def rejets_modeles():
{code}
if request.method == 'POST':
uname = request.form['uname']
print("----")
print(uname)
return render_template ('rejets_modeles.html', tables=[df.to_html(table_id = 'rejets_modeles')], titles=df.columns.values, header="true")
And here is my HTML code
<form action="POST">
<div class="modal-body-modifs">
<p>Gestion du rejet : </p>
<label><b>NOM</b></label>
<input type="text" name="uname"></br>
<label><b>PRENOM</b></label>
<input type="text" name="uprenom"></br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-default" data-dismiss="modal"> OK</button>
</div>
</form>
I don't even have the ("---") printed, that means that my 'POST' request isnt' interpreted. How can I fix that ? Thank you
It has to be method instead of action
<form method="POST">
In action you can set url to which it has to send form data - ie.
<form method="POST" action="/rejets_modeles">
but if you want to send to the same url then you don't have to set it.
Solved. The problem was data-dismiss="modal" in my input tag. If you delete this the modal will close and the form will be sent via POST request.
I have a table, where I add in the last column of every row the buttons “delete” and “edit”. I do this with the url + parameters in the href in the template (see below). I wrote a function for every href + parameter and the scripts work.
<form method="post">
{% csrf_token %}
<input type="hidden" name="projekt_id" value="{{objekt.id}}" />
<a class="btn btn-outline-secondary btn-sm" href="{% url 'check:remove_project' objekt.id %}" role="button">delete</a>
<a class="btn btn-outline-secondary btn-sm" href="{% url 'check:edit_project' objekt.id %}" role="button">edit</a>
</form>
Since i need such tables very often I want to handle the entire functionality (view the data/edit/delete/create) in one single view (I already have this in one template). My idea/wish is to pass the name= and value= from inside the buttons to the view. There I can distinguish for the appropriate functions - by if-statements- between edit/delete/view/create…
How can the parameters be passed from the BUTTONS in template to the view? Where is the documentation?
I wonder if there is a more elegant way to solve this? (maybe a combination of class based views?)
You can access a button like any other field in the POST data.
<button type="submit" name="delete">Delete</button>
<button type="submit" name="edit"> /Edit</button>
if "edit" in request POST:
...
elif "delete" in request.POST:
...
I am trying to pass what ever the user inputs into the url as keyword arguments (even if its not a real entry). When I try to assign the input name as the keyword arguments it fails.
HTML:
<p class="search">
<form method="GET" action="{% url 'job' %}" class="sidebar-form">
<div class="ogsearchbar input-group">
<input class="searchbarz" type="text" name="user_input" id="user_input" placeholder="Enter Job Number" autocomplete="off" />
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
</p>
Django:
def get_job(request):
if request.method == 'GET':
formvar = request.GET['user_input']
return HttpResponseRedirect('/jobs/' + formvar)
What you want doesn't make sense. The {{ }} signs denote a context variable which is passed into the template from the server, before the template is rendered. But you're trying to use a value which is only defined when the user actually types something into the rendered page itself.
You could probably do this with some Javascript, but there doesn't seem to be much point. Drop the parameter from the URL and let the form send it in the query params, which you can access in your view as request.GET.
I decided to just go with javascript since my django code was not working with a request method when refreshing the page.