Button type "submit" doesn't let bootstrap modal to open but type="button" doesn't fulfill my need. How to use AJAX to solve this? - django

I have a web page in which there is an input field. And below is an edit button. When I enter some text in the input field and press the edit button, a modal pops up and there is an input field in it also. I want to pass the text from the first input field to the input field in the modal window.
But then a problem arises. The modal window only opens when the edit button has type="button". But this type="button" doesn't submit the text input to the backend when I click the edit button. It submits the text to the backend when I use button type="submit", but then the modal doesn't open because the page reloads.
I don't know how to use AJAX, how can this be done with AJAX?
Here's my HTML code:
<div class="container">
<div class="row manage-groups">
<div class="row g-0 login_form justify-content-center" id="contactForm" novalidate="novalidate">
<form method="POST">
{% csrf_token %}
<div class="col-md-12 form-group">
<input type="text" class="login-inpt" id="name" name="type-groups" placeholder="type in the group name">
</div>
<div class="row g-0 justify-content-center group-action">
<div class="col-sm-4 submit-group">
<div>
<button type="submit" data-bs-toggle="modal" data-bs-target="#ModalAddGroups"
class="button-box">Add</button>
</div>
</div>
<div class="col-sm-4 submit-group">
<button type="button" onclick="form_submit()" data-bs-toggle="modal" data-bs-target="#ModalEditGroups"
class="button-box">Edit</button>
</div>
<div class="col-sm-4 submit-group">
<button type="submit" data-bs-toggle="modal" data-bs-target="#ModalDeleteGroups"
class="button-box">Delete</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- Modal window for Edit button -->
<div class="modal fade" id="ModalEditGroups" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content edit-modal">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Edit Group</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body grid-container">
<input type="text" value="{{ group.group_name }}">
{{ group.group_name }}
{{ group }}
<table class="edit-groupLinks">
<thead>
<tr class="header">
<th>Links</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="www.google.com"></td>
<td><button type="button" class="delete" aria-label="Close">
<span aria-hidden="true">×</span>
</button></td>
</tr>
</tbody>
</table>
<button class="add-linkBTN"><i class="fa fa-plus" aria-hidden="true"></i></button>
</div>
<div class="modal-ftr">
<button type="submit" class="button-box" id="footer-btn">Save</button>
</div>
</div>
</div>
</div>
Views.py file:
def manageGroups(request):
form = GroupSorting()
group = request.POST.get('type-groups', False)
content = Groups.objects.filter(group_name__contains = group)
if request.method == "POST":
form = GroupSorting(request.POST)
if form.is_valid():
form.save()
else:
form = GroupSorting()
context = {'form': form, 'group': content}
return render(request, 'posts/manage-groups.html', context)

Related

How is it possible to get data from one form that has multiple textareas in Django

I'd like to get data from one form that has multiple textareas inside , In my views: 'compare_ingredients' I've tried requesting data from my form id 'compareform' also the textarea id 'ingredients', but when I enter something into one texture and click on submit it comes back as 'None' when I print. Here is my html and views:
html :
<div class="container-fluid">
<h4>Please enter in your ingredients:</h4>
<h6>(Seperate each item by comma)</h6>
<br>
<button class="add_item">Add Item</button>
<br>
<div class="row row-cols-1 row-cols-md-2 mx-auto">
<form action="{% url 'compare_ingredients' %}" method="POST" name="compareform" id="compare">
{% csrf_token %}
<br>
<button type="submit" class="btn btn-info sub_btn">Submit</button>
<button type="submit" class="btn btn-secondary back_button">
Back
</button>
<br>
<br>
<div class="row form_row">
<div class="col mb-4">
<h5>Item 1</h5>
<div class="card form_card">
<div class="card-body compare_cardbody">
<textarea name="ingredients1" id="ingredients" cols="30" rows="10" form="compareform"></textarea>
</div>
</div>
</div>
<div class="col mb-4">
<h5>Item 2</h5>
<div class="card form_card">
<div class="card-body compare_cardbody">
<textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compareform"></textarea>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
views.py:
def compare_ingredients(request):
if request.method == "POST":
ingredients = request.POST.get('compareform')
print(ingredients)
return render(request, 'result/compare.html')
ok, I figured it out , the problem was in the html textarea I had the name of the form as 'compareform' when it should have been 'compare' :
<textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compare"></textarea>
then in my views I did:
ingredients1 = request.POST.get('ingredients1')

