I am trying to send a json response from django view to template but when I try to console.log the response in my ajax, I am getting nothing. What could i be doing wrong ? I am trying to pass the result data from views to my ajax success function. I also noticed something strange that when I mention the datatype = json in my ajax then I dont receive any response in the success function but when I remove the dataType = json then I get the entire html of my template in my success function as a response. Why is that ??
views.py
class ChangePassword(View):
def post(self, request, *args, **kwargs):
form = PasswordChangeForm(request.POST)
#current_password = json.loads(get_value.current_password)
#print ('current password',get_value['current_password'])
if form.is_valid():
print("valid form")
user = CustomUser.objects.get(email=request.user.email)
current_password = form.cleaned_data['current_password']
print('current_password',current_password)
new_password = form.cleaned_data['new_password']
print('newpassword',new_password)
if user.check_password(current_password):
print('entered')
update_session_auth_hash(self.request, self.request.user) # Important!
user.set_password(new_password)
user.save()
result = {'success': "Succefully reset your password"};
result = json.dumps(result)
print ('result',result)
return render(request, 'change_password.html',context={'result': result})
else:
return render(request, 'change_password.html', {'error': "We were unable to match you old password"
" with the one we have. <br>"
"Please ensure you are entering your correct password"
"then try again."})
else:
print("not valid")
return render(request, 'change_password.html', {'form':form})
def get(self, request, *args, **kwargs):
return render(request, 'change_password.html', {})
template
function changePassword() {
csrfSetUP()
new_pass = document.getElementById('new_pass')
cur_pass = document.getElementById('current_pass')
if (validpassword(new_pass) && cur_pass!= "") {
var cpass = $('#current_password').val();
var npass = $('#new_pass').val();
var data = {current_password:cpass,new_password:npass}
$.ajax({
url: '/account/change_password/',
type: 'post',
data: data,
dataType: "json",
success: function(json) {
console.log(json)
}
});
} else {
$('#change_password').submit()
}
}
When you are working with AJAX you have to use JSONResponse() instead of render()
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
If you need to have generated some HTML with that JSON - it is even better to use render_to_string method and return a html string to your AJAX, smth like that:
html = render_to_string('ajax/product_details.html', {"most_visited": most_visited_prods})
return HttpResponse(html)
NOTE: When using render_to_string remember to delete dataType: "json" from your AJAX, cuz u return not JSON, but a string.
P.S. Under this question there are plenty of examples how this can be done, but look at newer ones.
Related
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()
I have a very basic view that is supposed to render a page and pass some data to this page, here is how i do it:
def myview(request):
request = mydb.objects.filter(user=request.user)
return render(request,
"main/mytemplate.html",
context={"data":request})
When the page is loaded, the data is passed to the template, so to show that data, i'll only have to go to my html and add this:
{{data}}
But how can i do the same from a view that is not the same view that renders the page?
Let's say that this is a view that i can call with an Ajax request, so when the Ajax request is triggered, the view should send data in the same way and i want to be able to use it in the Django template language.
Here is an example:
def secondview(request):
request = mydb.objects.filter(item='free')
return HttpResponse(request)
This view is called from an Ajax request, it will send a response with the data, but i don't want to get the data in this format or in json format, instead i want to use it from the Django template language, just as i did with the first example. Is there any way to do it? Or can i only pass data to the template in the context?
1) Instead of returning HttpResponse in your secondview do this
def secondview(request):
from django.template.loader import render_to_string
x = 1
return render_to_string('template_name.jinja', locals())
2) If you want to display that response in your html, do this in your html,
<div id="x"> </div>
function someFunc(){
$.ajax({
url: "someurl",
type: 'GET',
success: function (response) {
document.getElementById("x").innerHtml = response
},
error: function (xhr, err) {
console.log(xhr.responseText);
},
cache: false,
contentType: false,
processData: false
});
I hope I've answered all of your questions, if not let me know.
def myview(request):
request = mydb.objects.filter(user=request.user)
context = {"data":request}
return render(request, "main/mytemplate.html", context)
Here's my View,
class ObjLike(RedirectView):
def get_redirect_url(self, *args, **kwargs):
id = self.kwargs.get('id')
obj = get_object_or_404(Data, id=id)
user = self.request.user
if user.is_authenticated():
if user in obj.likes.all():
obj.likes.remove(user)
else:
obj.likes.add(user)
So after this view how can I redirect user to the same page?
I used "return redirect(request.META['HTTP_REFERER'])" but it gives an error "name 'request' is not defined"
I can't use the get absolute URL method, i'm using this view at several places.
So, how can I do that?
to like an object with ajax calls do this
first in html we want to make a like button:
<button id="like">Like!</button>
the add a script that contain the ajax:
<script>
$(document).ready(function() {
$("#like").click(function(event){
$.ajax({
type:"POST",
url:"{% url 'like' Obj.id %}",
success: function(data){
confirm("liked")
}
});
return false;
});
});
</script>
the we add the like url to the urlpatterns list:
url(r'like/obj/(?P<pk>[0-9]+)/', views.like, name="like"),
adding the view :
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def like(request, pk)
obj = Obj.objects.get(id=pk)
obj.likes += 1
obj.save()
return HttpResponse("liked")
Note: you can customize the like view to check if user liked already
I have an application that I want to put behind a login page. I receive login information through ajax on the login page I load, then I want to load some data based on the user and render them a new page. I'm also using jinja2 to render javascript based on their user data.
#cherrypy.expose
#cherrypy.tools.json_out()
#cherrypy.tools.json_in()
def get_data(self):
result = {"operation": "request", "result": "success"}
input_json = cherrypy.request.json
value = input_json["anno"]
print value
return result
#cherrypy.expose
#cherrypy.tools.json_out()
#cherrypy.tools.json_in()
def login(self):
result = {"operation": "request", "result": "success"}
input_json = cherrypy.request.json
uname = input_json["uname"]
print uname
tmpl = env.get_template('index.html')
imlist = os.listdir('app/public/clips'+uname)
imlist.sort()
print "loading homepage for user " + uname
imlist = ['static/clips/'+item for item in imlist]
return tmpl.render(salutation='User:', target=uname,image_list=json.dumps(imlist))
And my login script in login.html is:
function enter_login(){
var tb = document.getElementById("scriptBox");
var tbtxt = tb.value;
$.ajax({
url: "login",
type: "POST",
contentType: 'application/json',
data: JSON.stringify({"uname": tbtxt}),
dataType:"json"
});
}
What am I doing wrong here? How do I render index.html with the given jinja parameters?
I was able to fix this via adding a success function to the AJAX call:
success:function(data)
{
if(data!="")
{
$("body").html(data);
}
}
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'})