Login form django using ajax - ajax

I have a login form of Django and i want to redirect user to the landing page if the password and the username is matching and to show an alert message if the login is failed and eventually show a validation error if the form is submitted empty.
When i submit the form using the right credentials the user is logged but no message is shown on the form, on the server log i have this message
09/May/2019 23:35:52] "POST /login/ HTTP/1.1" 200 7560
when i submit an empty form i have this message
Bad Request: /login/
[09/May/2019 23:36:53] "POST /login/ HTTP/1.1" 400 0
and when i submit a wrong credentials i have this message
[09/May/2019 23:37:36] "POST /login/ HTTP/1.1" 200 61
This is my html form
<div id="cd-login"> <!-- log in form -->
<div class="login_div"></div>
<form id="login_form" class="cd-form" action="{% url 'login' %}" method="POST">
{% csrf_token %}
<p class="fieldset">
<label class="image-replace cd-email" for="signin-email">E-mail</label>
<input class="full-width has-padding has-border" id="username" type="text" name="username" placeholder="E-mail">
<span class="cd-error-message">Error message here!</span>
</p>
<p class="fieldset">
<label class="image-replace cd-password" for="signin-password">Password</label>
<input class="full-width has-padding has-border" id="password" type="text" name="password" placeholder="Password">
Hide
<span class="cd-error-message">Error message here!</span>
</p>
<p class="fieldset">
<input class="full-width" type="submit" value="Login">
</p>
</form>
<p class="cd-form-bottom-message">Forgot your password?</p>
<!-- Close -->
</div> <!-- cd-login -->
This is my views.py
def ajax_login(request):
if request.method == 'POST':
username = request.POST.get('username', '').strip()
password = request.POST.get('password', '').strip()
if username and password:
# Test username/password combination
user = authenticate(username=username, password=password)
# Found a match
if user is not None:
# User is active
if user.is_active:
# Officially log the user in
return render(request, 'issueresolver/landing_page.html')
else:
data = {'success': False, 'error': 'User is not active'}
else:
data = {'success': False, 'error': 'Wrong username and/or password'}
return HttpResponse(json.dumps(data), content_type='application/json')
# Request method is not POST or one of username or password is missing
return HttpResponseBadRequest()
This my js file
$('form').on('submit', function(e) { e.preventDefault()
$.ajax({
type:"POST",
url: $(this).attr('action'),
data: $('#login_form').serialize(),
beforeSend: function (xhr, settings) {
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function(response){
/* here i am supposed to redirect user if login success and show an alert error message if the login is failed */
}
});
});
If any one can help me adjusting my code to be working as i described i will be more than grateful.

Finally i managed to solve the issue making some changes to the view.
This is the working code :
def ajax_login(request):
if request.method == 'POST':
username = request.POST.get('username', '').strip()
password = request.POST.get('password', '').strip()
response_data = {}
if username and password:
# Test username/password combination
user = authenticate(username=username, password=password)
# Found a match
if user is not None:
login(request, user)
response_data['result'] = 'Success!'
response_data['message'] = 'You"re logged in'
else:
response_data['result'] = 'Failed!'
response_data['message'] = 'Login Failed, Please check your credentials'
return HttpResponse(json.dumps(response_data), content_type="application/json")
return render(request, 'login.html')
ajax call
$('form').on('submit', function(e) { e.preventDefault()
$.ajax({
type:"POST",
url: $(this).attr('action'),
data: $('#login_form').serialize(),
beforeSend: function (xhr, settings) {
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function(response){
if (response['result'] == 'Success!')
window.location = '/';
else
alert(response['message']);
}
});
});

Related

how to request django post method values using ajax

I would like to implement simple django login method using ajax. when i want to retreive html input values using ajax in views, the request.post values are returning None. for ex print(request.POST.get('username')), it returns None.
my html form
<form action="" method="POST">{% csrf_token %}
<input type="text" name="username1" class="form-control rounded-1" id="id_username1" value="">
<input type="password" name="password1" class="form-control rounded-1" id="id_password1" value="">
</div>
<input type="button" id="btnlogin" value='Valider'>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js"></script>
<script>
var token = '{{csrf_token}}';
//login
$('#btnlogin').click(function(){
//alert("/login");
$.ajax({
url: "{% url 'login' %}",
headers:{'X-CSRFToken':token},
method:"POST",
data:{},
dataType: 'json',
success: function (data) {
if (data.status){
console.log('Success');
}
else{
console.log("login failed");
}
}
});
})
</script>
urls.py
path('login/', views.login_page, name='login'),
views.py
def login_page(request):
if request.method == 'POST':
username = request.POST.get('username1')
password = request.POST.get('password1')
print('password :',password)
#result "password : None"
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return JsonResponse({'status':True})
else:
return JsonResponse({'status':False})
context = {}
return render(request, 'core/login.html', context)
I do not know where is the error and how to fix this issue.
Thanx in advance.
i tried request.POST['password1']#result None
i changed to GET method. same issue.
I would like to collect forms input values in django view method using ajax

Django Ajax Auth Login

I'll want to redirect index page after logged in auth user. But don't know how coding the response to data. repeatedly redirect login page
views.py
#csrf_exempt
def Login(request):
if request.method == 'POST':
print("POST Method")
username = request.GET.get('username')
password = request.GET.get('password')
if username and password:
# Test username/password combination
user = authenticate(username=username, password=password)
# Found a match
if user is not None:
# User is active
if user.is_active:
# Officially log the user in
login(request, user)
data = {'success': True}
return render_to_response('index/index.html', data, RequestContext(request))
else:
data = {'success': False, 'error': 'User is not active'}
return render_to_response('accounts/login.html', data, RequestContext(request))
else:
data = {'success': False, 'error': 'Wrong username and/or password'}
print (data)
return HttpResponse(json.dumps(data), mimetype='application/json')
# Request method is not POST or one of username or password is missing
return render_to_response('accounts/login.html', RequestContext(request))
Ajax call : POST ( Is how to login the auth user )
$('#signIn_1').click(function (e) {
var username = $.trim($('#un_1').val());
var password = $.trim($('#pw_1').val());
$.ajax({
url : "{% 'login' %}",
type : 'POST',
data : {
'username' : username,
'password' : password
},
dataType : 'json',
success : function (data) {
if (data != null && data == "success") {
window.location = '/'
}
else {
$('#signIn_1').append(data);
alert(data);
}
}
})
});
})(jQuery);
login.html
<div class="form-main">
<form method="POST" action="{% url 'login' %}">{% csrf_token %}
<div class="form-group">
<input type="text" id="un_1" class="form-control" placeholder="username" required="required">
<input type="password" id="pw_1" class="form-control" placeholder="password" required="required">
</div>
<button id="signIn_1" type="submit" class="btn btn-block signin">Sign In</button>
</form>
<div id="message"></div>
</div>
Please use this for ajax response parsing..
$('#signIn_1').click(function (e) {
var username = $.trim($('#un_1').val());
var password = $.trim($('#pw_1').val());
$.ajax({
url : "{% 'login' %}",
type : 'POST',
data : {
'username' : username,
'password' : password
},
dataType : 'json',
success : function (data) {
if (data != null && data.success == true) {
window.location = '/'
}
else {
$('#signIn_1').append(data);
alert(data);
}
}
})
});
})(jQuery);

