I'm trying to create a delete button in my template:
<button type="submit" class="btn btn-danger" value={{ instance.name }}> Delete </button>
And I want this button to submit that data in my views.py :
instance_client = compute_v1.InstancesClient()
if request.method == "POST":
instance = request.POST['data']
instance_client.delete(project='xxx', zone='xxx', instance=HERE_I_WANT_THE_DATA)
It's a script that will delete an instance from gcloud.
But I don't know exactly how to deliver the data from the template to views.py.
I'm using Bootstrap 5.
Hope I understand your question.
Template
<form action="{% url 'delete_function' item.id %}" method="POST">
{% csrf_token %}
Cancel
<input class="btn btn-sm btn-danger" type="submit" value="Delete">
</form>
Views
def deleteFunction(request, pk):
item = Model.objects.get(id=pk)
if request.method == "POST":
item.delete()
return redirect('/')
url
path('delete_function/<str:pk>', views.deleteFunction, name='delete_function')
Related
I have two simple HTML forms on one page. I want to create Django view to submit multiple Django forms. I can submit form1 but I have no clue how to submit form2.
There is lot of material on internet but they are all about Djanog forms. Please help me with HTML form submission.
HTML Form
<form action="" method=post name="form1" id="form1">
<input type="text" id="input_form1" name="input_form1">
<button type="submit">Submit</button>
</form>
<form action="" method=post name="form2" id="form2">
<input type="text" id="form2" name="form2">
<button type="submit">Submit</button>
</form>
Views.py
def index(request):
if request.method == 'POST':
input_form1 = request.POST.get('input_form1')
return render(request, 'index.html', params)
Please elaborate how to integrate form2 in Views.py
you can put hidden input inside of each form to identify them
index.html
<form action="" method="post">
{% csrf_token %}
<input type="text" id="input_form1" name="input_form1">
<button type="submit">Submit</button>
<input type="hidden" name="which_form_is_it" value="this_is_form_1">
</form>
<form action="" method="post">
{% csrf_token %}
<input type="text" id="input_form2" name="form2">
<button type="submit">Submit</button>
<input type="hidden" name="which_form_is_it" value="this_is_form_2">
</form>
views.py
def index(request):
if request.method == 'POST':
#watch output in console
print(request.POST)
which_form_is_submiting = request.POST["which_form_is_it"]
if str(which_form_is_submiting) == "this_is_form_1":
#here is yor logic for data from form 1
form_1_input = request.POST["input_form1"]
if str(which_form_is_submiting) == "this_is_form_2":
#here is your logic for data from form 2
form_2_input = request.POST["input_form2"]
return render(request, 'index.html', params)
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.
I have two pages both containing form. However both the pages are sending post request to the same page. How do I differentiate which page has sent the request.
dummy.html(first page)
<form action="/nda" method='POST'>
{% csrf_token %}
<button type="submit" name="submit" id="submit" value="I Agree" target="_blank">I Agree</button>
<button onclick="window.open('/greeting')" target="_blank"> I Disagree </button></br>
</form>
This page redirects to nda page.
nda.html(second page)
This page also redirects to the same page.
<form action="/nda" method='POST'>
{% csrf_token %}
<button type="submit" name="submit" id="submit" value="I Agree" target="_self">I Agree</button>
<button onclick="window.open('/greeting')" target="_self"> I Disagree </button></br>
</form>
My question is, how do I differentiate in my view that from which page it was coming from the page dummy or the same page that was nda.
views.py
def nda(request):
if request.method=='POST' :
# if this is from dummy I want to do this
return render(request,'mainapp/nda.html',{'user':email.split('#')[0]})
if request.method=='POST' :
# if this is from same page that is nda I want to do this
return render(request,'mainapp/home.html')
I am unable to figure out, how do I handle both cases differently
If I understand your question properly,you can use the name attribute in your submit button
<button type="submit" name="submit1" id="submit" value="I Agree" target="_blank">I Agree</button
<button type="submit" name="submit2" id="submit" value="I Agree" target="_blank">I Agree</button
And in the views
def nda(request):
if request.method=='POST' and 'submit1' in request.POST :
# do something
return render(request,'mainapp/nda.html',{'user':email.split('#')[0]})
elif request.method=='POST' and 'submit2' in request.POST:
#do something else
...
How it works ?
You click on the submit button and the server is accessing ..
A button with type submit follows the "action" path specified in the form tag
That is, so that you have a request for different pages, you need to create an additional url, views and html
Example:
one_html.html
<form action="{% url your_app:name1 %}" method='POST'>
{% csrf_token %}
<button type="submit" name="submit" id="submit" value="I Agree" target="_blank">I Agree</button>
<button onclick="window.open('/greeting')" target="_blank"> I Disagree </button></br>
</form>
urls.py:
...
url(r'^' + app_name + 'some_path', views_one, name='name1'),
views.py:
def views_one(request):
if request.method=='POST':
# do something
Exapmle:
two_html.html
<form action="{% url your_app:name2 %}" method='POST'>
{% csrf_token %}
<button type="submit" name="submit" id="submit" value="I Agree" target="_blank">I Agree</button>
<button onclick="window.open('/greeting')" target="_blank"> I Disagree </button></br>
</form>
urls.py:
...
url(r'^' + app_name + 'some_path', views_two, name='name2'),
views.py:
def views_two(request):
if request.method=='POST':
# do something
The difference is that the action points to a different url and thus will be called different views
Sorry for asking similar questions, but other similar questions/answers do not help me with Django 2.
Question:
I have two actions, one is to show some data as a table.
In the second form, I edit this data and will save it as a table using Django in the database. Here is some code:
simple_upload.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile" value="formOne">
<button class="btn btn-primary" type="submit">Upload</button>
</form>
second form:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="mytable" value="formTwo">
<table class="table" border="1" id="tbl_posts">
<thead>
<tr>
...
</tbody>
</table>
<input type="submit" value="Submit">
</form>
views.py
def simple_upload(request):
if request.method == 'POST':
...
if request.is_ajax():
return render(request,
'project/simple_upload.html',
{'section': 'project', 'lines': zipped})
return render(request,
'project/list.html',
{'section': 'project', 'lines': zipped})
return render(request, 'project/simple_upload.html')
urls.py:
urlpatterns = [
...
path('', views.simple_upload, name='list'),
...
]
list.html:
...
{% include "project/simple_upload.html" %}
...
In this case, only the first form works, the second one fails.
Question 1: Can I do if request.method == 'POST' and formOne in request.POST:", I try but it does not react at all.
Question2: How can I write two methods and assign them using urls.py?
To show the data in a table, you can try Tables2 in Django, this might make things easier for you
Also in your case, you might need to make different views for different forms, Since both of them make a POST request, it will be difficult to differentiate.
You can easily do that by specifying action attribute in form tag.
Form 1
<form id="form1" method="post" action="view/for/form/1" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile" value="formOne">
<button class="btn btn-primary" type="submit">Upload</button>
</form>
Form 2
<form method="post" action = "view/for/form/2" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="mytable" value="formTwo">
<table class="table" border="1" id="tbl_posts">
<thead>
<tr>
...
</tbody>
</table>
<input type="submit" value="Submit">
</form>
Later you can redirect using json responses to avoid refreshing the page
in your urls.py add
url('view/for/form/2', save_form, name='save'),
in your views.py
def save_form(request):
#your save logic using request.post
return redirect('your/current/url')
I have an input field that should save the content to a database:
{% for comment in comments %}
<div class="row">
{{ comment.content }}
</div>
{% endfor %}
<div class="row">
<form action="." method="POST">
<textarea class="form-control" name="contents" placeholder="Enter a comment"></textarea>
<input type="submit" class="btn btn-warning" value="save">
</form>
</div>
in flask_app I check whether it is a POST or GET method. If it is POST it should reload the page with a redirect. However, it always returns me to "home".
#app.route('/photography', methods=["GET", "POST"])
def show_photography():
if request.method == "GET":
return render_template('photography.html', comments=Comment.query.all())
elif request.method == "POST":
comment = Comment(content=request.form["contents"])
db.sesson.add(comment)
db.session.commmit()
return 'welcome to flask!'
else:
flash('error message via flash')
return 'welcome to flaks' was just a test, it still redirects me to home after clicking the button. Can anyone help me?
It looks like your 'action="."' is the problem. Set it to url_for('show_photography') in the template.