Saving edited data back to database using django and knockout - django

I am trying to figure out how to save edited data back to the database using django forms and knockout. The edit.html file has been changed to use knockout to display and edit information on the edit page. I need to figure out how to change the views.py file to save the information. The page seems to be behaving how I want it to (I think...), but I don't know how to update the information back to the database once editing has occurred since I am not using django fields in the .html file.
I have read this thread: using knockout.js with django forms?, but that is using fields in the html file instead of the knockout code. I'm not opposed to going that route if that is a better method, but was struggling a little with the implementation of that idea when I tried it.
The relevant info from the views.py file:
#render_to('phones/edit.html')
def EditPhone(request, number):
p_number = PhoneTable.objects.get(number=number)
customer_list = list(Customer.objects.values('customer_id'))
JSON_customer_list = json.dumps(customer_list)
if not request.POST:
return dict(
form=PhoneForm(instance=p_number),
CallType=p_number.call_type,
number=number,
Customer=p_number.customer_id,
extension=p_number.profile.extension,
department=p_number.profile.department,
JSON_customer_list=JSON_customer_list
)
form = PhoneForm(request.POST, instance=p_number)
if not form.is_valid():
return dict(form=form)
form.save()
messages.success(request, 'Phone Number updated')
return redirect('phones:available_phones', number=p_number.number)
class PhoneForm(ModelForm):
class Meta:
model = PhoneTable
This is the html file:
{% block pagetitle %}Edit Phone Number: {{ number }}{% endblock %}
{% block content %}
<div class="row">
<div class="span2">
<div class="pull-right">Call Type:</div>
</div>
<div class="span6">
<select data-bind="options: callTypes, value: callType"></select>
</div>
</div>
<div class="row">
<!-- ko if: callType() === "Direct" -->
<div class="span2">
<div class="pull-right">Extension:</div>
</div>
<div class="span6">
<input type="text" data-bind="value: editExtension" />
</div>
<!-- /ko -->
</div>
<div class="row">
<!-- ko if: callType() === "Sales" -->
<div class="span2">
<div class="pull-right">Customer:</div>
</div>
<div class="span6">
<select data-bind="options: customerDisplays, value: selectedCustomer"></select>
</div>
<!-- /ko -->
</div>
<div class="row">
<!-- ko if: callType() === "Service" -->
<div class="span2">
<div class="pull-right">Service Profile:</div>
</div>
<div class="span6">
<select data-bind="options: servProfiles, value: servProfile"></select>
</div>
<!-- /ko -->
</div>
<div class="form-actions">
<input type="submit" class='btn btn-primary' value="Update" />
<a class="btn" href="{% url phones:available_phones %}">Cancel</a>
</div>
{% endblock %}
{% block javascript_compress %}
<script type='text/javascript' src="{% static 'js/knockout/knockout.js' %}"></script>
<script type="text/javascript">
$(function(){
customerListFromServer = {{ JSON_customer_list|safe }};
var PhoneViewModel = function() {
var self = this;
customerList = [];
for (var key in customerListFromServer) {
customerList.push(customerListFromServer[key].customer_id);
}
self.callTypes = ko.observableArray(['Free', 'Direct', 'Sales', 'Service']);
self.callType = ko.observable("{{ CallType }}");
self.editExtension = ko.observable("");
self.servProfiles = ko.observableArray(["{{ extension }}", "{{ department }}"]);
self.servProfile = ko.observable();
self.customerDisplays = ko.observableArray(customerList);
self.selectedCustomer = ko.observable();
}
ko.applyBindings(new PhoneViewModel());
});
</script>
{% endblock %}
Any suggestions? If I am missing something, please let me know. Thank you.

