how to request django post method values using ajax - 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

Related

After form submit redirect without refresh using Ajax in laravel 8

I am developing multi Step Form Submit without refresh. collect the data from 1st step 2nd step collect some date, 3rd step collect some date & finally submit data in the database. Can you tell me how to fix this.
My blade template.
<form id="post-form" method="post" action="javascript:void(0)">
#csrf
<div>
<input class="form-input" type="text" id="ptitle" name="ptitle" required="required"
placeholder="What do you want to achieve?">
</div>
<button type="text" id="send_form" class="btn-continue">Continue</button>
</div>
</form>
Ajax Script
$(document).ready(function() {
$("#send_form").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var ptitle = $('#ptitle').val();
$.ajax({
url: "{{route('create.setp2') }}",
method:'POST',
data: {_token:_token,ptitle:ptitle},
success: function(data) {
alert('data.success');
}
});
});
Web.php router
Route::post('/setp2', [Abedoncontroller::class, 'funcsetp1'])->name('create.setp2');
Controller method
public function funcsetp1(Request $request) {
$postdata=$request->input('ptitle');
return response()->json('themes.abedon.pages.create-step-2');
}

Login form django using 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']);
}
});
});

Page still refreshing while using ajax with django

I'm using my own custom form. Which looks like:
{%extends 'base_template.html'%}
{%block title%}
<title> Simple Ajax Demo </title>
{%endblock%}
{%block javascript%}
<script>
$(document).ready(function(){
$("#formi").submit(function(event){
$.ajax({
type:"POST",
url:"{% url 'haha:ajax' %}",
data: {
username : $('#username').val(),
password : $('#password').val(),
csrfmiddlewaretoken: {% csrf_token %},
},
success: function(data){
alert('asdas');
},
});
});
});
</script>
{%endblock%}
{%block content%}
<div>
<form method="post" id="formi">
{%csrf_token%}
Username:<input type="text" id="username"><br>
Password:<input type="text" id="password"><br>
<button type="submit">Click Me</button>
</form>
</div>
{%endblock%}
I've got two input fields with name password and username, to be saved to the table User.
View.py
def ajax(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
Users.objects.create(username=username, password=password)
return render(request,'core/ajax.html')
I've tried with the GET method too. But still the page gets refreshed. Also tried firing the Ajax call while clicking the button, but it says something like multiple-dict value error. Also tried with
username = request.POST.get('username')
password = request.POST.get('password')
Edit onSubmit event as
$("#formi").submit(function(event){
event.preventDefault();
$.ajax({
/* you have type here change it to method */
method:"POST",
url:"{% url 'haha:ajax' %}",
data: {
username : $('#username').val(),
password : $('#password').val(),
csrfmiddlewaretoken: {% csrf_token %},
},
success: function(data){
alert('asdas');
},
});
}
It is the default behaviour of onSubmit to refresh the page whenever we submit the form. By event.preventDefault(); we are pausing that default behaviour.
Just modified the jquery code, works well!! Here's a code:
{%extends 'base_template.html'%}
{%block title%}
<title> Simple Ajax Demo </title>
{%endblock%}
{%block javascript%}
<script>
$(document).on('submit','#formi',function(event){
event.preventDefault();
$.ajax({
method:"POST",
url:"{%url 'haha:ajax'%}",
data: {
username : $('#username').val(),
password : $('#password').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success: function(data){
alert('asasd');
},
});
});
</script>
{%endblock%}
{%block content%}
<div>
<form id="formi" method="post">
{%csrf_token%}
Username:<input type="text" name="username" id="username"><br><br>
Password:<input type="text" name="password" id="password"><br><br>
<input type="submit" value="Click Me"><br>
</form>
</div>
{%endblock%}
But i don't understand why is document.on('submit','#formi'){} is working?

Need e.preventDefault to save JWT into localStorage

For some reason, when trying to login I need to have e.preventDefault (prevent page reloading) in order to save my JWT into local storage with an AJAX call. So when i have this:
handleLogin(e) {
//Without e.preventDefault, the jwt token is not save -> cannot access api
e.preventDefault();
const email = $('#email').val()
const password = $('#password').val()
const request = {"auth": {
"email": email,
"password": password
}}
$.ajax({
url: "http://localhost:5000/api/user_token",
type: "POST",
data: request,
dataType: "json",
success: function (result){
console.log(result.jwt)
localStorage.setItem("jwt", result.jwt)
}
})
}
Here is my simple form
render(){
return(
<div>
<form>
<input
name="email"
id="email"
type="email"
/>
<input
name="password"
id="password"
type="password"
/>
<button
onClick={this.handleLogin}
>Login</button>
<button
onClick={this.handleLogout}
>Logout</button>
</form>
<button onClick={this.getUsers}>Get Users</button>
{
this.state.users
}
</div>
)
}
I want my page to reload/go to a different page after submitting a successful login. On create-react-app and using a Rails API 5
In your case, you can try this:
success: function (result){
console.log(result.jwt)
localStorage.setItem("jwt", result.jwt)
//page reload
window.location.reload(true);
// or route to another page
window.location.href = 'foo'; // any route
}
But I would recommend to use react router so your app will never loose it's state.
If you have any query, you can ask.

django.utils.datastructures.MultiValueDictKeyError DJANGO

I have a form. When I post the form without using ajax, it works well. But when I use the ajax, I have an error like this;
django.utils.datastructures.MultiValueDictKeyError:
My codes are below that without using ajax. It works.
HTML Form:
<form id="add_form" action="/adding/" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input type="file" name="picture">
<button type="submit" id="send_form" value="ok">Ok</button>
</form>
My views.py codes are:
if request.method == "POST":
title = request.POST.get('title')
pic = request.FILES['picture']
query = Images_Table(title=title, pic=pic)
query.save()
My model codes are:
class Images_Table(models.Model):
title = models.CharField(max_length=70, blank=True, null=True)
pic = models.FileField(upload_to='images_folder', blank=True, null=True)
Until here; everythings are normal, codes works. When I use ajax, I have an error. My HTML Form:
<form id="add_form" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input type="file" name="picture">
<button id="send_form" value="ok">Ok</button>
</form>
My ajax codes are:
$("#send_form").click(function(){
$.ajax({
url: '/adding/',
method:'post',
data: $("#add_form").serialize(),
headers: '{{ csrf_token }}',
success : function(){
alert('Success posted!');
}
});
});
Error code is below;
django.utils.datastructures.MultiValueDictKeyError: "'picture'"
I solved the problem by changing ajax.
$("#send_form").click(function(){
var file_data = $('#picture').prop('files')[0];
var form_data = new FormData($('form').get(0));
form_data.append('file', file_data);
$.ajax({
url: '/adding/',
method:'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
headers: {'X-CSRFToken': '{{ csrf_token }}'},
success : function(){
alert('Success posted!');
}
});
});

Resources