The render do not render to the template - python

In the admin index page I bind a id to a button, and use jquery ajax to request a logout event:
$("#logout").click(function(){
$.ajax({
url:'/logout/',
type:'POST'
})
})
And in the frontend/views.py:
def logout(request):
if request.method == 'POST':
request.session['username'] = None
request.session['is_login'] = False
import app_admin.views as app_admin_views
app_admin_views.conn = None # clean the connection
print ('before logout')
return render(request,'frontend/login.html')
In the Terminal have printed the 'before logout', but the page do not render to the frontend/login.html, and I also tried use redirect, all failure.

In logout view function, return a redirect
return redirect('login-or-something')
In javascript AJAX request handle the redirect response,
function handleSuccess(data, textStatus, jqXHR) {
location.href = jqXHR.getResponseHeader('Location');
}
function handleError(jqXHR, textStatus, errorThrown) {
console.log(errorThrown); // send to some error log collectors
}
$.ajax({
url:'/logout/',
type:'POST'
success: handleSuccess,
error: handleErr
});

Related

Django - "return render(...)" doesn't work in a view that interacts with an ajax request

I want to solve this task: I click a button on the first page and after that my view creates a chat room and redirects me to the chat page.
I decided to use ajax request for this task, but I have a problem, my view works until line return render(request, 'chat/chatroom.html'), the chat room is created, but the chat/chatroom.html page doesn't open, I don't understand why. I have no errors, the return render(request, 'chat/chatroom.html') line does nothing.
My code:
html
<button type="submit" id="chat-button" value="{{advertisement.author.id}}">Write to the author</button>
<script>
$(document).on('click', '#chat-button', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "main_app:create-chat" %}',
data: {
send_to_id: $('#chat-button').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
},
error: function (xhr, errmsg, err) {
}
});
})
</script>
views.py
from django.contrib.auth import get_user_model
from django.shortcuts import render, redirect, get_object_or_404
from django.db.models import Q
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from chat.models import Thread
User = get_user_model()
#method_decorator(csrf_exempt, name='dispatch')
class CreateChat(View):
def post(self, request):
send_to_id = int(request.POST.get('send_to_id'))
send_to = User.objects.get(id=send_to_id)
auth_user = request.user
final_q = Q(Q(first_person=send_to) & Q(second_person=auth_user)) \
| Q(Q(first_person=auth_user) & Q(second_person=send_to))
thread = Thread.objects.filter(final_q)
if not thread:
Thread.objects.create(first_person=auth_user, second_person=send_to)
return render(request, 'chat/chatroom.html')
urls.py
app_name = 'main_app'
urlpatterns = [
...
path('create_chat', CreateChat.as_view(), name='create-chat')
]
I guess ajax request is not the best solution, but I don't know how to implement this feature in another way.
Thanks for the help.
AJAX always returns to request when it is called, so you can't render it to a new view. so to do this, when the request has been successfully completed, return status 200, etc. when getting the success response in AJAX call. likely in
success: function (json) {
},
redirect it to the desired view. so the code will be like that.
from http.client import OK
from django.http import JsonResponse
#method_decorator(csrf_exempt, name='dispatch')
class CreateChat(View):
def get(self,request):
return render(request, 'chat/chatroom.html')
def post(self, request):
send_to_id = int(request.POST.get('send_to_id'))
send_to = User.objects.get(id=send_to_id)
auth_user = request.user
final_q = Q(Q(first_person=send_to) & Q(second_person=auth_user)) \
| Q(Q(first_person=auth_user) & Q(second_person=send_to))
thread = Thread.objects.filter(final_q)
if not thread:
Thread.objects.create(first_person=auth_user, second_person=send_to)
return JsonResponse({},status=OK)
and the AJAX request will be like that
<script>
$(document).on('click', '#chat-button', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "main_app:create-chat" %}',
data: {
send_to_id: $('#chat-button').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
location.href = "create-chat" // from here render create-chat
},
error: function (xhr, errmsg, err) {
}
});
})
</script>

Unable to render a template after using fetch in django

I have the following requirement:
Send data to backend using fetch()
receive the data in a view and render another template ( route to a different view)
The following is my code snippet:
JS:
fetch("/addpost", {
method: "POST",
body: JSON.stringify({ value: selecteddict }),
headers: {
"Content-type": "application/json;",
},
})
.then((res) => {
return res.text();
})
.then((text) => {
console.log(text);
});
// the data is being sent successfully
Django View1:
#csrf_exempt
def addpost(request):
if request.method == 'POST':
song = json.loads(request.body.decode('utf-8'))['value']
print(song)
# I want to redirect to another view called createpost that renders a new page
return JsonResponse({'status':201})
return render(request, 'addpost.html')
Django createpost view:
def createpost(request):
return render(request, 'createpost.html')
The view createpost is working fine when given the required path but it is not rendering when it's redirected from addpost
Please suggest a solution to this.
Your addpost view returns as JsonResponse in case of a POST request. If you want to redirect somewhere you need to use redirect() instead of JsonResponse()

How do I get data from my AJAX Post to my Django View?