Django Jquery Form no AJAX request

After reading other questions on similar subject, I still do not understand what's wrong with this code.
I am testing a code that uses Jquery Form plugin. I added a call in the view to the template, to display it for 1st time so user can select file and upload. But it never sends the AJAX request, hence the code section in view is not executed. Although not shown here, jQuery library and the jQueryForm plugin are indeed being called.
Template:
<form id="uploadForm" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
{{ form.docfile }}
<span class="upload-message"></span>
<input type="submit" value="Upload" />
</form>
<script>
var message = '';
var options = {
type: "POST",
url: '/upload/file/',
error: function(response) {
message = '<span class="error">We\'re sorry, but something went wrong. Retry.</span>';
$('.upload-message').html(message);
$('fileInput').val('');
},
success: function(response) {
message = '<span class="' + response.status + '">' + response.result + '</span> ';
message = ( response.status == 'success' ) ? message + response.fileLink : message;
$('.upload-message').html(message);
$('fileInput').val('');
}
};
$('#uploadForm').ajaxSubmit(options);
</script>
View:
def upload(request):
response_data = {}
if request.method == 'POST':
if request.is_ajax:
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
upload = Upload(
upload=request.FILES['upload']
)
upload.name = request.FILES['upload'].name
upload.save()
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded:"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "We're sorry, but kk something went wrong. Please be sure that your file respects the upload conditions."
return HttpResponse(json.dumps(response_data), content_type='application/json')
else:
form = UploaderForm()
return render(request, 'upload.html', {'form': form})
It does call template correctly during first time, it displays buttons, it executes the script again but the form is not valid, so response_data is with error.
What am I missing?
Thanks, Ricardo
You can try using the example from API section instead, just look at the source code:
$('#uploadForm').ajaxForm({
beforeSubmit: function(a,f,o) {
$('.upload-message').html('Submitting...');
},
success: function(data) {
$('.upload-message').html('Done!');
}
});
and the HTML:
<form id="uploadForm" action="/upload/file/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
File: <input type="file" name="file">
{{ form.docfile }}
<span class="upload-message"></span>
<input type="submit" value="Upload" />
</form>
How it is supposed to be worked if there are no form data send in your script.
var options = {
type: "POST",
url: '/upload/file/',
data: new FormData(document.getElementById('uploadForm')),
processData: false,
contentType: false,
error: function(response) {
message = '<span class="error">We\'re sorry, but something went wrong. Retry.</span>';
$('.upload-message').html(message);
$('fileInput').val('');
},
success: function(response) {
message = '<span class="' + response.status + '">' + response.result + '</span> ';
message = ( response.status == 'success' ) ? message + response.fileLink : message;
$('.upload-message').html(message);
$('fileInput').val('');
}
};
You have at least one problem with you view - this:
if not request.GET:
return render(request, 'upload.html')
will prevent further execution when request.GET is empty which is the case when doing a POST request.