I figured this out, so I will post how if it can help anyone else.
I added a form id and post method along with a hidden field to the html file. As Kevin suggested, I used a data-bind on the submit button and added a submit function to the ko viewModel. Then I changed the views.py file to get the json data and to save the edited values.
#render_to('phones/edit.html')
def EditPhone(request, number):
p_number = PhoneTable.objects.get(number=number)
customer_list = list(Customer.objects.values('customer_id'))
JSON_customer_list = json.dumps(customer_list)
if not request.POST:
return dict(
form=PhoneForm(instance=p_number),
CallType=p_number.call_type,
number=number,
Customer=p_number.customer_id,
extension=p_number.profile.extension,
department=p_number.profile.department,
JSON_customer_list=JSON_customer_list
)
json_data = request.POST.get('json_blob')
obj = loads(json_data)
p_number.call_type = obj.get("callType")
p_number.customer_id = obj.get("selectedCustomer")
p_number.profile.extension = obj.get("editExtension")
p_number.profile.department = obj.get("servProfile")
p_number.save()
messages.success(request, 'Phone Number updated')
return redirect('phones:available_phones')
class PhoneForm(ModelForm):
class Meta:
model = PhoneTable
The html file:
{% block pagetitle %}Edit Phone Number: {{ number }}{% endblock %}
{% block content %}
<form id="phone_form" method="post">
{% csrf_token %}
<input type="hidden" id="json_blob" value="" />
<fieldset>
<div class="row">
<div class="span2">
<div class="pull-right">Call Type:</div>
</div>
<div class="span6">
<select data-bind="options: callTypes, value: callType"></select>
</div>
</div>
<div class="row">
<!-- ko if: callType() === "Direct" -->
<div class="span2">
<div class="pull-right">Extension:</div>
</div>
<div class="span6">
<input type="text" data-bind="value: editExtension" />
</div>
<!-- /ko -->
</div>
<div class="row">
<!-- ko if: callType() === "Sales" -->
<div class="span2">
<div class="pull-right">Customer:</div>
</div>
<div class="span6">
<select data-bind="options: customerDisplays, value: selectedCustomer"></select>
</div>
<!-- /ko -->
</div>
<div class="row">
<!-- ko if: callType() === "Service" -->
<div class="span2">
<div class="pull-right">Service Profile:</div>
</div>
<div class="span6">
<select data-bind="options: servProfiles, value: servProfile"></select>
</div>
<!-- /ko -->
</div>
<div class="form-actions">
<input type="submit" class='btn btn-primary' value="Update" data-bind="click: submitForm" />
<a class="btn" href="{% url phones:available_phones %}">Cancel</a>
</div>
{% endblock %}
{% block javascript_compress %}
<script type='text/javascript' src="{% static 'js/knockout/knockout.js' %}"></script>
<script type="text/javascript">
$(function(){
customerListFromServer = {{ JSON_customer_list|safe }};
var PhoneViewModel = function() {
var self = this;
customerList = [];
for (var key in customerListFromServer) {
customerList.push(customerListFromServer[key].customer_id);
}
self.callTypes = ko.observableArray(['Free', 'Direct', 'Sales', 'Service']);
self.callType = ko.observable("{{ CallType }}");
self.editExtension = ko.observable("");
self.servProfiles = ko.observableArray(["{{ extension }}", "{{ department }}"]);
self.servProfile = ko.observable();
self.customerDisplays = ko.observableArray(customerList);
self.selectedCustomer = ko.observable();
self.submitForm = function() {
$("#json_blob").val(ko.toJSON(self));
$("#phone_form").submit();
}
}
ko.applyBindings(new PhoneViewModel());
});
</script>
{% endblock %}

With knockout, i typically like to control as much as possible through the view model, including saving information back to the server. in your case, i would have the submit button execute a save function inside the view model like so:
html:
<input type="submit" class='btn btn-primary' value="Update" data-bind="click: submitForm" />
in your knockout view model, there are a couple of ways you can save the data:
self.submitForm = function () {
// save via postback
ko.utils.postJson('/EditPhone', ko.toJSON(self));
// save via ajax
$.ajax({
type: 'POST',
data: ko.toJSON(self),
url: '/EditPhone',
success: function () {
alert("saved");
},
error: function () {
alert("no worky");
}
})
}
unfortunately, i have no experience with django so im not sure exactly how you need to set that up in order to accept the json data coming back to the server

Related

passing a for loop value to bootstarp modal in 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

I'm using ajax to set up a view of uploaded data, but it works in first item only

