Jinja code rendered using ajax is enclosed witin doublequorts in django project - django

I am developing a todo app using django as backend and html,css,bootstrap for frontend,
I used Ajax in this project to load data from server without refresh.
**Look at the image **
the {%csrf_token%} is passed through ajax but is is renderd in html page as a text within a double quort.
How to fix this
I want to render the {%csrf_token%} in the webpage without double quorts.
Ajax code
$.ajax({
type:'POST',
url:'/task/'+todo_id+'/new_todo/',
processData: false,
contentType: false,
data: data,
success: function(response){
console.log("**********Data send to backend");
var new_id = response['new_id'];
var new_color = response['new_color'];
var new_status = response['new_status']
var new_todo_note = response['new_todo_note']
if (new_todo_note == null){
my_note = " "
}
else{
my_note = new_todo_note
}
$("#"+todo_id).hide();
$.ajax({
type:'GET',
url:'/task/'+todo_id+'/new_todo/',
data:data,
dataType:'json',
success: function(response){
var todo_section = `<ol class="list-group mb-3 v1" id="${response.latest_todo.id}right">
<li class="list-group-item d-flex justify-content-between align-items-start">
<div class="ms-2 me-auto d-flex">
<div>
<div class="fw-bold">${response.latest_todo_name}</div>
<p style="font-size: x-small; margin:0;">${response.latest_todo_added_date}</p>
<div style="max-width: 100px; display:flex; ">
<div id="${new_id}task_note">
${my_note}
</div>
</div>
</div>
<div class="mt-1 ms-4">
<a href="{%url 'todo-details' todo.id%}">
<i class="fa-solid fa-arrow-up-right-from-square text-muted"></i>
</a>
</div>
</div>
<div class="d-flex flex-column">
<div style="align-self: flex-end;" id="${new_id}badge_live">
<span class="badge rounded-pill" id="${new_id}badge" style="background-color:${new_color};">&nbsp&nbsp&nbsp
</span>
</div>
<div class="mt-2 d-flex">
<div class="me-2">
<button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#exampleModal" style="font-size: xx-small;">
Note
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Create Task Note</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="/todo/${new_id}/add_note/" method="post" id="task_note_form" name="${new_id}" enctype="multipart/form-data">
{%csrf_token%}
<div class="modal-body">
<div>
<h2>Add Task Note</h2>
</div>
<div class="mb-3">
<textarea name="note" id="note${new_id}" cols="15" rows="5" class="form-control" required></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary note_submit_btns" value="Create" data-bs-dismiss="modal" name="${new_id}">
</div>
</form>
</div>
</div>
</div>
</div>
<div id="${new_id}btn_live_change">
<div id="${new_id}btn_live">
<input type="submit" value="${new_status}" id="${new_id}"
class="btn btn-primary stat_btns"
style="font-size: xx-small;">
</div>
</div>
</div>
</div>
</li>
</ol>`
$("#display-todo-data").append(todo_section);
document.getElementById("task_note_form").reset();
},
});
}
});
}
});

Related

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>

How to open a Bootstrap modal using jQuery?

