Django and Ajax refreshing a div - django

I am very new to JS/Ajax and a relative novice to Django. I am testing to see how I can get information back and forth from an Ajax call to my view, and back to Ajax to replace a header string as a simple test.
I can receive information back to my view (h1, which is "AJAX TEST"). What I can't seem to get is the h2text to change to "HEADER CHANGED".
Any help is appreciated as I don't know if it's my Django return function or my Ajax function.
Here is my ajax_test.html:
<div class="content">
<div class="center">
<h1 id="h1">AJAX TEST</h1>
<div>
<button id="btn">PRESS ME</button>
</div>
</div>
<div id="update_div">
{% include "ProdPlat/ajax_test_div.html" %}
</div>
</div>
<script type="text/javascript" src="{% static 'ProdPlat\js\ajax_test.js' %}"></script>
{% endblock %}
My ajax_test_div.html (which I'm trying to refresh):
<div class="content">
<div class="center">
<h2 id="h2">{{h2text.h2text}}</h2>
</div>
</div>
My views_test.py:
def test_ajax(request):
h2text = {'h2text': "INITIAL HEADER"}
if request.method == 'POST':
logger.debug('POST request')
text = request.POST.get('text')
logger.debug('text = {}'.format(text))
h2text = "HEADER CHANGED"
dict = {
'h2text': h2text,
}
# return JsonResponse(dict)
# return render(request, 'ProdPlat/ajax_test_div.html', {'h2text': h2text})
return render_to_response('ProdPlat/ajax_test_div.html', dict)
return render(request, 'ProdPlat/ajax_test.html', {'h2text': h2text})
And finally my Ajax call:
$(document).on('click', 'button', function(){
var csrftoken = getCookie('csrftoken');
console.log('Button Clicked!');
var text = $('h1').text()
console.log('h1 text = ' + text);
$.ajax({
type : 'POST',
url : "/ProdPlat/Ajax_Test/",
dataType: 'json',
data: {'text' : text,
'csrfmiddlewaretoken': csrftoken,
},
success: function(data) {
console.log('data = ' + data);
console.log('data.h2text = ' + data.h2text);
$('#update_div').load(' #update_div')
console.log('Success!');
},
failure: function(data) {
console.log('Failed!');
console.log('data = ' + data);
},
})
})

Related

Not able to retrieve variable in template in Django ajax call

I am trying retrieve counter value passed from view in the html template .It is coming as None, however in the view print and in ajax success log value it is coming correct.
JS ajax func
$(".pos").click(function(){
counter=counter+1;
$(".add").html('add counter '+counter);
$.ajax(
{ url :'page',
type :'get' ,
data:{
quantity: counter
},
success:function(response){
console.log(response);
}
}
);
My view
def page(request):
counter=request.GET.get('quantity')
print(counter) ## this is printing fine
return render(request,'page.html',{'counter':counter})
html template
<body>
{{counter}}
<button class="btn neg" name="neg-btn">-</button>
<button class="btn add" name="add-btn" >add to box</button>
<button class="btn pos" id="test" name="pos-btn">+</button>
</body>
getting this counter as None
Usually you would have two views, one to render the template and another for your ajax request. This helps to keep your code more organized and have functions do exactly one task as most of the its described in its naming.
One important thing that is happening in your view, is that you are returning the HTML generated by the render API and not the counter value. Of course, there are many ways to do this correctly, but here is one possible solution:
page.html
{% extends 'base.html'%}
{% block content %}
<body>
<div id="counter">
{{counter}}
</div>
<button class="btn neg" id="neg" name="neg-btn">-</button>
<button class="btn add" id="add" name="add-btn" >add to box</button>
<button class="btn pos" id="pos" name="pos-btn">+</button>
</body>
{% endblock content %}
{% block script %}
<script>
let counter = parseInt("{{counter}}");
let page_url = "{% url 'core:page' %}";
console.log(page_url)
$( "#pos" ).click(function() {
counter += 1;
$( "#counter" ).replaceWith(`<div id="counter">${counter}</div>`);
});
$( "#neg" ).click(function() {
counter -= 1;
$( "#counter" ).replaceWith(`<div id="counter">${counter}</div>`);
});
$( "#add" ).click(function() {
$.ajax({
url :page_url,
type :'post' ,
data:
{
counter: counter,
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success:function(response){
console.log(response);
}
});
});
</script>
{% endblock script %}
views.py
from django.http import JsonResponse
def page(request):
counter = 0
if request.method == 'POST':
counter = int(request.POST.get('counter'))
print(counter)
return JsonResponse({'counter': counter})
return render(request,'page.html',{'counter':counter})

I want to get e-mail authentication

An authentication number function that generates eight random characters was implemented.
i inputted username, and mail. because i want to write searching password html and request it at view with Ajax.
When I enter my username and email, I want the authentication number to be sent to the email. At the same time, the code created in ajax should show the authentication number window.
but, it happened nothing.
what should i do...?
help me!
error is Uncaught SyntaxError: Unexpected token '<' WHAT'S THAT..?
First of all, I corrected the white page. I missed it. '>'
#html
{% load static %}
<!DOCTYPE html>
<html lang="KO">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="{% static 'users/css/recovery_pw.css' %}" rel="stylesheet">
<link href="{% static 'users/css/default.css' %}" rel="stylesheet">
<script
src="https://kit.fontawesome.com/96379a54a1.js"
crossorigin="anonymous"
></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="{% static 'users/js/recovery_pw.js' %}" </script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
{% block content %}
<form method="get" enctype="multipart/form-data">
<div class="container">
<div class="inner-box">
<div class="title">
<h1>비밀번호 찾기</h1>
</div>
<div class="input-box">
<div class="id">
<input type="email" placeholder="등록하신 메일로 인증번호가 발송됩니다." name="email" maxlenth="20" autocomplete="off" value="{{ form.email.value|default_if_none:'' }}" required />
</div>
<div class="password">
<input type="username" placeholder="아이디를 입력하세요" name="username" maxlength="20" value="{{ form.username.value|default_if_none:'' }}" required />
</div>
</div>
<div class="btn">
<div class="btn-white" id="btn_white"><button type="submit">임시 비밀번호 발송</button></div>
</div>
<div class="loading-box">
<div id="loading"></div>
</div>
</div>
</form>
{% endblock %}
</body>
</html>
#users/js/recovery_pw.js
$(document).ready(function () {
$('#find_pw').click(function () {
$('#loading').replaceWith('<div id="loading_end" class="loading"></div>')
// 걍 임의로 만든것 같음
var name = $("#pw_form_name").val();
var email = $("#pw_form_email").val();
$.ajax({
type: "POST",
url: "/users/recovery/pw/find/",
dataType: "json",
data: {
'name': name,
'email': email,
'csrfmiddlewaretoken': '{{csrf_token}}',
},
success: function (response) {
// loading_end 이걸 지움
$('#loading_end').remove()
alert('회원님의 이메일로 인증코드를 발송하였습니다.');
// 나는 이메일전송버튼이지
$('#btn_white').remove()
$('#result_pw').replaceWith(
'<hr><div class="row justify-content-md-center"><form class="form-inline" style="margin-bottom:-15px; margin-top:-10px;"><div class="md-form md-outline"><label for="input_auth_num">인증번호 입력 (<span id="timeset"></span>)</label><input type="text" id="input_auth_num" class="form-control mx-sm-2" autofocus/></div></form>' +
'<button type="submit" name="auth_confirm" id="id_auth_confirm" class="btn btn-red" style="opacity: 90%; height:30%; margin-top:10px; font-size: 12px;"><i class="fas fa-check"></i> 인증확인</button></div><hr>'
)
function countdown(elementName, minutes, seconds) {
var elementName, endTime, hours, mins, msLeft, time;
function twoDigits(n) {
return (n <= 9 ? "0" + n : n);
}
function updateTimer() {
msLeft = endTime - (+new Date);
if (msLeft < 1000) {
alert("인증시간이 초과되었습니다.");
$("" + elementName).remove();
cert_ok = false;
certificationNum = false;
location.href = "{% url 'recovery_pw' %}"
} else {
time = new Date(msLeft);
hours = time.getUTCHours();
mins = time.getUTCMinutes();
$("" + elementName).html((hours ? hours + ':' + twoDigits(mins) : twoDigits(mins))
+ ':' + twoDigits(time.getUTCSeconds()));
setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
}
}
endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
updateTimer();
}
countdown("#timeset", 5, 0);
var user = response.result
$(document).ready(function () {
$('#id_auth_confirm').click(function () {
var input_auth_num = $("#input_auth_num").val();
$.ajax({
type: "POST",
url: "/users/recovery/pw/auth/",
dataType: "json",
data: {
'input_auth_num': input_auth_num,
'csrfmiddlewaretoken': '{{csrf_token}}',
},
success: function (response) {
location.href = "{% url 'recovery_pw_reset' %}";
},
error: function () {
if ($('#input_auth_num').val() == "") {
alert('회원님의 이메일로 전송된 인증번호를 입력해주세요.');
} else {
alert('인증번호가 일치하지 않습니다.');
}
},
});
})
})
},
error: function () {
$('#loading_end').remove()
if (username == "" || email == "") {
alert('이름, 이메일을 모두 입력해주세요.');
} else {
alert('입력하신 정보가 일치하지 않거나 존재하지 않습니다.');
}
},
});
})
});
#views.py
class RecoveryPwView(View):
template_name = 'users/recovery_pw.html'
recovery_pw = RecoveryPwForm
def get(self, request):
if request.method=='GET':
form = self.recovery_pw(None)
return render(request, self.template_name, { 'form':form, })
def ajax_find_pw_view(request):
username = request.POST.get('username')
email = request.POST.get('email')
target_user = User.objects.get(username=username, email=email)
if target_user:
auth_num = email_auth_num()
target_user.auth = auth_num
target_user.save()
send_mail(
'this is email verify',
['email'],
html=render_to_string('users/recovery_email.html', {
'auth_num': auth_num,
}),
)
return HttpResponse(json.dumps({"result": target_user.username}, cls=DjangoJSONEncoder), content_type = "application/json")
#urls.py
path('recovery/pw/', RecoveryPwView.as_view(), name='recovery_pw'),
path('recovery/pw/find/', views.ajax_find_pw_view, name='ajax_pw'),
path('recovery/pw/auth/', views.auth_confirm_view, name='recovery_auth'),
path('recovery/pw/reset/', views.auth_pw_reset_view, name='recovery_pw_reset'),
form
class RecoveryPwForm(forms.Form):
username = forms.CharField(label='id')
email = forms.EmailField(label='email')
class Meta:
fields = ['username', 'email']
class CustomSetPasswordForm(forms.Form):
new_password = forms.CharField(
max_length=16,
min_length=6,
label=_('새 비밀번호')
)
confirm_password = forms.CharField(
max_length=16,
min_length=6,
label=_('새 비밀번호 확인')
)
since you are using the get method into the View model, you can use it directly without checking by method and that is what that function does for ease
Note:-
now you handle the request method by get method which you can't use csrf_token into your form
now the problem is that, you are trying to use get method to send data then, you want to get this data in ajax by Post method which you won't receive any data of course in addition to, that you are trying to execute the separate function in the view which cause a problem where the function will never execute because the form doesn't know where should it send the data in after the request is created.
so, now you can remove the additional function you use and try to use and include what you want in the one view to prevent the confusion so, follow the solution like so:
class RecoveryPwView(View):
template_name = 'users/recovery_pw.html'
recovery_pw = RecoveryPwForm
def get(self, request):
form = self.recovery_pw(None)
return render(request, self.template_name, { 'form':form})
def post(self, request):
form = self.recovery_pw(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
target_user = User.objects.get(username=username, email=email)
# do send email here
# return the render that you want to finish by post method here
html
<form method="post">
{% csrf_token %}
<div class="container">
<div class="inner-box">
<div class="title">
<h1>비밀번호 찾기</h1>
</div>
<div class="input-box">
{% comment %} <div class="id">
<input type="email" placeholder="등록하신 메일로 인증번호가 발송됩니다." name="email" maxlenth="20" autocomplete="off" value="{{ form.email.value|default_if_none:'' }}" required />
</div>
<div class="username">
<input type="username" placeholder="아이디를 입력하세요" name="username" maxlength="20" value="{{ form.username.value|default_if_none:'' }}" required />
</div> {% endcomment %}
{% for field in form %}
<label>{{ field.label }}</label>
<div>{{ field }}</div>
{% endfor %}
</div>
<div class="btn">
<div class="btn-white" id="btn_white"><button type="submit">임시 비밀번호 발송</button></div>
</div>
<div class="loading-box">
<div id="loading"></div>
</div>
</div>
</form>
Now this solution is not completed, because I'm not sure from understanding exactly what you want to do but at least you can see that there's something new happen for your problem to find the min problem, the issue now will come from Ajax just let me know what you are facing after that

Django - POST method not working for those forms created within a FOR loop in template

I'm using a for loop in a template to create multiple forms with method="post" that work with Ajax. But only the form for the first element of items_list works fine, the rest do not work at all showing error 405 0 Method Not Allowed. I think they all should work the same way. And just wondering if this issue was caused by a for loop or something else.
cart_items.html:
<script>
$(document).ready(function () {
$("#remove").click(function (event) {
event.preventDefault();
$.ajax({
url: '{% url "cart:remove_from_cart" %}',
type: "POST",
dataType: 'json',
data: {bookID: $('#idInput').val()},
success: function (response_data) {
alert('works fine')
},
error: function (response_data) {
console.log('error occurred');
}
});
});
});
</script>
{% for book in items_list %}
<div class="items">
<p id="title"> {{ book.book.title }}, quantity: {{ book.quantity }} </p>
<form method="post">
{% csrf_token %}
<input id="idInput" value="{{ book.book.id }}" >
<button id="remove" type="submit"> Remove</button>
</form>
</div>
{% endfor %}
The code in the function body below is just for testing. Once the first form works, I guess the problem was not caused by the function view.
cart/views.py:
#csrf_exempt
def remove_books(request):
cart = Cart.objects.get(user=request.user)
if request.method == 'POST':
passed_id = request.POST['bookID']
secured_id = int(passed_id)
response_data = {
'quantity': secured_id
}
return JsonResponse(response_data)
<script>
$(document).ready(function () {
$(".remove").click(function (event) {
// event.preventDefault(); // don't think it should be required with button type=button
var book_id = $(this).parent().find('.idInput').val(); // find correct input box.
var csrf = $('input[name="csrfmiddlewaretoken"]').val(); // get csrf token in variable.
// there are multiple ways to get csrf token, I personally like this ^^, see https://docs.djangoproject.com/en/2.1/ref/csrf/#ajax for more
$.ajax({
url: '{% url "cart:remove_from_cart" %}',
type: "POST",
dataType: 'json',
data: {
bookID: book_id,
csrfmiddlewaretoken: csrf // add csrf token to post data
},
success: function (response_data) {
alert('works fine')
},
error: function (response_data) {
console.log('error occurred');
}
});
});
});
</script>
{% csrf_token %} <!-- It will render a hidden input field with csrf token in it. Keep it outside for loop but in html. No need to render exactly same element multiple times. -->
{% for book in items_list %}
<div class="items">
<p class="title"> {{ book.book.title }}, quantity: {{ book.quantity }} </p>
<form method="post">
<input class="idInput" value="{{ book.book.id }}" > <!-- use class not id -->
<button class="remove" type="button"> Remove</button> <!-- you can use button type=button to avoid form submit and hence avoid event.preventDefault(); in js -->
</form>
</div>
{% endfor %}

Does Making an AJAX call make a DJANGO form Invalid?

I make an ajax call to my server using the change event on a select widget. Does this cause the Django Form to be invalid? Here is an example of the code.
JAVASCRIPT
<form class="form-horizontal" action="{% url 'accountSelections' %}" method="post">
{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-md-4">
{{ account_selection_form|crispy }}
<input class="btn btn-primary" id="button" type="Submit" value="Next >>">
</div>
<div class="col-md-4">
</div>
<div class="col-md-4">
<div id="grid"></div>
</div>
</div>
</div>
</form>`
$( document ).ready(function() {
$("#id_excludeClassification").SumoSelect();
var token = $('input[name="csrfmiddlewaretoken"]').prop('value');
$( "#id_acctFilterName" ).change(function() {
var data = "";
$.ajax({
type:"GET",
url : "../filter",
data : "id="+$(this).val(),
csrfmiddlewaretoken: token,
success : function(response) {
$("#grid").kendoGrid({
data: response,
height: 550,
groupable: true,
sortable: true,
columns: [
{
field: "acctCd",
title: "Code"
}, {
field: "shortName",
title: "Account Name"
}]
});
var grid = $("#grid").data("kendoGrid");
dataSource = new kendo.data.DataSource({
data: response
});
grid.dataSource = dataSource;
dataSource.read();
grid.refresh();
data = response;
return response;
},
error: function() {
alert('Error occured');
}
});
});
});
Does a form submit after cause this to make the form invalid?
My understanding is that you can submit multiple times with the same CSRF token, so it shouldn't be a problem.
you put your csrfmiddlewaretoken variable out data object that you send to your server then it can't work.
Here is what you have to do :
data : {
id : $(this).val(),
csrfmiddlewaretoken: token,
}

Having trouble submitting my form using Dojo

I am using Django 1.5 and Dojo 1.8. I am trying to get Dojo to submit a form back to a Django view when I click a button.
Here is my Django view:
def report(request, report_id, report_url=None, template='report_parameters.html'):
if request.method == 'POST':
form = ReportParametersForm(request.POST)
if form.is_valid():
report_params = form.save()
html = "Success!"
return HttpResponse(html)
else:
form = ReportParametersForm()
return render(request,template, {
'form': form,
'report_url': report_url,
'report_id': report_id,
})
Here is the html page:
<div id="report_body">
<form data-dojo-type="dijit/form/Form" id="parameters_form" data-dojo-id="parameters_form">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<p><button id="submit_parameters" dojoType="dijit.form.Button" type="submit">Submit</button></p>
</form>
</div>
<script type="dojo/on" data-dojo-event="submit" data-dojo-args="e">
e.preventDefault();
require(["dojo/dom", "dojo/request", "dojo/dom-form"], function(dom, request, domForm){
on(dom.byId("submit_parameters"), "click", function() {
console.log("Dojo Post");
request.xhr("/report_parameters/report_id/report_url/", {
method: "post",
handleAs: "json",
data: domForm.toJson("parameters_form"),
}).then(
function(response){
alert(response);
dom.byId("report_body").innerHTML = "Report!";
},
function(error){
dom.byId("report_body").innerHTML = "<div class=\"error\">"+error+"<div>";
}
);
});
});
</script>
When I click the Submit button, I want to send a POST request to the url passing the data I have in my form. However, right now when I click Submit, the page reloads with a url looking something like this: /?csrfmiddlewaretoken=Y9gaNMFRWZNXMbJ2L3Ev7A5iKPGTuWeF&param_1=0&param2=0/report_parameters/report_id/report_url/.
I don't see the Dojo Post that should be appearing in my console.
How do I get my form to submit?
This fiddle seems to do what you want.
The major differences seem to be:
The <form> is actually a <div>. The Dojo documentation for Form links to reasons why this is done for IE.
All the related event script is inside the form <div>.
Remove the on(dom.byId("submit_parameters")... code, as there's already a declarative submit event handler.
HTML code:
<div id="report_body"></div>
<div data-dojo-type="dijit/form/Form" id="parameters_form" data-dojo-id="parameters_form" encType="multipart/form-data" action="" method="">
<input name="dummy" value="dummy">
<script type="dojo/on" data-dojo-event="submit" data-dojo-args="e">
console.log("submit");
e.preventDefault();
require(["dojo/dom", "dojo/request/xhr", "dojo/dom-form"], function(dom, xhr, domForm) {
console.log("Dojo Post");
var url = "/report_parameters/report_id/report_url/";
var data = domForm.toJson("parameters_form");
// overwrite url and data for jsfiddle
url = "/echo/json/";
data = {
json: data
};
xhr(url, {
method: "post",
handleAs: "json",
data: data,
}).then(function(response) {
alert(JSON.stringify(response, null, 2));
dom.byId("report_body").innerHTML = "Report!";
}, function(error) {
dom.byId("report_body").innerHTML = "<div class=\"error\">" + error + "<div>";
});
});
</script>
<button data-dojo-type="dijit/form/Button" id="submit_button" type="submit" name="submitButton" value="Submit">Submit</button>
</div>
JS code:
require(["dojo/parser", "dijit/registry", "dijit/form/Form", "dijit/form/Button", "dijit/form/ValidationTextBox", "dijit/form/DateTextBox", "dojo/domReady!"], function (parser, registry) {
parser.parse().then(function () {
console.log("parsed");
console.log(registry.byId("parameters_form"));
console.log(registry.byId("submit_button"));
});
});
I had to modify the above slightly. This is what eventually worked for me:
<div id="report_body"></div>
<form data-dojo-type="dijit/form/Form" id="parameters_form" data-dojo-id="parameters_form" encType="multipart/form-data" action="" method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<script type="dojo/on" data-dojo-event="submit" data-dojo-args="e">
e.preventDefault();
require(["dojo/dom", "dojo/request/xhr", "dojo/dom-form"], function(dom, xhr, domForm){
var url = "/report_parameters/report_id/report_url/"
var data = domForm.toObject("parameters_form")
xhr(url, {
method: "post",
data: data,
}).then(
function(response){
alert(response);
dom.byId("report_body").innerHTML = "Report!";
},
function(error){
dom.byId("report_body").innerHTML = error;
}
);
});
</script>
<p><button id="submit_parameters" dojoType="dijit/form/Button" type="submit" name="submitButton" value="Submit">Submit</button></p>
</form>
Using either the <div> or <form> tags to wrap the whole thing worked for me.