Django using modals for deleting a user

I want to delete users with modals in django. I have a deletion function which I don't know how I should return to template.
views.py:
#login_required(login_url='admin_signin')
#admin_only
def admin_profiles_deletion(request, username):
context = {}
account = Account.objects.get(username=username)
account.delete()
messages.success(request, "User deleted!")
context['account'] = account
return render(request, 'HOW SHOULD I REFER MODALS HERE?', context)
And my urls.py looks:
path('admin/profile/<str:username>/delete', views.admin_profiles_deletion, name='admin_profiles_deletion'),
And finally my template is:
<td class="text-center td-actions">
<i class="la la-eye view"></i>
<i class="la la-edit edit"></i>
<a href="{% url 'admin_profiles_deletion' account.username %}" data-toggle="modal" data-target="#deleteaccount">
<i class="la la-close delete"></i>
</a>
<!-- Modal -->
<div class="modal fade" id="deleteaccount" tabindex="-1" role="dialog" aria-labelledby="deleteaccountTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteaccountTitle">Delete confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h5>Do you want to delete?</h5>
</div>
<div class="modal-footer">
<div class="col-6 text-left">
<div class="previous">
<form method="POST">
{% csrf_token %}
<input class="btn btn-danger btn-sm btn-block" type="submit" name="submit" value="Yes">
</form>
</div>
</div>
<div class="col-6 text-left">
<div class="next">
<a class="btn btn-info btn-sm btn-block" href="{% url 'accounts' %}">No</a>
</div>
</div>
</div>
</div>
</div>
</div>
</td>
In modal I want to hit YES and then delete specific account. but I don't know how to do it while I am using modals.
Try this one.
from django.shortcuts import redirect
...
def admin_profiles_deletion(request, username):
...
return redirect("/admin/profile/")
# or to return to same (previous) page:
return redirect(request.META['HTTP_REFERER'])
In your template add action attribute to your form
<form method="POST" action="{% url 'admin_profiles_deletion' account.username %}">
{% csrf_token %}
<input class="btn btn-danger btn-sm btn-block" type="submit" name="submit" value="Yes">
</form>
OR to update action attribute dynamically
<a href="#" data-url="{% url 'admin_profiles_deletion' account.username %}" class="deleteaccount">
<i class="la la-close delete"></i>
</a>
and than with jQuery
<script>
$(document).ready(function() {
$('a.deleteaccount').on( "click", function() {
event.preventDefault();
$('#deleteaccount form').attr('action', $(this).data("url"));
$('#deleteaccount').modal('show');
});
});
</script>
UPDATE - working example http://jsfiddle.net/cbzmewhq/1/
Add <span id="current_username"></span>? to your modal body.
Then with jQuery add your your desired text on click:
$('#deleteaccount #current_username').text($(this).data("username"));
BELOW IS AN EXAMPLE OF YOUR CODE
...<!-- YOUR TABLE -->
<td class="text-center td-actions">
<i class="la la-eye view"></i>
<i class="la la-edit edit"></i>
<a href="#" data-username="{{ account.username }}" data-url="{% url 'admin_profiles_deletion' account.username %}" class="deleteaccount">
<i class="la la-close delete"></i>
</a>
</td>
....<!-- YOUR TABLE -->
<!-- Modal OUT OF TABLE -->
<div class="modal fade" id="deleteaccount" tabindex="-1" role="dialog" aria-labelledby="deleteaccountTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteaccountTitle">Delete confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- ADD SPAN TO ADD USERNAME dynamically -->
<h5>Do you want to delete <span id="current_username"></span>?</h5>
</div>
<div class="modal-footer">
<div class="col-6 text-left">
<div class="previous">
<form method="POST">
{% csrf_token %}
<input class="btn btn-danger btn-sm btn-block" type="submit" name="submit" value="Yes">
</form>
</div>
<div class="col-6 text-left">
<div class="next">
<a class="btn btn-info btn-sm btn-block" href="{% url 'accounts' %}">No</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ADD BELOW CODE TO THE BOTTOM OF BODY -->
<script>
$(document).ready(function() {
$('a.deleteaccount').on( "click", function() {
event.preventDefault();
$('#deleteaccount form').attr('action', $(this).data("url"));
$('#deleteaccount #current_username').text($(this).data("username"));
$('#deleteaccount').modal('show');
});
});
</script>

