passing a for loop value to bootstarp modal in django - django

Here i am trying to pass the value outside for loop modal using ajax
Here is the reference link which i followed reference link and please help me where i am wrong
here is my template.html
{% for compliance in compliance %}
{% complience_category compliance request.user as compliances %}
{% for qualification in compliances %}
.....
.....
<td>
<button data-toggle="modal" data-target="#modal-default" data-id="{{ qualification.id }}" type="button" class="btn btn-warning margin-bottom edit-qualification">
edit
</button>
</td>
....
.....
{% endfor %}
{% endfor %}
{% csrf_token %}
<div class="modal hid fade" id="modal-default">
<div class="modal-dialog">
<form class="form-horizontal" method="POST" enctype="multipart/form-data" action="{% url 'update_qualifications' qualification.id %}" ">
{% csrf_token %}
{% if qualification %}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Update Compliance</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="inputdate_{{qualification.id}}">Expiry Date</label>
<div class="controls">
<input type="date" id="inputdate_{{qualification.id}}" name="expiry_date" value="{{qualification.expiry_date|date:'Y-m-d'}}">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit">Save</button>
</div>
{% endif %}
</form>
</div>
</div>
here is my AJAX
<script>
$(document).on('click','.edit-qualification',function(){
var id = $(this).data('id');
console.log(id)
$.ajax({
url:'',
type:'POST',
data:{
'id':id,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
},
success:function(data){
$('#modal-default .modal-dialog').html($('#modal-default .modal-dialog',data));
$('#modal-default').modal('show');
},
error:function(){
console.log('error')
},
});
});
</script>
Here is my views.py
#login_required
def update_qualifications(request, qualifiaction_id):
client = request.user.client
next_url = request.POST.get('next', '/')
date = request.POST.get('expiry_date') or None
record_date = request.POST.get('record_date') or None
name = request.POST.get('id_name')
compilance = request.POST.get('compliance')
document = request.FILES.get('document')
qualification = get_object_or_404(ClientUserQualification, pk=qualifiaction_id)
if document:
qualification.document = document
done = request.POST.get('done', False)
qualification.expiry_date = date
qualification.record_date = record_date
if request.user.is_admin:
qualification.validated = True
else:
qualification.validated = False
qualification.done = done
if name:
qualification.name = name
qualification.qualification_id = compilance
messages.success(request, 'Compliance was successfully updated.')
if request.user.is_admin:
qualification.save()
return redirect(next_url)
qualification.validated = False
qualification.save()
return redirect(reverse('worker_compliance_list'))
here when clicking edit of particular item it need to update only for that item
Please help me to solve this problem where i am wrong

Related

My data is not going into post operation in django. How to do the Post call in this function?

I am working on a Django project where I have a form which I want to do POST. but everytime it went to the else part.
here's my view:
def ATFrun(request,test_case_ID):
if request.method == 'POST':
print("post")
url = 'http://www.google.com'
pi = APIDetails.objects.get(pk=test_case_ID)
atfParam= list(APIParameter.objects.values('id','parameterName','parameterValue').filter(TC_ID=pi))
fm = APIDetailsReg(request.POST, instance=pi)
req = fm.data
# req = request.POST
req_list = list(dict(req).values())
ATFparams_count = len(req_list)
ATFparams = ""
if ATFparams_count > 0:
for i in range(ATFparams_count-1):
ATFparams = ATFparams + req_list[i+1][0] + '=' + req_list[i+1][1] + '&'
data = ATFparams[:-1]
url = url + data
print('paramfinal',url)
if fm.is_valid():
fm.save()
fm = APIDetailsReg()
return HttpResponseRedirect('/TAFDashboard')
else:
print("not post")
pi = APIDetails.objects.get(pk=test_case_ID)
fm = APIDetailsReg(instance=pi)
atfParam= list(APIParameter.objects.values('id','parameterName','parameterValue').filter(TC_ID=pi))
atf = APIDetails.objects.all()
return render(request, 'hello/ATF_Run.html',{'ATF': atf, 'Param': atfParam})
here's my html form
<div class="panel panel-info atf-form">
<div class="panel-heading text-center" style="background-color: #660099;">
<h1 class="panel-title" style="color: white;">TAF Integration URL</h1>
</div>
<form style="margin-top: 10px;">
{% for param in Param %}
<div class="form-row">
<div class="form-group col-md-2">
<label for="param">TAF Parameter</label>
<input type="text" name="{{param.id}}" class="form-control" id="inputapi_param" value="{{param.parameterName}}" readonly>
</div>
{% if param.parameterName == 'api' or param.parameterName == 'callback' %}
<div class="form-group col-md-4">
<label for="val">TAF Value</label>
<input type="text" name="{{param.id}}" class="form-control" id="inputapi_val" value="{{param.parameterValue}}" readonly>
</div>
{%else%}
<div class="form-group col-md-4">
<label for="val">TAF Value</label>
<input type="text" name="{{param.id}}" class="form-control" id="inputapi_val" value="{{param.parameterValue}}" required>
</div>
{% endif %}
</div>
{% endfor %}
<div class="form-row ">
<div class="form-group col-md-12">
<button type="submit" class="btn btn-primary taf-btn"><b>Generate TAF URL</b></button>
</div>
</div>
</form>
</div>
can someone help with that post call? everytime it went to the else part but as per my requirement it should be in POST part.

