How to list the id with getlist method in Django checkbox - django

html file
Here I list the client and Process in the input tag
And select the and submit
{% extends 'client_pannel.html' %}
{% block content %}
<script>
function postConfirm() {
if (confirm('Are you sure you want to delete this client')) {
yourformelement.submit();
} else {
return false;
}
}
</script>
<form method="POST">
{% csrf_token %}
<div class="breadcome-area">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="breadcome-list single-page-breadcome">
<div class="row">
<div class="col-lg-10 col-md-6 col-sm-6 col-xs-12">
<div class="breadcome-heading">
<form role="search" class="sr-input-func">
<label>{{ emp.first_name }} {{ emp.last_name }}</label>
</form>
</div>
</div>
<div class="col-lg-2 col-md-6 col-sm-6 col-xs-12">
<a href="/employee_list/"> <button type="submit"
class="btn btn-info add-new">Submit</button></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="data-table-area mg-b-15">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="sparkline13-list">
<div class="sparkline13-graph">
<div class="datatable-dashv1-list custom-datatable-overright">
<table id="table" data-toggle="table" data-pagination="true" data-search="true"
data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true"
data-key-events="true" data-show-toggle="true" data-resizable="true"
data-cookie="true" data-cookie-id-table="saveId" data-show-export="true"
data-click-to-select="true" data-toolbar="#toolbar">
<thead>
<tr>
<th>Process</th>
</tr>
</thead>
<tbody>
{% for client in form %}
<tr>
<td>
<input type="checkbox" name="cname[]" value="{{ client.id }}">
{{ client.Name }}
</td>
<td>
{% for process in client.clients %}
<input type="checkbox" name="process[]" value="{{ process.id }}">
{{ process.process }}<br />
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
{% endblock %}
views file
The below code is get the selected in checkbox. The getlist method return nothing
if request.method == "POST":
cname = request.POST.getlist('cname[]')
print("cname", cname)
process = request.POST.getlist('process[]')
print("process", process)

Related

IntegrityError at /send/ NOT NULL constraint failed: user_transactions.user_id