Frontend ajax POST call can't login to Django

I've spent several days to no avail and was wondering if anyone could help me? I am trying to use Django as a backend only with the ultimate goal of porting to a mobile application. I have a form and ajax call in the front end to a url/view in Django (REST API as well if that is relevant), but for some reason that I don't understand the call won't go through to log me in.
Relevant applications:
Django-Userena
Tastypie
Could anyone advise me in the right direction? Below is the code and thank you!
index.html
<script>
$(document).ready(function(){
`//login test`
`$('#login').submit(function(){`
$.ajax({
url: 'http://127.0.0.1:8000/accounts/signin/',
type: 'POST',
//data: loginString,
data: $('#login').serialize(),
success: function() {
alert('Test');
$('#datadisplay').append("<h2>It worked</h2>");
},
error: function(errorThrown){
alert('Error');
alert(errorThrown);
}
});
});
});
</script>
</head>
<body>
<div id="datadisplay"></div>
<input type="submit" id="getdata" value="Submit">
<div id="loginform">
<form name="login" id="login" action="">
<fieldset>
<label for="id_identification">Username</label>
<input type="text" name="identification" id="id_identification" size="30" value="" />
<br/>
<label for="id_password">Password</label>
<input type="password" name="password" id="id_password" size="30" value="" />
<br/>
<input type="submit" name="submit" class="loginbutton" value="Login" />
</fieldset>
</form>
</div>
api.py
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
include_resource_uri = False
allowed_methods = ['get', 'post']
def override_urls(self):
return [url(r"^(?P<resource_name>%s)/signin%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('signin'), name="api_signin"),
]
def signin(self, request, **kwargs):
self.method_check(request, allowed=['post'])
data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return self.create_response(request, {
'success': True
})
else:
return self.create_response(request, {
'success': False,
'reason': 'disabled',
}, HttpForbidden )
else:
return self.create_response(request, {
'success': False,
'reason': 'incorrect',
}, HttpUnauthorized )
$.ajax({
url: '/accounts/signin/',
type: 'POST',
data: {
csrfmiddlewaretoken: '{{csrf_token}}',
//other variables
},
success: function() {
alert('Test');
$('#datadisplay').append("<h2>It worked</h2>");
},
error: function(errorThrown){
alert('Error');
alert(errorThrown);
}
});

Ajax Contact form validation and submit

I'm trying to make a HTML contact form. Here's my code
`Get in Touch
<p class="success-sending-message">Thank you, your message has been sent!</p>
<p class="error-sending-message">There has been an error, please try again.</p>
<div id="contact-form">
<form action="" id="contactForm" class="styled" method="post">
<label for="contact_name">Name</label>
<input type="text" tabindex="3" id="contact_name" name="contact_name" value="" class="requiredField textbox" />
<label for="contact_email">Email</label>
<input type="text" tabindex="4" id="contact_email" name="contact_email" value="" class="requiredField email textbox" />
<label for="contact_subject">Subject</label>
<input type="text" tabindex="5" id="contact_subject" name="contact_subject" value="" class="requiredField textbox" />
<label for="contact_message">Your Message</label>
<div class="textarea-wrap">
<textarea cols="65" rows="9" tabindex="6" id="contact_message" name="contact_message" class="requiredField"></textarea>
</div>
<div class="form-section">
<button class="button" tabindex="7" type="submit" id="born-submit" name="born-submit">Send Message</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
<span class="sending-message"><img src="css/images/loading-light.gif" /> Sending...</span>
</div>
</form>
</div>`
And here's my validation script
$(window).load(function() {
/* Ajax Contact form validation and submit */
jQuery('form#contactForm').submit(function() {
jQuery(this).find('.error').remove();
var hasError = false;
jQuery(this).find('.requiredField').each(function() {
if(jQuery.trim(jQuery(this).val()) == '') {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
hasError = true;
} else if(jQuery(this).hasClass('email')) {
var emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!emailReg.test(jQuery.trim(jQuery(this).val()))) {
jQuery(this).addClass('input-error');
hasError = true;
}
}
});
if(!hasError) {
jQuery(this).find('#born-submit').fadeOut('normal', function() {
jQuery(this).parent().parent().find('.sending-message').show('normal');
});
var formInput = jQuery(this).serialize();
var contactForm = jQuery(this);
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
}
return false;
});
jQuery('.requiredField').blur(function() {
if(jQuery.trim(jQuery(this).val()) != '' && !jQuery(this).hasClass('email')) {
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
} else {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
}
});
jQuery('.email').blur(function() {
emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(emailReg.test(jQuery.trim(jQuery(this).val())) && jQuery(this).val() != '') {
jQuery(this).removeClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
});
jQuery('.requiredField, .email').focus(function(){
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
});
});
My form is working properly, After filling details It is showing me "Thank you, your message has been sent!" But where is this message going, I don't have any of the process.php file and all. I want that email should be send to my email id.
Bonjour ... Look in the firebug or chrome developper tools console to see the post trace.
In your php file, you can put echos or var_dump to be sure all it's ok.
Another thing ... the form action is empty.
Currently there's no where it is going. Give where it needs to go in the action="" attribute of the <form>. And also, in the actioned URL, typically, a PHP file, give this code:
<?php
if (count($_POST))
{
$name = $_POST["contact_name"];
$email = $_POST["contact_email"];
$subject = $_POST["contact_subject"];
$message = $_POST["contact_message"];
$mail = "Name: $name\nEmail: $email\nSubject: $subject\nMessage: $message";
if (mail("mymail#domain.com", "New Mail from Contact Form", $mail))
die ("OK");
else
die ("Fail");
}
?>
Also, you need to make a small correction in your JavaScript AJAX Call. Replace this way:
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
if (data == "OK")
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
else
alert ("Message not sent!");
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
Test if your server supports SMTP through PHP Script
Create a small file, which has this content, say mail.php:
<?php
var_dump(mail("yourmail#gmail.com", "Testing Message", "This mail was sent from PHP Script."));
?>
And try to access the file and see what you are getting. Please update the same in your question.

Resources