This is what My ajax call looks like
$.ajax({
url:"{% url 'handsontable' %}",
data: {'getdata': JSON.stringify(hot.getData())},
dataType: 'json',
type: 'POST',
success: function (res, status) {
alert(res);
alert(status);
},
error: function (res) {
alert(res.status);
}
});
This is what my django view looks like.
if request.method == 'POST':
request_getdata = request.POST.get('getdata', 'None')
return HttpResponse(request_getdata)
The alerts in ajax return the data and "success". But my HttpResponse returns "None".
Any idea why it is not passing the data through? Thanks!
First off you are trying to POST to a html file
url:"/utility_tool/decisions/solution_options/handsontable.html",
Instead, it should be a url to a view.
Second, the ajax post request should have the csrftoken in it's header and you can set it up like this:
<script type="text/javascript">
// using jQuery get csrftoken from your HTML
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
// if not safe, set csrftoken
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: "{% url 'name of the view from urls.py' %}",
data: {
// here getdata should be a string so that
// in your views.py you can fetch the value using get('getdata')
'getdata': JSON.stringify(hot.getData())
},
dataType: 'json',
success: function (res, status) {
alert(res);
alert(status);
},
error: function (res) {
alert(res.status);
}
});
</script>
And in your django view:
# views.py
from django.http import JsonResponse
def someView(request):
if request.method == 'POST':
# no need to do this
# request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
request_getdata = request.POST.get('getdata', None)
# make sure that you serialise "request_getdata"
return JsonResponse(request_getdata)
And in your urls:
# urls.py
urlpatterns = [
# other urls
path('some/view/', views.someView, name='name of the view in urls.py'),
]
I cannot add comments because I do not yet have up to 50 reputations as demanded by StackOverflow. This is supposed to be a comment under the answer provided by #abybaddi009. He has done a very good job thus far but the answer needs a finishing touch.
In the view
request_getdata = request.POST.get('getdata', None) does not work
but this does
body = request.body.decode('utf-8')
data = body[3]
request.body.decode('utf-8') returns a string which would look something like getdata=your_data you can then use string manipulation techniques or regex to extract your data.
What you need to do is :
code for ajax call ( in js file) to send the data to the view
jQuery.ajax(
{
'url': "url_pattern_in_urls_py_file/",
'type': 'POST',
'contentType': 'application/json; charset=UTF-8',
'data': JSON.stringify({'updated_data':your_data_val}),
'dataType': 'json',
'success': function ( return_data ) {
//success body
}
}
);
code in django view with respect to above POST ajax call to receive the data
import json
if request.method == 'POST':
updatedData=json.loads(request.body.decode('UTF-8'))
I added return false; at the end of the ajax request and it worked. I printed out the values in the view instead of using HttpResponse.

Django + Phonegap Authentication

I am building an application with Phonegap on the client side and a Django server on the backend. I am not able to authenticate the user. Here's my code.
$.ajax({
url: "http://192.168.0.101/userbase/login/",
type: "POST",
dataType: "json",
data: {"username": username,
"account": account,
"password": password,},
success: function (json) {
if (json.logged_in == true) {
window.location.href = "products.html";
}
else {
alert("Invalid Credentials. " + json.error);
}
}
});
This is the AJAX call to log in the user from the index.html. It is authenticated temporarily as in the views.py
# SOME CODE
login(request, user=user)
print(request.user.is_authenticated())
response = JsonResponse(response_data)
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'OPTIONS,GET,PUT,POST,DELETE'
response['Access-Control-Allow-Headers'] = 'X-Requested-With, Content-Type'
return response
prints True. But, when the window redirects to products.html and I make an AJAX request to my Django server and check if the user is authenticated or not, it returns False. I am not able to find the error.
Please help. Thanks.

Django returns invalid ajax response

I have a ajax call in my django template file as:
$(document).ready(function () {
$("button#wdsubmit").click(function(){
$.ajax({
type: "post",
url: "/audit/addwd/",
data: $('form.wddetails').serialize(),
dataType: "json",
success: function(msg){
alert(msg);
alert('Added Successfully');
$("#newwd").modal('hide'); //hide popup
},
error: function(msg){
alert(msg.success);
}
});
});
});
Form:
class WDForm(ModelForm):
class Meta:
model = WDModel
fields = '__all__'
and view in django is :
def addwd(request):
if request.method == 'POST':
updated_request = request.POST.copy()
updated_request.update({'updated_by': request.user.username})
form = WDForm(updated_request)
if form.is_valid():
form.save()
response = simplejson.dumps({'success': True})
return HttpResponse(response, content_type="application/json", mimetype='application/json')
else:
response = simplejson.dumps({'error': True})
return HttpResponse(response , content_type="application/json")
Whenever I make a Ajax call it always returns error even though I have sent Success(Means the form is valid and data is successfully pushed to database).
I also tried to send response={'success':True} doesn't work.
Please help me to solve this issue.
Environment Details:
Python verion: 3.4
Django :1.7
Windows OS 8
I doubt on this line " response = simplejson.dumps({'success': success})
"
you can try JsonResponse objects.
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

Categories

Resources