Flask app - can't passing a value to a confirmation modal before deleting a post

I need your help with my flask blog app.
I made a simple dashboard listing all the posts, admin can edit or delete any of them. Edit option is fine. But, for delete option, I am trying to implement a confirmation step using a modal. My code is below.
{% block body %}
<h1>Dashboard <small> Welcome {{session.username}} </small></h1>
<a class="btn btn-success" href="/add_article">Add Article</a>
<hr>
<table class="table table-striped">
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Date</th>
<th></th>
<th></th>
</tr>
{% for article in articles %}
<tr>
<td>{{article.id}}</td>
<td>{{article.title}}</td>
<td>{{article.author}}</td>
<td>{{article.create_date}}</td>
<td> Edit </td>
<td>
<!-- Button trigger modal -->
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModalCenter">
Delete
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Deleting Post </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this post?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<form action="{{url_for('delete_article', id=article.id)}}" method="post">
<input type="submit" value="Delete" class="btn btn-danger">
</form>
</div>
</div>
</div>
</div>
</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Issue: Form action is generating same url (/delete_article/1) for all posts.
Please help.
Regards Hossain
The problem was for the reuse of modal id. As the modal code in the loop, so modals for all the post were having the same id. That's why view function was getting the same URL.
Solution (three changes in the above code):
data-target="#exampleModalCenter" -- > data-target="#exampleModalCenter{{article.id}}"
id="exampleModalCenter" --> id="exampleModalCenter{{article.id}}"
and
id="exampleModalLongTitle" --> id="exampleModalLongTitle{{article.id}}"
Create an element to select the product to be deleted in layout.html
<div id="dvtextRemoveDiv" style="display: none">
<p class="pintitle"> Select a product name to be deleted from the dropdown: </p>
<table border="0" width="1000">
<tr>
<td>
<p class="pinfield"><select name="KeyValuesRemove" id="KeyValuesRemove" class="form-control" onchange="passKeyToBeDeleted()">
{% for row in KeyValuesRemove %}
<option value="{{row}}">{{row}}</option>
{% endfor %}
</select>
</p>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-danger btn-sm m-1" data-toggle="modal" data-target="#deleteModal">Delete</button>
</td>
</tr>
</table>
</div>
Create a modal in the same page
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Delete Post?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<form action="{{ url_for('delete_post')}}" method="POST">
<input name="pass_value" type="hidden" value="pass_value" id="hidden_input">
<input class="btn btn-danger" type="submit" value="Delete">
</form>
</div>
</div>
</div>
</div>
Javascript function to pass value from html file to views.py (from frontend to backend)
<script>
function passKeyToBeDeleted(){
var valuefromID = document.getElementById('KeyValuesRemove').value;
$('#hidden_input').val(valuefromID);
alert(document.getElementById('hidden_input').value);
$("#deleteModal").modal("show");
}
</script>

Django - Deleting instance according a user's choice in a table

