I'm new with Python and Flask, I have a problem while rendering my page. The function is executed every time I refresh the page but I want the function executed when I click on the SUBMIT button.
Here is my main.py:
#app.route('/gp_bagging_one_app', methods=['POST','GET'])
def gp_bagging_one_app():
if request.method == 'POST':
apk_to_bag = request.form['input']
if (os.path.isfile("./Downloads/" + apk_to_bag)):
print("HELLO")
gp_bag.create_json_for_apk(apk_to_bag[:-4])
else:
print("Apk not found in ./Downloads")
return render_template("GooglePlayStore/gp_bagging_one_app.html")
Here is my view :
{% extends 'layout.html' %}
{% block body %}
<h4> Bagging one app. </h4>
<form method="POST">
<div class="form-group">
<h6>Select an APK to bag:</h6> <input type="file" name="input"><br><br>
</div>
<div class=" form-group">
<button type="submit" class="btn btn-light text-primary" >Bag the APK</button>
</div>
</form>
{% endblock %}
I think it's because of my POST method and way to handle the clickevent but I don't know how to fix it. Thank you
Related
I want to be able to CRUD data from my django-db through the view.py.
{% extends 'home/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<form method="POST" action ="{% url 'twitter' %}" enctype="multipart/form-data">
{% csrf_token %}
<fieldset="form-group">
<legend class="border-bottom mb-4">Twitter Information</legend>
{{ tw|crispy }}
</fieldset>
<div class="form-group">
</form>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Submit</button>
<button class="btn btn-info" type="submit">Update</button>
<button class="btn btn-dark" type="reset">Reset</button>
Delete
</form>
{% endblock content %}
twitter_container.twitter-edit is a view in my view.py. I'm trying to call this function on button clicked.
In order to call a function in views.py with HTML button, you need to use AJAX in javascript.
Check this out for more info.
City is a (dropdown in a main form ) with a +(Add) button.
This +(Add) button opens another form in separate window.
On saving a new city in the second form, I want the new city name to be added in the City dropdown without refreshing the main form.
Here is my code.
<form method="POST" enctype="multipart/form-data" id="form">
{% csrf_token %}
<td>City: {{ form.city }}
<button class="btn btn-primary" onclick="addCity(event)">+</button>
</td>
<button type="submit" class="btn btn-primary">Save</button>
</form>
<script>
function addCity(e){
e.preventDefault();
window.open("/city/", "", "width=500,height=500");
}
</script>
city.html
<form method="POST" class="post-form" action="/city/" id="form">
{% csrf_token %}
<div class="container">
<div class="form-group row">
<label class="col-sm-2 col-form-label">City:</label>
<div class="col-sm-4">
{{ form.name }}
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
urls.py
urlpatterns = [
path('city/', views.add_city, name='city_master'),
]
views.py
def add_city(request):
cities = City.objects.all()
if request.method == "POST":
form = CityForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/city/')
except:
pass
else:
form = CityForm()
return render(request,'city.html',{'form':form})
I can not comment that is why i am writing here, Sir you need ajax call. Do not use POST request, for all post request the page reloads it self. so try using ajax, you can create a route and function inside controller.
HTML form on Django.
I want to perform or create web page in which the button performs the action, and in backend I am handling the Django function.
The code of HTML file is:
<form name="bookappointment" class="form" method="POST">
{% csrf_token %}
<br>
<input type="hidden", name="selecteddoctornumber" value="{{i.doctornumber}}">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-4">
<button class="btn approve" name="approvebtn">Approved</button>
</div>
<div class="col-md-1"></div>
<div class="col-md-4">
<button class="btn notapprove" name="notapprovebtn">Not Approved</button>
</div>
<br>
</div>
<a class="btn cancel" href="requests">Cancel</a>
<br>
</form>
and the other side the Django function is:
if request.method == 'POST':
if request.POST.get('approvebtn'):
for i in doctor:
if pendingDoctorNumber == i.contactNumber:
i.status = 'Approved'
return redirect('request')
if request.POST.get('notapprovebtn'):
for i in doctor:
if pendingDoctorNumber == i.contactNumber:
i.status = 'Not Approved'
return redirect('request')
but its not working any action just get me back to same page
<form action="{% url 'bookappointment' %}" method="POST">
you have to define bookappointment in your urls.py which redirect to views.py where your function lies with name bookappointment.
I am new to Python Flask. I want to update a list in HTML template and return it to the Python Flask application.
So far, I send the list from flask app to the HTML template and display it.
Flask App:
return render_template('er_draw.html', relationship_data=relationship_data)
HTML template:
{% for data in relationship_data %}
<div class="form-row">
<div class="form-group col-md-2">
<input type="text" placeholder="{{ data['entity1'] }}">
</div>
<div class="form-group col-md-2">
<input type="text" placeholder="{{ data['entity2'] }}">
</div>
<div class="form-group col-md-2">
<input type="text" placeholder="{{ data['relationship'] }}">
</div>
<div class="form-group col-md-2">
<select id="inputState" class="form-control">
{% if data['cardinality'] == 'one_to_one' %}
<option selected>One to One</option>
{% else %}
<option>One to One</option>
{% endif %}
{% if data['cardinality'] == 'one_to_many' %}
<option selected>One to Many</option>
{% else %}
<option>One to Many</option>
{% endif %}
{% if data['cardinality'] == 'many_to_many' %}
<option selected>Many to Many</option>
{% else %}
<option>Many to Many</option>
{% endif %}
</select>
</div>
<div class="col-auto">
<a href="#">
<button type="submit" class="btn btn-primary mb-2" name="submit_button" id="update_list"
value="update_list">Update
</button>
</a>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary mb-2" name="submit_button" value="delete_item">Delete
</button>
</div>
</div>
{% endfor %}
When I click the update button I want to update the relationship_data list and return it back to the Flask application. In order to achieve this, I wrote AJAX request code (but I have no clear idea about that).
<script>
let relationship_data;
$.ajax({
url: "/list_change",
type: "POST",
contentType: "application/json;charset=UTF-8",
dataType: "json",
data: JSON.stringify({html_data: relationship_data}),
success: function(response) {
console.log(response);
},
});
</script>
I create a new endpoint in Flask application.
#app.route('/list_change', methods=['POST'])
def list_change():
if request.method == 'POST':
if request.form['submit_btn'] == 'update_list':
data = request.get_json()
print(data['html_data'])
However, I do not how can I access relationship_data list in Javascript is there any method to do that?
Context: Flask uses Jinja in order to generate your page from your HTML template which is represented by your code. In consequence, your screenshot of the application is the already rendered page having filled the {% variable} from the data provided by Flask. From the rendered point onward the page behaves like an usual "webpage".
Answer to question: You have different options to achieve your desired goal. For instance, you can implement a corresponding javascript function for your button press. This function generates an Ajax request which is sent to a new "endpoint" of your Flask application (you need to specify the endpoint yourself). This endpoint processes the information (update the relationship_data for your purpose) and sends it back. The javascript function then processes the received information and updates your page with the new content. In short, you have a mix of javascript implementations alongside setup requirements for your Flask
I have a list of multiple objects from my database (named "plp's"), arranged in a table. Next to each "plp" element I have a button "Edit" to modify that particular entry.
Next, I redirect the user to a new url, where I pass the id of that "plp", and show the form to edit it, with a "save" button.
After pressing the "save", which is request.POST, I want to redirect the user back to the first url, with the list of all the "plp" objects in one list. That means to the site, where he first pressed "Edit".
Can I somehow save the url of where the "Edit" was clicked, and pass it to my views.py?
Thank you
listdns.html:
<td>
Uredi
</td>
urls.py:
rl(r'^(?P<plp_id>\d+)/uredi$', plp_list_uredi,name="plpuredi")
views.py:
def plp_list_uredi(request, plp_id=None):
moj_plp=PLPPostavka.objects.get(id=plp_id)
form=PLPPostavkaForm(request.POST or None,request=request,dns=moj_plp.dns, instance=moj_plp)
context ={
'plp':moj_plp,
'form':form,
}
if request.POST:
if form.is_valid():
plp = form.save()
return redirect(request.path)
return render(request, "plp_pos/uredi.html",context)
uredi.html
<form action="" method="POST">
{% csrf_token %}
<div class="box">
<div class="box-header">
<h4 class="box-title">
Urejanje PLP Postavke
</h4>
</div>
<div class="box-body">
{% for field in form %}
<div class="form-group">
<label for="{{ field.id_for_label }}" class="col-md-2 control-label detail">{{ field.label }}</label>
<div class="col-md-10">
{% if field|field_type == "datefield" %}
{% render_field field class+="form-control dateinput" %}
{% else %}
{% render_field field class+="form-control" %}
{% endif %}
</div>
</div>
{% endfor %}
</div>
<div class="box-footer">
<div class="box-tools pull-right">
<input type="submit" value="Shrani" class="btn btn-primary" />
</div>
</div>
Don't you only have 1 page to edit all the elements? Then you could perhaps hardcode the link e.g.
return HttpResponseRedirect(my_edit_url)
If this doesn't work and you need to go 2 pages back take a look at this post:
How to redirect to previous page in Django after POST request