I have to set up the user should be able to view the contact info of customer, For that I'm using ajax. the code is working but the problem is the ajax is only working in the first item, other buttons are not working what is the reason
another issue is when i hit the button again it showing data agin and agin how to control it
how to solve these two issues
views.py
def contact_details(request):
property_details = Property.objects.all()
seraializer = PropertySerializer(property_details, many=True)
data = seraializer.data
return JsonResponse(data, safe=False )
HTML page(including ajax)
{% if accomodations %}
{% for accomodation in accomodations %}
<div class="row">
<div class="col-sm-2 col-md-2"></div>
<div class="col-sm-4 col-md-4">
<img src="{{accomodation.images.url}}" class="img-responsive" style="width:100%">
</div>
<div class="col-sm-5 col-md-5">
<div class="caption">
<h3>{{ accomodation.headline }}</h3>
<div>
{{ accomodation.city }}
</div>
<div>
{{ accomodation.location }}
</div>
<div>
{{ accomodation.facilites }}
</div>
<div>
{{ accomodation.rent }}
</div>
<div>
{{ accomodation.owner }}
</div>
<div>
{{ accomodation.id }}
</div>
<button id="request-btn" name="property_id" class="btn btn-primary">Contact info:</button>
</form>
<div id=response></div>
</div>
</div>
</div>
<hr>
{% endfor %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#request-btn").click(function(){
$.ajax({
url: "{% URL 'contact_details' %}" ,
type: "GET",
dataType:"json",
success:
function(result){
$.each(result, function() {
html = "Email:" +this.email + "<br>" +"Mobile:" + this.mobile +"<hr>"
$("#response").append(html)
});
}
});
});
});
</script>
{% else %}
<h1>Not Found</h1>
{% endif %}
The problem is that you are using an id instead of a class, that's why only the first button works. Change it to class instead, then it should work. Try this:
<script type="text/javascript">
$(document).ready(function(){
$(".request-btn").click(function(){
var reference = this;
$.ajax({
url: "{% URL 'contact_details' %}" ,
type: "GET",
dataType:"json",
success:
function(result){
$.each(result, function() {
html = "Email:" +this.email + "<br>" +"Mobile:" + this.mobile +"<hr>"
$("#response").append(html)
});
}
});
});
});
</script>
I'm not sure what your second question is - could you please rephrase it or add details?

Styling errors in the form

There is the following form.
<form id="contact_form" class="get-in-touch-form" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h1 class="title {% if component.css_title_style %}{{ component.css_title_style }}{% endif %}">
{{ component.title }}
</h1>
<p class="subtitle {% if component.css_subtitle_style %}{{ component.css_subtitle_style }}{% endif %}">
{{ component.description }}
</p>
<div class="row">
<div class="col-sm-6">
<div class="input-wrapper">
{{ contact_form.name }}
</div>
<div class="input-wrapper">
{{ contact_form.email }}
</div>
<div class="input-wrapper">
{{ contact_form.phone }}
</div>
<div class="input-wrapper" style="position: relative;">
{{ contact_form.text }}
<img id="clip" src="{% static 'images/clip.png' %}" style="position: absolute; left: 95%; top: 5%;" onclick="document.querySelector('#id_file').click()">
</div>
<div class="input-wrapper" style="display: none">
{{ contact_form.file }}
</div>
<div class="input-wrapper">
<div class="col-md-5">
<div class="custom-checkbox">
{{ contact_form.nda }}
<label for="checkbox1">Send me an NDA</label>
</div>
</div>
<img src="/static/images/loader.svg" height="65" alt="Loading..." style="display: none;">
<input type="submit" value="Send" class="green-button">
</div>
</div>
<div class="col-sm-6">
<img src="{% static 'images/map_all.png' %}">
</div>
</div>
</form>
When I submit it and errors occur, text is displayed near the field that generates the error in its usual form. How can I style this text? For example, to highlight this field somehow?
I tried to do this through ajax, but it didn’t work. When I try to send a form containing errors to the server, I immediately get an error (for example, this field is required) and accordingly it does not reach any styling.
Now the error output looks like this.
How can you style it this way?
Add novalidate to form tag.
Add following block after your input fields.
<div class="contact_form_name" style="font-size:15pt; position: absolute; right: 30px; top: 20px; color: #FD7900; display: none"></div>
Add jquery + ajax code.
var frm = $('#contact_form');
frm.submit(function (e) {
e.preventDefault();
$.each($("div[class^='contact_form_']"), function(ind, value){
$(value).hide();
$(value).prev().css('border', 'none')
})
$.ajax({
type: frm.attr('method'),
url: '',
data: frm.serialize(),
success: function(data) {
console.log(data)
if (data.result == 'error'){
$.each(data.response, function(key, value) {
$('.contact_form_' + key).css('display', 'block')
$('.contact_form_' + key).prev().css("border", 'solid #FD7900')
$('.contact_form_' + key).text(value)
})
} else {
location.reload();
}
}
});
return false;
});
Add view function.
def post(self, request, *args, **kwargs):
contact_form = ContactFormForm(request.POST, request.FILES)
if contact_form.is_valid():
contact_form.save()
return JsonResponse({})
else:
response = {}
for k in contact_form.errors:
response[k] = contact_form.errors[k][0]
return JsonResponse({'response': response, 'result': 'error'})

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