I have the following situation: At the user's area on the website he can see all his real estate posts in a table. There is a "trash button" for each one of the posts. When he press the button I want do delete from DB the exact instance he choose.
This is the HTML that I have. Please note that I used an to use a view to access the DB and then delete from DB. But I don't know how to send the exactly parameters to find it on the DB.
<div class="container">
<div class="col-xs-12">
<h1>Olá, {{ request.user.first_name }}</h1>
</div>
<div class="row col-md-12 col-md-offset-0 custyle">
<table class="table table-striped custab">
<thead>
<tr>
<th>Imagem Principal</th>
<th>Data Criação</th>
<th>Tipo do Anúncio</th>
<th>Tipo do Imóvel</th>
<th>Preço Venda</th>
<th>Visualizações</th>
<th>Expira</th>
<th>Status</th>
<th class="text-center">Action</th>
</tr>
</thead>
{% for anuncio in anuncios %}
<tr >
<td>
<div class="embed-responsive embed-responsive-16by9">
<img class="embed-responsive-item" src="{{anuncio.imagem_principal.url}}">
</div>
</td>
<td>Falta</td>
<td>{{anuncio.tipo_anuncio}}</td>
<td>{{anuncio.tipo_imovel}}</td>
<td>R$ {{anuncio.preco_venda}}</td>
<td>Falta</td>
<td>News Cate</td>
<td>News Cate</td>
<td><p data-placement="top" data-toggle="tooltip" title="Delete">
<button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete">
<span class="glyphicon glyphicon-trash"></span>
</button></p>
</td>
</tr>
{% endfor %}
</table>
</div>
</div>
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
<h4 class="modal-title custom_align" id="Heading">Edit Your Detail</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input class="form-control " type="text" placeholder="Mohsin">
</div>
<div class="form-group">
<input class="form-control " type="text" placeholder="Irshad">
</div>
<div class="form-group">
<textarea rows="2" class="form-control" placeholder="CB 106/107 Street # 11 Wah Cantt Islamabad Pakistan"></textarea>
</div>
</div>
<div class="modal-footer ">
<button type="button" class="btn btn-warning btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Update</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<div class="modal fade" id="delete" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
<h4 class="modal-title custom_align" id="Heading">Delete this entry</h4>
</div>
<div class="modal-body">
<div class="alert alert-danger"><span class="glyphicon glyphicon-warning-sign"></span> Are you sure you want to delete this Record?</div>
</div>
<div class="modal-footer form-actions">
<span class="glyphicon glyphicon-ok-sign"></span> Yes
<button type="submit" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> No</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
I am practing what I learnt in a book, so I don't want to go for AJAX yet.
Make the button inside of a <form> that POSTs to a view, which will then delete the instance. For example:
html
<form action="{% url 'delete_estate %}" method="POST">
{% csrf_token %}
<input type="hidden" name="estate_id" value="{{ estate.id }}">
</form>
view
def delete_estate(request):
if request.method == "POST":
estate_id = request.POST['estate_id']
estate = Estate.objects.get(id=estate_id)
estate.delete()
messages.success(request, "Estate deleted successfully!")
return redirect("/")
urls
...
url(r'^delete-estate/$', views.delete_estate.as_view(), name='delete_estate'),
....
Put the modal inside of the for loop as well so that there is a distinct modal for every estate. Remember to change the id of the modal to something like id="delete_{{ anuncio.id }}" and have the delete button activate that same modal using data-target="delete_{{ anuncio.id }}". From within that modal you should be able to do what Hybrid said with the form and access the {{ anuncio.id }} variable.
If you didn't already know, id is already created by default.

How to create a popup with a form inside a table element in Django

I want to have a "sendemail" button for each element in the table, once the user clicks on this there should be a pop up with a form inside and a button. I tried using jquery for the popup but it is not working, can someone please tell me what I am doing wrong or suggest me any other way of creating this pop up. Currently I am using twitter bootstrap modal but want to replace that with a popup/popover
homepage.html
<table id="search-results" class="table table-hover">
</table>
ajax.js
$(function(){
$('#searchtest').click(function() {
$.ajax({
type: "POST",
url: "/searchtrips/",
data: {
'city' : $('#city').val(),
'location' : $('#location').val(),
'duration' : $('#duration').val(),
'search_text' : $('#searchtest').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data);
}
search-results.html
{% for data in datas %}
<tr>
<td>{{ data.score}}</td>
<td>{{ data.distance}}</td>
<td>{{ data.time}}</td>
{%for element in data.place.elements%}
<td>
{{element.placeName}}
</td>
{% endfor %}
<td>
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Share with your friends</h3>
</div>
<form action="{% url "send_mail"%}" class="form-horizontal" method="post">
<div class="control-group">
<label class="control-label" for="subject">Subject</label>
<div class="controls">
<input type="text" name="subject" value="Your friend has shared a traverse trip" id="subject" placeholder="subject">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" name="email" id="email" placeholder="Email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="message">Message</label>
<div class="controls">
<input type="text" name="message" id ="message" placeholder="message" value ="Here we will have the link ">
</div>
</div>
<div class="modal-footer">
{% csrf_token %}
<input type="submit" value="email" class="btn btn-primary">
</div>
</form></div>
<i class="icon-envelope"></i>SendEmail
<a href="{% url "add_trip" city=data.score score=data.score distance=data.distance|floatformat:"0" time=data.time %}"
class ="btn btn-mini btn btn-warning">Add/delete</a>
</td>
</tr>
{% endfor %}*