enter code heremodels
class Transactions(models.Model):
user=models.ForeignKey(CustomUser,related_name='accounts',on_delete=models.CASCADE, blank=True) recipient_account_type = models.CharField(max_length=230) recipient_name = models.CharField(max_length=100) recipient_acount_number = models.PositiveIntegerField() recipient_routing_number = models.PositiveIntegerField() recipient_bank_name = models.CharField(max_length=200) recipient_swift_code = models.CharField(max_length=100) recipient_sending_amount = models.DecimalField(max_digits=15, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) transaction_ID =models.IntegerField(default=ID) description = models.CharField(max_length=1000)
forms
class TransactionForm(forms.ModelForm):
class Meta:
model = Transactions
fields = ['recipient_account_type','recipient_name','recipient_acount_number',
'recipient_routing_number','recipient_bank_name','recipient_swift_code','recipient_sending_amount','description',]
Widget = forms.TextInput(attrs={'autofocus':'autofocus','size':'40', 'font-size':'xx-large'})
views
#login_required(login_url='/login/')
def send(request):
posts =Transactions.objects.filter(user=request.user)
form = TransactionForm()
if request.method=="POST":
form = TransactionForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/success/')
else:
print(form.errors)
# messages.error(request, 'Failed, Resend')
context = {'form':form,'posts':posts}
return render(request, 'index_user/send-money.html', context)
**template**
{% extends 'about/user-base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% load humanize %}
{% block content %}
<!-- Content
============================================= -->
<div id="content" class="py-4">
<div class="container">
<div class="row mt-4 mb-5">
<div class="col-lg-11 mx-auto">
<div class="row widget-steps">
<div class="col-12 step active">
<div class="step-name">Details</div>
</div>
</div>
</div>
</div>
<h2 class="fw-400 text-center mt-3">Send Money</h2>
<p class="lead text-center mb-4">Send your money at anytime, anywhere in the world.</p>
<div class="row">
<div class="col-md-18 col-lg-7 col-xl-6 mx-auto bg-primary">
<div class="bg-white shadow-sm rounded p-3 pt-sm-4 pb-sm-5 px-sm-5 mb-4">
<hr class="mx-n3 mx-sm-n5 mb-4">
<div class="bg-white shadow-sm rounded p- pt-sm-5 pb-sm-5 px-sm-5 mb-4 bg-secondary">
<div class="text-center bg-primary p-4 rounded mb-4">
<h3 class="text-10 text-white fw-400">${{user.account_balance|intcomma}}</h3>
<p class="text-white">Available Balance</p>
{% comment %} Withdraw Full Amount </div> {% endcomment %}
<!-- Send Money Form
============================ -->
<p style="color: red; font-size:large">
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
</p>
<center style="background-color: #007bff;">
<form id="form-send-money" method="POST" action="" class="bg-success" >
{% csrf_token %}
<div class="mb-3 pb-sm-5 px-sm-5">
{% comment %} <label for="withdrawto" class="form-label">Withdraw From</label> {% endcomment %}
<br>
{% comment %} <select id="withdrawto" class="form-select px-sm-4 pb-sm-1" name="">
<option value="">FNMB Bank - {{user.account_number}}</option>
</select> {% endcomment %}
</div>
<div id="id_long_desk" class="mb-3 px-sm-4 pb-sm-9">
<label for="emailID" class="form-label">Recipient Full Name</label>
<br>
{{form.recipient_name}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Account Number</label>
<br>
{{form.recipient_acount_number}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Bank Name</label>
<br>
{{form.recipient_bank_name}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Routing Number</label>
<br>
{{form.recipient_routing_number}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Swift Code</label>
<br>
{{form.recipient_swift_code}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Account Type</label>
<br>
{{form.recipient_account_type}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Sending Amount</label>
<br>
{{form.recipient_sending_amount}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Description</label>
<br>
{{form.description}}
</div>
{% comment %} <div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Fees</label>
<br>
$ {{form.fees}}
</div> {% endcomment %}
<!-- <p>Transfer Fees <span class="float-end"> 12.21 USD</span></p> -->
<hr>
<div class="d-grid"><button class="submit btn btn bg-white">Send</button></div>
<hr>
</form>
</center>
<!-- Send Money Form end -->
</div>
</div>
</div>
</div>
</div>
<!-- Content end -->
{% endblock %}
Have you checked whether your form is valid with something like the following?
if form.is_valid():
obj = form.save()
else:
# errror handling? debug with form.errors...
If your code does look like above, please add more info (like the form handling method as a whole)

Custom Form for create and update the blogposts give Page Not Found error

I've create a simple form to create and update the blogposts. After the creation of the update view happen something strange that I can't solve.
views.py
def createPost(request):
if request.method == "POST":
form = BlogPostForm(request.POST or None)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug_post = slugify(new_post.title)
new_post.save()
return redirect('post_list')
else:
form = BlogPostForm()
context = {
'form': form,
}
template = 'blog/editing/create_post.html'
return render(request, template, context)
def updatePost(request, slug_post=None):
update_post = get_object_or_404(BlogPost, slug_post=slug_post)
form = BlogPostForm(request.POST or None, instance=update_post)
if form.is_valid():
update_post = form.save(commit=False)
update_post.slug_post = slugify(update_post.title)
update_post.save()
return redirect('post_list')
context = {
'form': form,
}
template = 'blog/editing/create_post.html'
return render(request, template, context)
urls.py
urlpatterns = [
path("blog/", views.listPost, name='post_list'),
path("blog/<str:slug_post>/", views.singlePost, name='single_post'),
path("blog/create-post/", views.createPost, name='create_post'),
path("blog/<str:slug_post>/update-post/", views.updatePost, name='update_post'),
path("blog/<str:slug_post>/delete-post/", views.deletePost, name='delete_post'),
]
post_list.html
<div class="row">
{% for post in post_list %}
{% if forloop.first %}<div class="card-deck">{% endif %}
<div class="card mb-3 shadow" style="max-width: 540px;">
<div class="row no-gutters">
<div class="col-md-4">
<img src="{{ post.header_image_link }}" class="card-img" alt="{{ post.title }}" style="height: 250px;">
</div>
<div class="col-md-8">
<div class="card-body">
<h4 class="card-title">{{ post.title }}</h4>
<p class="card-text">{{ post.description }}</p>
<p class="card-text my-0 py-0"><small class="text-muted"><strong>Published: </strong>{{ post.publishing_date|date }}</small></p>
</div>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:"4" or forloop.last %}</div>{% endif %}
{% if forloop.counter|divisibleby:"4" and not forloop.last %}<div class="card-deck">{% endif %}
{% empty %}
<div class="row justify-content-md-center my-3 mx-1 py-2 shadow bg-danger rounded">
<div class="col-md-auto">
<h1 class="text-center px-2 py-2" id="text-shadow">Empty list!</h1>
</div>
</div>
{% endfor %}
</div>
create_post.html
<form class="" method="POST" enctype="multipart/form-data" novalidate>{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<div class="form-group mb-4">
<div>{{ form.title }}</div>
<label for="id_title">
<span class="text-info" data-toggle="tooltip" title="{{ form.title.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.title.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.description }}</div>
<label for="id_description">
<span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.description.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.description.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.contents }}</div>
<label for="id_contents">
<span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.contents.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.contents.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.header_image_link }}</div>
<label for="id_highlighted">
<span class="text-info" data-toggle="tooltip" title="{{ form.header_image_link.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.header_image_link.errors }}</small>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="form-inline mb-4 py-0">
<div class="input-group mx-1">
<label for="id_highlighted">{{ form.highlighted.label }}</label>
<div class="ml-1">{{ form.highlighted }}</div>
</div>
<div class="input-group mx-1">
<label for="id_draft">{{ form.draft.label }}</label>
<div class="ml-1">{{ form.draft }}</div>
</div>
</div>
<div class="form-group mb-4">
<label for="publishing_date_field">
{{ form.publishing_date.label }}
<small class="text-danger">{{ form.publishing_date.errors }}</small>
</label>
<div class="input-group date" data-target-input="nearest">
{{ form.publishing_date }}
<div class="input-group-append" data-target="#publishing_date_field" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
<script>
$(function () {
$("#publishing_date_field").datetimepicker({
format: 'DD/MM/YYYY HH:mm',
});
});
</script>
</div>
<div class="form-group mb-4">
<div class="row justify-content-md-center py-4 border border-warning rounded">
<h5 class="text-justify px-3">Clicca sul tasto che segue per vedere l'elenco delle immagini. Potrai copiare il link all'immagine che ti interessa ed usarlo per creare l'immagine di testata o migliorare i contenuti del post.</h5>
<button type="button" class="btn btn-primary mt-2 mx-2" data-toggle="modal" data-target=".bd-example-modal-xl">Image list</button>
</div>
<div class="modal fade bd-example-modal-xl" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-body">
{% for image in images_url_list %}
{% if forloop.first %}<div class="card-deck">{% endif %}
<div class="card mx-1 my-1" style="height: 100%; width: 300px;">
<img src="{{ image.file.url }}" class="card-img-top h-100" alt="{{ image.file.url }}" id="{{ image.id }}">
<div class="card-body">
<button class="btn btn-outline-primary btn-sm" type="button" onclick="CopyToClipboard('{{ image.id }}')">Copy URL</button>
</div>
</div>
{% if forloop.counter|divisibleby:"3" or forloop.last %}</div>{% endif %}
{% if forloop.counter|divisibleby:"3" and not forloop.last %}<div class="card-deck">{% endif %}
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="row justify-content-md-center">
<div class="col-md-auto">
<input type="submit" class="btn btn-info" value="Pubblica">
</div>
</div>
</div>
</form>
I have this error message if I try to create a new post with my form:
Page not found (404) Request Method: GET Request URL:
http://127.0.0.1:8000/blog/create-post/ Raised by:
blog.views.singlePost
As I said this happen after the creation of updatePost. If I comment the path of the single post path("blog/<str:slug_post>/", views.singlePost, name='single_post'), I can create a post whitout problems.
What I've wrong?
Move path("blog/<str:slug_post>/", views.singlePost, name='single_post') to the bottom of your list, below the update and delete paths.
urlpatterns = [
path("blog/", views.listPost, name='post_list'),
path("blog/create-post/", views.createPost, name='create_post'),
path("blog/<str:slug_post>/update-post/", views.updatePost, name='update_post'),
path("blog/<str:slug_post>/delete-post/", views.deletePost, name='delete_post'),
path("blog/<str:slug_post>/", views.singlePost, name='single_post'),
]

Delete data form after sending post request

I'm coding user management page. In page, I have form to add new user with post request and delete button with comfirmation form. I add new user successfully, page is reloaded, then I delete any account, but data in form I sent request to create new user is sent again with new user ID. How to fix?
user_management.html
{% extends 'pages/base.html' %}
{% block title %} Quản lý người dùng{% endblock %}
{% block active %}
{% endblock %}
{% block link %}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
{% endblock %}
{% load static %}
{% block css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/user_management.css' %}">
<style>
#messages {
width: 200px;
height: 50px;
text-align: center;
}
</style>
{% endblock %}
{% block content %}
<div class="container">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-5">
<h2>Quản lý người dùng</h2>
</div>
<div class="col-sm-7">
<button type="button" class="btn btn-primary" data-toggle="modal"
data-target="#modalRegisterForm">
<i class="material-icons"></i>
<span>Thêm mới</span></button>
</div>
</div>
</div>
{% ifequal msg null %}
{% else %}
<div id="messages" class="alert alert-success" role="alert">
<span class="">{{ msg }}</span>
</div>
{% endifequal %}
<p id="delete-notifa"></p>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>User ID</th>
<th>Name</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.id }}</td>
<td> {{ user.first_name }} {{ user.last_name }}</td>
<td>{{ user.date_joined }}</td>
<td>
<a href="{% url 'profile' user.id %}" class="edit" title="Edit" data-toggle="tooltip"><i
class="material-icons"></i></a>
<a href="#comfirmationForm" class="delete" title="Delete" data-toggle="modal"
data-id="{{ user.id }}"><i
class="material-icons"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="clearfix">
<div class="hint-text">Showing <b>5</b> out of <b>25</b> entries</div>
<ul class="pagination">
<li class="page-item disabled">Previous</li>
<li class="page-item">1</li>
<li class="page-item">2</li>
<li class="page-item active">3</li>
<li class="page-item">4</li>
<li class="page-item">5</li>
<li class="page-item">Next</li>
</ul>
</div>
</div>
</div>
<div class="modal fade mt-5" id="modalRegisterForm" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header text-xs-center">
<h5 class="modal-title font-weight-bold" id="myModalLabel">Thêm người dùng</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body mx-3">
<form action="{% url 'user_management' %}" method="post" id="addNewUser">
{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<input type="text" class="form-control" name="first_name" id="first_name"
placeholder="First Name">
</div>
<div class="col-xs-6">
<input type="text" class="form-control" name="last_name" id="last_name"
placeholder="Last Name">
</div>
</div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email" id="email"
required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="Password"
id="id_password"
required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" name="confirm_password" id="id_comfirm_pass"
placeholder="Confirm Password" required="required"
onkeyup="matchingPassword('id_password', 'id_comfirm_pass', 'msg');">
</div>
<p id="msg"></p>
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg btn-block" name="add">Thêm</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="comfirmationForm" class="modal fade">
<div class="modal-dialog modal-confirm">
<div class="modal-content">
<div class="modal-header">
<div class="icon-box">
<i class="material-icons"></i>
</div>
<h4 class="modal-title">Xác nhận</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>Do you really want to delete this user?</p>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger" id="btn_button">Delete</button>
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
{% endblock %}
{% block script %}
<script>
function matchingPassword(id_pass, id_comfirm_pass, id_msg) {
var pass = document.getElementById(id_pass).value;
var comfirm_pass = document.getElementById(id_comfirm_pass).value;
if (pass != comfirm_pass) {
document.getElementById(id_msg).style.color = 'red';
document.getElementById(id_msg).innerHTML = "Mật khẩu không trùng nhau";
} else {
document.getElementById(id_msg).innerHTML = "";
}
}
</script>
<script>
var tmp;
$('.delete').click(function () {
tmp = $(this).attr('data-id');
});
$('#btn_button').click(function () {
$.ajax({
url: '/delete_user',
type: 'get',
dataType: 'json',
data: {
user_id: tmp,
},
success: function (data) {
if (data.is_error) {
alert("Xóa không thành công");
window.location.reload();
} else {
alert("Xóa thành công");
location.reload();
}
}
})
})
setTimeout(function () {
$('#messages').hide()
}, 1000);
setTimeout(function () {
$('#delete-notifa').hide()
}, 1000);
</script>
{% endblock %}
views.py
def user_management(request):
if request.method == "POST":
if 'add' in request.POST:
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
username = request.POST.get('email')
password = request.POST.get('password')
user = User.objects.create_user(username=username, email=username, password=password, first_name=first_name,
last_name=last_name)
user.save()
user_info = UserInfor(user=user)
user_info.save()
user_list = User.objects.all()
msg = "Thêm thành công"
return render(request, 'pages/user_management.html', {'users': user_list, 'msg': msg})
else:
user_list = User.objects.all()
msg = "Thất bại"
return render(request, 'pages/user_management.html', {'users': user_list, 'msg': msg})
else:
user_list = User.objects.all()
return render(request, 'pages/user_management.html', {'users': user_list})
def delete_user(request):
data = {}
user_id = request.GET.get('user_id')
user = User.objects.get(id=user_id)
user_info = UserInfor.objects.get(user_id=user.id)
user.delete()
user_info.delete()
data['is_error'] = User.objects.filter(id=user_id).exists()
return JsonResponse(data)
I believe your problem is that you're using
type="submit" id="btn_button" and $('#btn_button').click(... together
I believe your modal-footer is triggering your form tag that's why when you click Delete button your page get's reloaded.
and at the same time $('#btn_button').click(function () {... is doing it's job by sending GET request to the server.
So as soon as you hit delete button, POST request to create user via form submission is sent and GET request to delete user is also sent.
Try changing this:
<button type="button" class="btn btn-danger" id="btn_button">Delete</button>
to
<button type="submit" class="btn btn-danger" id="btn_button">Delete</button>
Happy coding :)

Django Graphos Chart Not Loaded On Table Update Using Ajax

I have been using django graphos and it works fine till i realize that the chart is not drawn when i update my table through ajax instead of a page refresh. Let me describe the issue further.
When my page is loaded for the first time, all the charts are loaded properly using {{chart.as_html}} . I am usng django by the way .
This charts are displayed in a table.
But when user selects different value from a dropdown and click reload, my code will only update the table through ajax instead of a whole page refresh. Unfortunately , when the table is updated, the chart with new data is not displayed. It just appears blank. I can see all the data from the developer tools but the chart just fail to appear.
I have checked through various topics but I am unable to get it working.
Part of my main html file
{% if objects %}
{% for obj in objects %}
<tr data-toggle="collapse" data-target="#{{obj.name}}" data-parent="#myGroup" class="accordion-toggle">
<!--tr>-->
<td style="border:0;"><img src='{{STATIC_URL}}/static/images/{{obj.name}}.png' class="infostockIcon"></td>
{% if obj.risk == "high" %}
{% if obj.dpr == "high" %}
<td class="tablerisk"><strong> * {{obj.name}} </strong></td>
{% else %}
<td class="tablerisk"><strong> {{obj.name}} </strong></td>
{% endif %}
<td class="tablerisk"> {{obj.stock_price}} </td>
<td class="tablerisk" style="color: black;"> {{obj.option_strategy}} </td>
<td class="tablerisk" style="color: black;"> {{obj.whiz_strategy}} </td>
<td class="tablerisk"> {{obj.strike_price}} </td>
<td class="tablerisk"> {{obj.expiry_date}} </td>
<td class="tablerisk"> {{obj.premium}} </td>
<td class="tablerisk"> {{obj.roi}} </td>
{% else %}
{% if obj.dpr == "high" %}
<td><strong> * {{obj.name}} </strong></td>
{% else %}
<td><strong> {{obj.name}} </strong></td>
{% endif %}
<td> {{obj.stock_price}} </td>
<td> {{obj.option_strategy}} </td>
<td> {{obj.whiz_strategy}} </td>
<td> {{obj.strike_price}} </td>
<td> {{obj.expiry_date}} </td>
<td> {{obj.premium}} </td>
<td> {{obj.roi}} </td>
{% endif %}
<td style="border:0;"><span class="caret black"></span></th></td>
</tr>
<tr>
<td style="border: 0;padding: 0 !important;"></td>
<td colspan="8" style="padding: 0 !important; border: none;">
<div class="accordion-body collapse" id="{{obj.name}}">
<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
<li data-toggle="tab" class="active">
Monthly Seasonality
</li>
<li data-toggle="tab">
Weekly Seasonality
</li>
<li data-toggle="tab">
Dividend
</li>
<li data-toggle="tab">
{{obj.name}} Info
</li>
</ul>
<div id="my-tab-content" class="tab-content">
<div class="tab-pane active" id="{{obj.name}}monthseason">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<h4>Monthly Seasonality<img src='{{STATIC_URL}}/static/info.png' class="infoIcon" style="float: none; right: 0px; margin-left: 5px" /></h4>
<div id="gchart_div">
{{ obj.monthly_chart.as_html}}
</div>
</div>
</div>
</div>
<div class="tab-pane" id="{{obj.name}}weekseason">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<h4>Weekly Seasonality<img src='{{STATIC_URL}}/static/info.png' class="infoIcon" style="float: none; right: 0px; margin-left: 5px"/></h4>
{{ obj.weekly_chart.as_html}}
</div>
</div>
</div>
<div class="tab-pane" id="{{obj.name}}dividend">
<!--div style="padding-left: 2%;" >-->
<div class="row">
<div class="col-md-5 col-xs-6 col-sm-6 alignLeft">
<label >TTM Dividend Yield:</label>
<label >{{obj.ttm_dividend_yield}}</label>
</div>
<div class="col-md-5 col-xs-6 col-sm-6 alignLeft">
<label >Ex-Dividend Date:</label>
<label >{{obj.ex_div}}</label>
</div>
</div>
<!--/div>-->
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<h4>Dividend Yield<img src='{{STATIC_URL}}/static/info.png' class="infoIcon" style="float: none; right: 0px; margin-left: 5px"/></h4>
{{obj.div_yearly_chart.as_html}}
</div>
</div>
</div>
<div class="tab-pane alignRight" id="{{obj.name}}data">
<div style="padding-left: 2%;" >
<div class="row">
<div class="col-md-5 col-xs-6 col-sm-6 alignLeft">
<label >Sector:</label>
<label >{{obj.sector}}</label>
</div>
<div class="col-md-5 col-xs-6 col-sm-6 alignLeft">
<label >Industry:</label>
<label >{{obj.industry}}</label>
</div>
</div>
<div class="row">
<div class="col-md-5 col-xs-6 col-sm-6 alignLeft">
<label >Earning Date:</label>
<label >{{obj.earnings_date}}</label>
</div>
<div class="col-md-5 col-xs-6 col-sm-6 alignLeft">
<label >Ex-Dividend Date:</label>
<label >{{obj.ex_div}}</label>
</div>
</div>
<div class="row">
<div class="col-md-5 col-xs-6 col-sm-6 alignLeft">
<label >52 Week Range:</label>
<label >{{obj.year_range}}</label>
</div>
<div class="col-md-5 col-xs-6 col-sm-6 alignLeft">
<label >5 Year Low:</label>
<label >{{obj.five_year_low}}</label>
</div>
</div>
<div class="row">
<div class="col-md-5 col-xs-6 col-sm-6 alignLeft">
<label >DPR:</label>
<label >{{obj.dpr_value}}</label>
</div>
<div class="col-md-5 col-xs-6 col-sm-6 alignLeft">
<label >Latest News:</label>
<a href={{obj.url}}>Seeking Alpha</a>
</div>
</div>
</div>
<br>
</div>
</div>
</div>
</td>
</tr>
My ajax call:
`var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
$myGroup.find('.collapse.in').collapse('hide');
});
$('#tabs li a').click(function (e) {
$('#tabs li a.active').removeClass('active');
$(this).parent('li a').addClass('active');
});
$("#loadprofit").on("click", function(e)
{
//alert("asdas");
e.preventDefault();
var selectedOption = $("#strategy").val();
var selectedDate = $("#strategy2").val();
csrf_token = "{{ csrf_token }}";
$.ajax({
method: "POST",
url: window.location.href,
data: { selected_option: selectedOption,selected_date:selectedDate,csrfmiddlewaretoken: csrf_token },
})
.done(function( msg )
{
console.log(msg);
$("#sct tbody").html(msg);
});
});
</script>
{% endblock %}
`
This whole table gets updated when user clicks on a button. Then it calls views.py and table gets updated with the latest value. But {{ obj.monthly_chart.as_html}} is not loaded and it appears blank although i can see the whole chart drawing function and the data form the developer tool
Any help is greatly appreciated.

multi modals bootstrap in for loop django

I have a for loop on my html code to display a list of data, when I made a Bootstrap Modal in this loop to display it for each element of the list. It seems that the modal work only for the first element of the list.
{% for i in lb %}
<button class="btn" id="myBtn" title="Ajouter Serveur" style="padding-bottom:1px" data-target="#myModal"><a class="icon-plus-sign" title="Ajouter Serveur"></a></button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Ajouter Serveur</h4>
</div>
<div class="modal-body">
<form method="post" class="loginForm">
<input type="hidden" name="lb" value="{{ i.Nom }}">
<h6>{% csrf_token %}
{{ form.as_table }}</h6>
<input type="submit" name="submit" class="btn btn-primary " value="Submit" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div></div>
{% endfor %}
The id value of the button and <div class="modal"> have to be unique in the document.
Try adding a unique value to the id, ie:
<div class="span12">
{% for i in lb %}
<div id="Person-1" class="box">
<div class="box-header">
<div class="span10">
<i class="icon-hdd icon-large"></i>
<h5>{{i.Nom}}</h5></div>
<button class="btn" id="myBtn{{i.id}}" title="Ajouter Serveur" style="padding-bottom:1px" data-target="#myModal{{ i.id }}"><a class="icon-plus-sign" title="Ajouter Serveur"></a></button>
<div class="modal fade" id="myModal{{ i.id }}" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Ajouter Serveur</h4>
</div>
<div class="modal-body">
<form method="post" class="loginForm">
<input type="hidden" name="lb" value="{{ i.Nom }}">
<h6>{% csrf_token %}
{{ form.as_table }}</h6>
<input type="submit" name="submit" class="btn btn-primary " value="Submit" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div></div>
</div>
<div class="box-content box-table">
<table class="table table-hover tablesorter">
<thead>
<tr>
<th>Nom</th>
<th>Adresse</th>
<th>Etat</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{% for j in s %}
{% if i.Nom == j.LB %}
<tr>
<td>{{ j.Nom }}</td>
<td>{{ j.Adresse }}</td>
{% if j.Etat == m %}
<td>Désactiver</td>
{% else %}
<td>Activer</td>
{% endif %}
<td><a>Edit</a></td>
<td>Supprimer</td>
{% if j.Etat == m %}
<td class="icon-ok-circle icon-large" style="color : green" title="Activé"></td>
{% else %}
<td class="icon-remove-circle icon-large" style="color : red" title="Désactivé"></td>
{% endif %}
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
</div>
<script>
var a = "{{ i.id }}"
$(document).ready(function(){
$("#myBtn"+a).click(function(){
$("#myModal"+a).modal({show:true});
});
});
</script>
{% endfor %}
</div>
In HTML id have unique identification. So we use unique id in every modal
{% for l in lamp %}
<h6>change in button</h6>
<button data-target="#mymodal{{l.id}}"</button>
<h6>change in modal id </h6>
<div class="modal" id="mymodal{{l.id}}"</div>
{% endfor %}