Using Bootstrap Modal as Register and Login Form. On error the full page is served

I am using jquery.bootstrap.modal.forms.js to load Login and Register form from their url as Modals using the code below:
<script>
$(function ($, undefined) {
// log in & sign up buttons
$(".register-btn").modalForm({
modalID: "#registerModal",
formURL: "/register-modal/",
});
});
$(function ($, undefined) {
// log in & sign up buttons
$(".login-btn").modalForm({
modalID: "#registerModal",
formURL: "/login-modal/",
});
});
$(function ($, undefined) {
// log in & sign up buttons
$(".forgot-password").modalForm({
modalID: "#registerModal",
formURL: "/recover-modal/",
});
});
</script>
HTML code for the modal
<div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="registerModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document" style="width:400px;">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="registerModalLabel">Register</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</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>
Modal Code :
{% extends 'base.html' %}
{% load static %}
{% block title %} Login {% endblock %}
{% block style %}
{% endblock %}
{% block content %}
<div class="container-fluid ">
<div class="row ">
<div class="col-sm-12 col-xs-12 col-md-12">
<form class="account-register form-narrow p-3 mb-4 bg-white" id="login_form" method="POST"
action="" autocomplete="off">
{% if messages %}
<div id="messages">
{% for message in messages %}
<div class="alert alert-dismissible alert-info"
role="alert">
<button type="button" class="close" data-dismiss="alert"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message|escape }}
</div>
{% endfor %}
</div>
{% endif %}
{% if form.non_field_errors %}
<div id="messages">
{% for message in form.non_field_errors %}
<div class="alert alert-dismissible alert-danger"
role="alert">
<button type="button" class="close" data-dismiss="alert"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message|escape }}
</div>
{% endfor %}
</div>
{% endif %}
<div class="text-center">
<h4><i class="fa fa-lock fa-3x"></i></h4>
</div>
<h4 class="text-center mb-5">Login </h4>
{% csrf_token %}
<div class="form-group{% if form.username.errors %} has-error{% endif %}" >
<label class="control-label" for="id_username">Email Address</label>
<input class="form-control input-lg" id="id_username" maxlength="150" name="username" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" type="text" required />
<div class="error-block">{{ form.username.errors }}</div>
</div>
<div class="form-group{% if form.password.errors %} has-error{% endif %}">
<label class="control-label" for="id_password">Password</label>
<div class="input-group input-group-lg">
</div>
<input class="form-control input-lg" id="id_password" name="password" type="password" required />
<div class="error-block">{{ form.password.errors }}</div>
</div>
<div class="g-recaptcha mb-2" data-sitekey="6LebmPsZAAAAADT_1QjnC70TJ2aiBX1a9rqWmhev"
style="transform:scale(1.1);-webkit-transform:scale(1.1);transform-origin:0 0;-webkit-transform-origin:0 0;">
</div>
<button type="submit" name="login"
class="btn btn-danger btn-sm btn-block text-uppercase shadow-4 mb-4" >
Login<i class="fa fa-sign-in" aria-hidden="true"></i>
</button>
<br/>
<p class="text-center">
Don't have an account?<button type="button" class="register-btn a btn btn-link" style="font-size:14px; margin-top:-4px;">Register </button>
</p>
<br/>
<p class="text-center text-primary">
<button type="button" class="forgot-password a btn btn-link" style="font-size:14px; text-decoration:none;">Forgot user ID and/or password? </button>
</p>
</form>
</div>
</div>
</div>
<!-- /container -->
{% endblock %}
{% block scripts %}
<script src="{% static 'js/toggle.js' %}"></script>
<script src="{% static 'js/floating-wpp.min.js' %}"></script>
<script src="{% static 'js/jquery.magnific-popup.js' %}"></script>
<script src="{% static 'js/qoc_home.js' %}"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script>
<script>
$(document).ready(function(){
$("#login_form").on("submit", function(){
$("#pageloader").css('visibility', 'visible');
});//submit
});
$(function ($, undefined) {
// log in & sign up buttons
$(".register-btn").modalForm({
modalID: "#registerModal",
formURL: "/register-modal/",
});
});
$(function ($, undefined) {
// log in & sign up buttons
$(".forgot-password").modalForm({
modalID: "#registerModal",
formURL: "/recover-modal/",
});
});
</script>
{% endblock %}
LoginView Code
class LoginViewModal(FormView):
template_name = 'login-modal.html'
form_class = LoginForm
success_url = '/dashboard'
def get(self, request, *args, **kwargs):
if request.user.is_authenticated:
return redirect ("/dashboard")
else:
return super(LoginViewModal, self).get(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs):
if (self.request.user.is_authenticated) and (self.request.user.user_type==4):
return redirect('/dashboard')
else:
return super().dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""Use this to add extra context."""
context = super(LoginViewModal, self).get_context_data(**kwargs)
if 'show_captcha' in self.request.session:
show_captcha = self.request.session['show_captcha']
context['show_captcha'] = True
return context
def form_valid(self, form):
user = form.login(self.request)
recaptcha_response = self.request.POST.get('g-recaptcha-response')
url = 'https://www.google.com/recaptcha/api/siteverify'
payload = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
data = urllib.parse.urlencode(payload).encode()
req = urllib.request.Request(url, data=data)
# verify the token submitted with the form is valid
response = urllib.request.urlopen(req)
result = json.loads(response.read().decode())
if result['success']:
if user.two_factor_auth is False and (user.phone_number_verified is True):
login(self.request, user)
try:
UserLog.objects.filter(username=user.id).update(failed_attempt=0)
except Exception:
print("No failed attempts ")
return redirect('/dashboard')
else:
try:
response = send_verfication_code(user)
pass
except Exception as e:
messages.add_message(self.request, messages.ERROR,
'verification code not sent. \n'
'Please retry logging in.')
return redirect('/login')
data = json.loads(response.text)
if data['success'] == False:
messages.add_message(self.request, messages.ERROR,
data['message'])
return redirect('/login')
if data['success'] == True:
self.request.method = "GET"
print(self.request.method)
kwargs = {'user':user}
return PhoneVerificationView(self.request, **kwargs)
else:
messages.add_message(self.request, messages.ERROR,
data['message'])
return redirect('/login')
else:
messages.add_message(self.request, messages.ERROR, 'Invalid reCAPTCHA. Please try again.')
return redirect('/login')
When an error occurs in the form (for example if the user enters incorrect password. The modal redirects to /login-modal/ and a full page with login form is seen instead of returning to the same modal. What can I do in order to stay on the modal when error occurs ?
Correct me if I am wrong, what you are trying to achieve here is that when a user enters incorrect credentials, for example, you want to show an error message on the page without having to reload so that the credentials are not lost? if that is the case, you must use AJAX/fetch API, I'd go for AJAX since you're already using jquery, you can send the data using jquery $.post
Implementing AJAX with Django is a bit complicated but a simple google search would do, this tutorial explains how to implement a login and signup mechanism using ajax and Django.
Now if you just want to show the modal again when an error you could have an error variable as a boolean, with 0 being no errors and 1 being the opposite, and pass it to your front-end, and have a script tag in your HTML that will trigger the modal when there is an error.

Form Validation Not Displaying on Form

I have a custom form validation that runs on my popup window form. If the form validation occurs i get a bad request error which is what i have programmed in my views.py . How do i render it so the user stays on the form and the validation message displays. Thanks for the help. Here is my code.
#login_required
def K8_Points_Classroom(request):
#context_from_k8_points = request.session['k8_points_context']
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
else:
return HttpResponseBadRequest("Bad Request")
else:
return render(request, 'points/k8_points_classroom.html', {'form': form} )
Updated form.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% crispy K8Points_ClassroomForm %}
{% load static %}
{% block content %}
<br>
<h2>{% load static %}
<img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> {{class_name}}</h2>
<br>
<br>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<!-- Start Date -->
<div class="container">
<div class="container">
<div class='row'>
<div class="col-4">
<p> Recording Data as User : {{user.username}} </p>
</div>
</div>
<div class='row'>
<div class = "col-2">
{{form.date|as_crispy_field }}
</div>
<div class = "col-2">
{{form.week_of|as_crispy_field }}
</div>
<div class = "col-2">
{{form.day|as_crispy_field }}
</div>
</div>
</div>
</form>
<div class="jumbotron" align="middle">
<img src="{% static 'forms/levelup.png' %}" alt="levelup" height="120" width= "120">
<h1>My Students</h1>
<!-- Line Break -->
<hr style="border: 1px solid black;"/>
<!-- Line Break -->
<div class="row mb-3">
{% for i in students%}
<div class="col-md-4 themed-grid-col"><h2>{{i.student_name}}</h2>
<p align="left"> Today's Score: {{total}}</p>
<h4>
<button type="button" class="btn btn-primary btn-lg btn-block" data-toggle="modal"
data-target="#PointsBox{{ student.pk }}">Level Up
</button>
</h4>
<div id="PointsBox{{ student.pk }}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img src="{% static 'forms/star.png' %}" align="left" alt="chain" height="42"
width="42">
<h4 class="modal-title">Points Confirmation </h4>
<button type="button" class="close" data-dismiss="modal"> ×</button>
</div>
<div class="modal-body">
<h6>
<div class="modal-body">Please add the selected points for the current
student.</div>
</h6>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<div class="form-row" align='left'>
<div class="col-7">
{{form.class_name|as_crispy_field }}
<input type="student_name" class="form-control" value ="{{i}}" >
{{form.time_frame|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="col-3" align='left'>
{{form.behavior|as_crispy_field }}
{{form.academic|as_crispy_field }}
<button type="submit" class="btn btn-success" ><i
class="fas fa-star"></i> Level Up
</button>
</div>
</div>
</div>
<div class="modal-foot"></div>
</div>
</div>
</div>
</div>
</form>
{% endfor %}
{% endblock %}
You can't return a bad response if the form is invalid. Instead, render the page again with the invalid form and in the temolate you will be able to render the errors. Try starting rendering the form just using {{ form.as_p }} and you will see the errors. The form errors are in form.errors and each field has its own errors, you can access to them form.field.erorrs
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
return render(request, 'points/k8_points_classroom.html', {'form': form} )

where is the error in the update function?

i have django project that includes a form to be submit and allow user to create an update the stored data.
the problem is that once the user go the update page the system crash and display the below error :
local variable 'suspect' referenced before assignment
urls.py
path('update/<int:pk>/',update,name = 'update'),
update.html
{% extends "base.html" %}
{% load static %}
{% block body %}
<body>
<div class="lines">
<div class="line"></div><div class="line"></div>
<div class="line"></div><div class="line"></div>
<div class="line"></div><div class="line"></div><div class="line"></div>
</div>
{% for member in instance %}
<form enctype="multipart/form-data">
<div id='left-column-Input' class="formInput" include="select()">
<div class="forminputs">
<input type="text" id="fname" name="fname" autocomplete="off" required />
<label for="fname" class="label-name">
<span class="content-name" name="fname">{{member.member_name}}</span>
</label>
</div>
<div class="forminputs">
<input type="text" id="lname" name="lname" autocomplete="off" required />
<label for="lname" class="label-name">
<span class="content-name" name="lname">{{member.member_last_name}}</span>
</label></div>
<div class="forminputs">
<input type="text" id="fatherName" name="fatherName" autocomplete="off" required />
<label for="fatherName" class="label-name">
<span class="content-name" name="fatherName">{{member.member_father_name}}</span>
</label></div>
<div class="home-Button">
<button id="edit" name="edit" type="submit">Edit</button>
<button id="clear" name="clear" type="submit">Clear</button>
</div>
</div>
{% endfor %}
<script type="text/javascript">
$(document).ready(function(){
$("#edit").on('click',function(event){
event.preventDefault()
fName=$('#fname').val()
lName = $('#lname').val()
fatherName = $('#fatherName').val()
$.ajax({
url:'/blog/update',
method:'POST',
data: {
FName: fName,
LName: lName,
FatherName: fatherName,
},
headers:{
'X-CSRFToken':'{{csrf_token}}'
}
}).done(function(msg){
location.href='/blog/list'
}).fail(function(err){
alert(err)
})
})
})
</script>
</form>
</body>
{% endblock %}
views.py
def update(request,pk):
#deny anonymouse user to enter the detail page
if not request.user.is_authenticated:
return redirect("login")
else:
member = member()# the class modal
member = get_object_or_404(member, pk=pk)standard **page not found**
if request.method =="POST":
member = member()
member.member_name = request.POST['FName']
member.member_last_name = request.POST['LName']
member.member_father_name = request.POST['FatherName']
member.save()
context = {
"title":member.member_name,
"instance":member,
}
return render(request,'blog/update.html',context)
i will appreciate any help
Your URL needs pk. You're not passing suspect id as pk in your context of your return statement of your view.
path('update/<int:pk>/',update,name = 'update'),
suspect.id will work as an argument to your {% url ... %}

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 :)