I have a 4 buttons on first page which put me through to another page(All those 'buttons' are connected to database in mysql) and on this second page I have some data from mysql tables which I wanna display depending on what I have chosen in the first page. Right now I just display everything I have and I don't really know how to change that. I was looking for solutions but none worked.
views.py
def kategorie_list(request):
obj = Kategorie.objects.all()
context ={'obj': obj}
return render(request, "kategorie/lista.html", context)
def uslugodawcy_list(request):
obj = Uslugodawcy.objects.all()
context ={'obj': obj}
return render(request, "uslugodawcy/uslugodawcy_lista.html", context)
first html page
{% for Kategorie in obj %}
<p> <a class="btn btn-primary" href="/uslugodawcy"><button type="nw" style="height: 65px; width: 170px"> <font size="4">{{Kategorie.idkategorie}} . {{Kategorie.nazwakategorii}}</font> </button> </a> </p>
{% endfor %}
second
{% for Uslugodawcy in obj %}
<p> <a class="btn btn-primary" href="/promocje"><button type="nw" style="height: 65px; width: 170px"> <font size="4">{{Uslugodawcy.iduslugodawcy}} . {{Uslugodawcy.nazwa_uslugodawcy}} </font> </button> </a> </p>
{% endfor %}
There are many approaches. In outline:
Style a link as a button. . If the href is http://djangoserver/url?foo=bar then request.GET['foo'] will be available and equal to "bar".
Make all the buttons relate to a form that you are displaying and POSTing, so all of them do a SUBMIT but have diffferent values that you can find in request.POST. <button form="form-id" type="submit" ...>
Use Javascript to cause clicking the button to fill in fields on the form (which may be hidden fields, so the user has no other way of changing them.
Related
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}')
I have files which are saved to the MEDIA_ROOT - and I am displaying the file paths as URLs in a table in my UI. I would like for these files to download when the user clicks the link in the table. However, when that happens I get an error because I don't have a URL or View defined to handle this I suppose. Problem is, I'm not really sure where to start - any suggestions. Below is my model, and the .html which displays the table and the link.
models.py
class Orders(models.Model):
...
order_file = models.FileField(upload_to='web_unit', null=True, blank=True)
...
def __str__(self):
return self.reference
index.html
<div class="table-responsive">
<table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%">
<thead>
<tr>
....
</thead>
<tbody>
{% for orders in orders %}
<tr>
<td>
<!-- Update book buttons -->
<button type="button" class="update-book btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'order_update' orders.pk %}">
<span class="fa fa-pencil"></span>
</button>
</td>
....
<td>Download</td> #this is the link
</tr>
{% endfor %}
</tbody>
</table>
When the link in the table is clicked - I'd like for the file to be downloaded - I need help on how to define the URL and the View to make this happen.
This has been marked as a duplicate a few times now - but I don't believe it is. The link that I have been referred to only shows a view. I don't understand how I am to trigger that view using a url since there will be many download links in the same screen. How does the view know which file link I have clicked on? Wouldn't that need to leverage the URL somehow?
First, don't do {% for orders in orders %}; instead do {% for order in orders %}
Then this should work (assuming order_file is the field name you didn't show in the model)
<td>Download</td>
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 using python and flask to make a web app. I am new to it, but have gotten most of what I am trying to accomplish done. Where I am stuck, is that I have a label whose value is a python variable( {{id}} ) This id is the id of a row I need to update in a sqlite database. My code is below. when I click the approve button, it takes me to a route which does the update query, but I have no way to pass the {{id}} with it. This would have been much easier if I could have just used javascript for the update query, but everything I've found using javascript, is for web sql, not sqlite, even though some of them say they are for sqlite.
</script>
<table border='1' align="center">
{% for post in posts %}
<tr>
<td>
<label>{{post.id}}</label>
<h1 id ='grill1'>{{post.photoName}}</h1>
<span>
<img id = 'photo1' src='{{post.photo}}' alt="Smiley face" height="200" width="200">
</span><br>
<h5 id ='blurb1'>
{{post.blurb}}
</h5>
<br>
<div style=" padding:10px; text-align:center;">
<input type="button" value="Approve" name="approve" onclick="window.location='/approve;">
<input type="button" value="Deny" onclick="window.location='/deny';"><br>
</div>
</td>
</tr>
{% endfor %}
</table>
Why not just do:
...
<input type="button" value="Approve" name="approve" onclick="window.location='/approve/{{post.id}};">
<input type="button" value="Deny" onclick="window.location='/deny/{{post.id}}';">
...
Then your flask route for approve and / or deny can just take a parameter for the post to approve or deny. i.e.:
#app.route("/approve/<int:post_id>")
def approve(post_id):
"""approve this post!"""
I am new to Python, GAE and the datastore model. So there are lots of things which I do not know yet, so please be patient :)
I am working on a web service that allows people to post 'name' and 'desc' (description) of an item and it will be included in a table on the same page. However when I clicked the submit button I got the error: 404 Not Found, The resource could not be found.
I am expecting a lot of things to be wrong in my code shown below (I only include short snippets of my code which I think is relevant to make it easier for reading), and my biggest problem is I have no idea which parts are wrong or which specific questions to ask. But I hope I can use this chance to learn more about everything that's involved in my code (Jinja, HTML, GQL etc), and how I can fit them all together.
class Events(ndb.Model):
name = ndb.StringProperty()
desc = ndb.StringProperty()
class Promote(webapp2.RequestHandler):
def get(self):
query = ndb.gql("SELECT * "
"FROM Events "
)
template_values = {"events" : query,}
template = jinja_environment.get_template('promote.htm')
self.response.out.write(template.render(template_values))
def post(self):
event = Events(name = self.request.get('name'), desc = self.request.get('desc'))
event.put()
self.redirect('/promote')
app = webapp2.WSGIApplication([('/', Main),
('/publicsearch', PublicSearch),
('/promote', Promote)],
debug=True)
This is my html code for that page.
<div class="jumbotron">
<div class = "container">
<form action="/promote" method="post">
<fieldset>
<div class="row-fluid">
<p> Promote your event here! </p>
<div class="row-fluid">
<div class="span6">
<p> Name of event: <br>
<textarea class="input-block-level" name="name" rows="1" cols = "50"> </textarea></p>
<p> Event description: <br>
<textarea class="input-block-level" name="desc" rows="3" cols = "50"> </textarea></p>
<p><input type="submit" value="Submit">
</div>
</div>
</div>
</div>
</div>
<h4> Events feed </h4>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th width="30%">Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for event in events %}
<tr>
<td>{{ event.name }} </td>
<td>{{ event.desc }} </td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
Your form is trying to post to a handler with a url of /wishlist however the only handler for POST methods you have registered is for /promote.
These things need to match up. Either change the form or the handler mapping.
Also while you are at it check that your app.yaml makes sense. Have a look in the logs whilst you are at it, you will see what URL is being requested.