I'm using Twitter Bootstrap modal window functionality. When someone clicks submit on my form, I want to show the modal window upon clicking the "submit button" in the form.
<form id="myform" class="form-wizard">
<h2 class="form-wizard-heading">BootStap Wizard Form</h2>
<input type="text" value=""/>
<input type="submit"/>
</form>
<!-- Modal -->
<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">Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
$('#myform').on('submit', function(ev) {
$('#my-modal').modal({
show: 'false'
});
var data = $(this).serializeObject();
json_data = JSON.stringify(data);
$("#results").text(json_data);
$(".modal-body").text(json_data);
// $("#results").text(data);
ev.preventDefault();
});
I have check demo from this website
https://bootstrapmodal.com
There was some missing divs in your modal that I have included below (modal-dialog and modal-content classes)
Also added a name attribute to your input so you can serialize it with serialize() according to https://api.jquery.com/serialize/
$('#myform').on('submit', function(ev) {
$('#myModal').modal('show');
var data = $(this).serialize();
json_data = JSON.stringify(data);
$("#results").text(json_data);
$(".modal-body").text(json_data);
// $("#results").text(data);
ev.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-SI27wrMjH3ZZ89r4o+fGIJtnzkAnFs3E4qz9DIYioCQ5l9Rd/7UAa8DHcaL8jkWt" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/js/bootstrap.min.js" integrity="sha384-3qaqj0lc6sV/qpzrc1N5DC6i1VRn/HyX4qdPaiEFbn54VjQBEU341pvjz7Dv3n6P" crossorigin="anonymous"></script>
<form id="myform" class="form-wizard">
<h2 class="form-wizard-heading">BootStap Wizard Form</h2>
<input type="text" name="text" value=""/>
<input type="submit"/>
</form>
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 id="myModalLabel">Modal header</h3>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>

Bootstrap wizard not working inside Bootstrap modal or jquery-ui dialog

Stuck on this for quite some time now, I am trying to create a form wizard using twitter bootstrap wizard (http://vinceg.github.io/twitter-bootstrap-wizard/) which is shown on button click inside a modal window. This doesn't seem to be working for me.
The wizard is created dynamically using an ajax call, which returns the html for the wizard. I also tried using jQuery Steps plugin which was also not working properly inside the modal windows. I tried 2 approaches:
Appending the wizard html inside a jquery-ui dialog. - Here the jquery steps plugin method .steps() wasn't able to create the wizard, rather flat html was rendered instead of a wizard.
Appending the wizard html inside a bootstrap wizard - Tabs are created as links, but clicking on either of the tabs navigates to localhost:port//#tab1
Here are my code snippets:
Bootstrap Wizard
<div id="MainContainer">
<form id="MainForm" class="form-horizontal">
<div class='sectionA' id='rootwizard'>
<ul class="nav nav-tabs">
<li class="active">Tab1</li>
<li>Tab2</li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="Tab1">
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" id="emailfield" name="emailfield" class="required email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" id="namefield" name="namefield" class="required">
</div>
</div>
</div>
<div class="tab-pane" id="Tab2">
<div class="control-group">
<label class="control-label" for="url">URL</label>
<div class="controls">
<input type="text" id="urlfield" name="urlfield" class="required url">
</div>
</div>
</div>
<ul class="pager wizard">
<li class="previous">Previous</li>
<li class="next">Next</li>
</ul>
</div>
</div>
</form>
</div>
Modal Window
<div id="MainDiv" tabindex="-1" class="modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Trigger</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="DialogDiv">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Javascript
$('#MainDiv').on('shown.bs.modal', function (e) {
$.ajax({
url: '/MethodToFetchData',
type: 'POST',
data: data,
contentType: 'application/json; charset=utf-8',
success: function (data) {
var html = JSON.stringify(data);
html = html.replace(/(?:\\[rn])+/g, "");
initTriggerAdvancedEdit(html);
},
error: function (err) { alert(JSON.stringify(err)); }
});
});
function initTriggerAdvancedEdit(html) {
$('#rootwizard').bootstrapWizard({
'tabClass': 'nav nav-pills'
});
}

Bootstrap modal as dropdown

<div id="lastcolumn" class="col-md-3">
<ul class="nav navbar-nav pull-right">
<li class="llogin"><a class="mlogin" data-target="#loginmodal" data-toggle="modal"><span class="glyphicon glyphicon-chevron-down pull-right"></span>Login</a></li>
<div class="modal" id="loginmodal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" name="text" class="form-control">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="Password" name="text" class="form-control">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<li class="lsignup"><a class="msignup"><span class="glyphicon glyphicon-chevron-down pull-right"></span>Signup</a></li>
<li class="lcart"><a class="mcart"><span class="glyphicon glyphicon-shopping-cart pull-right"></span>Item</a></li>
</ul>
</div>
</div>
</div>
I want to show bootstrap modal as dropdown under login currently my modal is showing in middle of the screen what i have to do to achieve the desired behaviour, kindly help.enter image description here
Move the .modal div in the li that you want to attach the modal with. Then define position:relative; for that li and position:absolute; for that .modal.
Here's a working snippet. I removed the .modal-backdrop and edited padding and margin for modal. You can ignore them since they are not relevant to the basic problem.
.nav.navbar-nav li{
float:left;
}
.nav.navbar-nav li a.mlogin{
position:relative;
}
div.modal#loginmodal{
position:absolute;
width:200px;
height:300px;
top:30px;
left:0;
padding:0;
margin:0;
}
div.modal#loginmodal .modal-footer{
padding:5px;
margin:0;
}
div.modal#loginmodal .modal-body{
padding:10px 20px;
margin:0;
}
div.modal#loginmodal .modal-header{
padding:5px 20px;
margin:0;
}
.modal-backdrop{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div id="lastcolumn" class="col-md-3">
<ul class="nav navbar-nav pull-right">
<li class="llogin"><a class="mlogin" data-target="#loginmodal" data-toggle="modal"><span class="glyphicon glyphicon-chevron-down pull-right"></span>Login</a>
<div class="modal" id="loginmodal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" name="text" class="form-control">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="Password" name="text" class="form-control">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</li>
<li class="lsignup"><a class="msignup"><span class="glyphicon glyphicon-chevron-down pull-right"></span>Signup</a></li>
<li class="lcart"><a class="mcart"><span class="glyphicon glyphicon-shopping-cart pull-right"></span>Item</a></li>
</ul>
</div>

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.