How can I display data sent through ajax in django? - python

I have the following setup but I can't seem to display content in ajax although it works if I go directly to the url.
<div class="test" style="width:200px; height:200px; border-style:solid;">
<button class="testb">click here</button>
</div>
Script:
$(".testb").click(function() {
$.ajax({
url: '../profile_page_tags_get/' + 'primary',
type: 'GET',
dataType: "json",
success: function(data) {
$(".test").html( "<div>" + data + "</div>")
}
})
});
View function:
def profile_page_tags_get(request, edit_type):
data = {}
if edit_type == 'primary':
p_options = Primary.objects.all()
data['p_options'] = list(p_options.values_list())
return HttpResponse(json.dumps(data), content_type = "application/json")
Url:
url(r'^profile_page_tags_get/(?P<edit_type>.*)/$', views.profile_page_tags_get, name='profile_page_tags_get'),

Related

Django: ajax not returning or sending any data in django

i am creating a simple like button with ajax, i have followed the tutorial but it seems, that i am missing something, i am not getting any error either in the console in my django terminal but when i click the button no data get sent, evrything just remains the same way, and this is not what i am expecting, i know i am missing something somewhere and i cannot really tell where this error is coming from.
views.py
#login_required
def like(request):
if request.POST.get("action") == 'post':
result = ""
id = int(request.POST.get('courseid'))
course = get_object_or_404(Course, id=id)
if course.like.filter(id=request.user.id).exists():
course.like.remove(request.user)
course.like_count -= 1
result = course.like_count
course.save()
else:
course.like.add(request.user)
course.like_count += 1
result = course.like_count
course.save()
return JsonResponse({'result': result})
urls.py NOTE:I don't know if i need a slug in this url path
path('like/', views.like, name="like"),
base.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
course-detail.html
<li><button id="like-button" value="{{course.id}}">like</button><span id="like-count">{{course.llke_count}}</span></li>
<script type="text/javascript">
$(document).on("click", '#like-button', function(e){
e.preventDefault()
$.ajax({
type: 'POST',
url: '{% url 'course:like' course.slug %}',
data: {
courseid: $('#like-button').val(),
csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(),
action: 'post'
},
success: function(json){
document.getElementById("like-count").innerHTML = json['result']
console.log(json)
},
error: function (xhr, errmsg, err)
console.log(xhr)
console.log(errmsg)
console.log(err)
})
})
</script>
this is all the code i have written for the functionality, if there is any other thing to be provided i will update the question
UPDATE AFTER FIRST ANSWER
#####################################################################
Now when i click the like button is does show an visible error but the like count now shows undefined and in my chrome dev tools is shows failed to load response data because this request was redirected
Update your code like this and I've doubt about your like table provide that inside your question.
inside your views.py
#login_required
def like(request):
if request.method == 'POST':
result = ""
course_id = int(request.POST.get('courseid'))
course = get_object_or_404(Course, id=course_id)
if course.like.filter(id=request.user.id).exists():
course.like.remove(request.user)
course.like_count -= 1
result = course.like_count
course.save()
else:
course.like.add(request.user)
course.like_count += 1
result = course.like_count
course.save()
return JsonResponse({'result': result})
inside your course-detail.html
<script type="text/javascript">
$("#like-button").on("click", function (e) {
e.preventDefault()
$.ajax({
type: 'POST',
url: "{% url 'course:like' %}",
data: {
courseid: $('#like-button').val(),
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function (json) {
document.getElementById("like-count").innerHTML = json['result']
console.log(json)
},
error: function (xhr, errmsg, err) {
console.log(xhr)
console.log(errmsg)
console.log(err)
}
})
})
</script>
Note :
You don't have to check for action instead you can check for method eg. request.method.
You've provided wrong url inside your ajax call '{% url 'course:like' course.slug %}' it should be '{% url 'course:like' %}' without passing slug.
Do not use id as avariable because it will conflict with python id() function, you can check for all available built-in functions in python here.

Python Django Ajax get request not working in def function

I'm trying to pass a variable from my JQuery Ajax object via get method to my views.py file (in django)
I was using a class before and it was working just fine..
views.py working code:
class AjaxHandlerView(View):
def get(self, request):
text = request.GET.get('button_text')
print()
print(text)
print()
if request.is_ajax():
return JsonResponse({'test': 'blah'})
return render(request,'home.html' , {'name': 'Handled by AHV'} )
app urls.py
from django.urls import path
from . import views
from .views import *
urlpatterns = [
path('', AjaxHandlerView.as_view() ),
path('ajaxg' , views.ajaxgtest, name="ajaxg" )
]
jquery ajax functions (ignore the post method)
var test_str = "[0,0]";
$(document).ready(function(){
var csrf = $('input[name=csrfmiddlewaretoken]').val()
$('#jq_btn').click(function(){
$.ajax({
url: '',
type: 'get',
data: {
button_text: test_str
},
success: function(response) {
$("#jq_btn").text(response.test + test_str);
console.log(test_str);
}
});
});
$('#post_btn').click(function() {
$.ajax({
url: '',
type: 'post',
data: {
text: test_str,
csrfmiddlewaretoken: csrf
},
success: function(reponse) {
test_str = reponse.postdata
console.log(test_str);
}
})
});
});
However I wanted to use a specific function for specific methods.. so I tried using a def..
views.py that is not working:
def ajaxgtest(self, request):
text = request.GET.get('button_text')
print(text + "deffer")
if request.is_ajax():
return JsonResponse({'test': 'blah'})
return render(request,'home.html' , {'name': 'Handled by AHV'} )
As for the Jquery code, all I did was edit url: '' to url: 'ajaxg' (which is what I named the view in the urls.py file)
new jq ajax code:
$('#jq_btn').click(function(){
$.ajax({
url: 'ajaxg',
type: 'get',
data: {
button_text: test_str
},
success: function(response) {
$("#jq_btn").text(response.test + test_str);
console.log(test_str);
}
});
});
I'm getting the error code;
TypeError: ajaxgtest() missing 1 required positional argument: 'request'
[01/Jan/2021 01:25:31] "GET /ajaxg?button_text=%5B0%2C0%5D HTTP/1.1" 500 58077
I'm unsure where I need to put a request element, or what not..

How to pass parameters of Ajax URL in Django?

I used Ajax to add items to wishlist:
<a href="{% url 'listing:wishlist' list.slug %}" id="wishlistbtn" data-slug='{{ list.slug }}'>Add to
wishlist</a>
the url looks like:
path('wishlist/<slug:title_slug>/', wishlist, name='wishlist'),
but I don't know how to pass list.slug or title_slug in above url using Ajax:
$(document).on('click', '#wishlistbtn', function (e) {
$.ajax({
type: 'GET',
url: "{% url 'listing:wishlist' %}",
data: {
title_slug: e.target.getAttribute('data-slug')
},
success: function (response) {
alert('added to wishlist')
}
})
})
my above stated solution didn't work? Please help me with this. Thank you.
edit: View added
def wishlist(request):
slug = request.GET.get('title_slug')
obj = get_object_or_404(Listing, slug=slug)
profile = Profile.objects.all().filter(user=request.user).first()
profile.wishlist.add(obj)
return HttpResponse('true')
is this your solution to pass the data-slug ?
$(document).on('click', '#wishlistbtn', function (e) {
let el = $(this);
$.ajax({
type: 'GET',
url: "{% url 'listing:wishlist' %}",
data: {
title_slug: el.attr("data-slug"),
},
success: function (response) {
alert('added to wishlist')
}
})
})
use this path -
path('wishlist', wishlist, name='wishlist'),
in your views to get slug use - request.GET.get("title_slug")
I don't know exactly what you want to do but I had similar situation, I will share my code with you hopefully it helps you
HTML
<div class="btn-wrapper">
<p id="loadMore_articles" data-total="{{total_data}}" data-limit="3" data-slug="{{author.id}}" class="btn-default transparent-btn-2 .">load articles <i class=" load-more-icon"></i></p>
</div>
JQuery/JS
$(document).ready(function () {
$("#loadMore_articles").on('click', function () {
var _currentarticles = $(".article-box").length;
var _limit = $(this).attr('data-limit');
var _total = $(this).attr('data-total');
var _slug = $(this).attr('data-slug');
// Start Ajax
$.ajax({
url: 'author/articles/load-more-articles',
data: {
slug: _slug,
limit: _limit,
offset: _currentarticles
},
dataType: 'json',
beforeSend: function () {
$("#loadMore_articles").attr('disabled', true);
$("#loadMore_articles").html('');
$(".load-more-icon").addClass('fa-spin');
$("#loadMore_articles").addClass("button--loading");
},
success: function (res) {
console.log(res);
console.log(res.articles);
$("#articles").append(res.articles);
$("#loadMore_articles").attr('disabled', false);
$(".load-more-icon").removeClass('fa-spin');
$("#loadMore_articles").html('Load Articles');
$("#loadMore_articles").removeClass("button--loading");
if (res.articles == '') {
$("#loadMore_articles").remove();
}
}
});
// End
});
});
views.py
def author_ajax_articles(request):
author = int(request.GET['slug'])
offset=int(request.GET['offset'])
limit=int(request.GET['limit'])
data=News.objects.filter(Q(author=author)&Q(is_live=True))[offset:offset+limit]
t=render_to_string('author/ajax/article.html',{'articles':data})
return JsonResponse({'articles':t})
forgive my bad codes... I am still learning clean code but I hope this helps you in your quest

Bottle POST method - getting query parameters

I am trying to send a POST AJAX request to a Bottle server and read query_string parameters.
This works with GET method, but with POST, bottle.request.query_string is empty.
This is with python 3.6.8. Bottle version in 0.12.17
I'm stuck, please advise.
Bottle server:
#!/usr/bin/env python3
import bottle
print(bottle.__version__)
class EnableCors(object):
name = "enable_cors"
api = 2
def apply(self, fn, context):
def _enable_cors(*args, **kwargs):
bottle.response.headers["Access-Control-Allow-Origin"] = "*"
bottle.response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS"
bottle.response.headers["Access-Control-Allow-Headers"] = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token"
if bottle.request.method != "OPTIONS":
return fn(*args, **kwargs)
return _enable_cors
application = bottle.app()
application.install(EnableCors())
#application.route("/api/params", method=['OPTIONS', 'POST'])
def Api_Params():
print('bottle.request.query_string:', bottle.request.query_string)
bottle.run(host='0.0.0.0', port=8080, debug=True, reloader=True)
Test javscript client:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
function test_post_param() {
var data = {'e': 'E', 'f': 'F', 'g': {'aa':'AA', 'bb':'BB'}};
$.ajax({
url: 'http://127.0.0.1:8080/api/params',
method: "POST",
data: "key=a",
// contentType: "text/plain",
success: function (response, textStatus) {
console.debug("test_post_param OK");
console.debug(textStatus);
console.debug(response);
},
error: function (response, textStatus) {
console.debug("test_post_param ERR");
console.debug(textStatus);
console.debug(response);
},
})
}
window.onload = test_post_param;
</script>
</body>
</html>
I put this on all my API endpoints. I am combining the POST form and query encoding into a single dict.
def merge_dicts(*args):
result = {}
for dictionary in args:
result.update(dictionary)
return result
payload = merge_dicts(dict(request.forms), dict(request.query.decode()))
So your code would look like this:
#application.route("/api/params", method=['OPTIONS', 'POST'])
def Api_Params():
payload = merge_dicts(dict(request.forms), dict(request.query.decode()))
print('bottle.request.query_string: {}'.format(payload))
Here is an example sending the data as JSON to a POST route which I have used successfully.
The JQuery AJAX call:
function test_post_param() {
var data = {'e': 'E', 'f': 'F', 'g': {'aa':'AA', 'bb':'BB'}};
$.ajax({
url: 'http://127.0.0.1:8080/api/params',
method: "POST",
data: JSON.stringify({
"key": "a"
}),
cache: false,
contentType: "application/json",
dataType: "json",
success: function(data, status, xhr){
// Your success code
},
error: function(xhr, status, error) {
// Your error code
}
})
};
The Bottle route:
#application.route("/api/params", method=['POST'])
def Api_Params():
key = bottle.request.forms.get("key")
print(key) # This should print 'a'
I prefer from bottle import route, get, post, template, static_file, request as the import statement. This allows the route to be written more simply (in my opinion).
#post("/api/params")
def Api_Params():
key = request.forms.get("key")
print(key) # This should print 'a'

HttpResponseRedirect not working for deletion and page redirect on button click

I am trying to delete a job at the click of a button and redirect to a different page. The deletion works but the redirection does not. My code is as follows:
views.py:
#login_required
def delete_job(request):
job_id = request.GET['Jobid']
job = Job.objects.get(pk=job_id)
try:
job.delete()
#return render(request, 'main/communitypartner_dash.html', {'form':form,'job' : job})
#return redirect('user_dash')
return HttpResponseRedirect('main/communitypartner_dash.html')
#return HttpResponseRedirect(reverse('user_dash'))
#jobs = user.jobs.all()
#return render_to_response('main/communitypartner_dash.html')
except Exception as e:
return HttpResponse("deletion not successful")
#return render(request, 'main/communitypartner_dash.html', {'form':form,'job' : job})
url.py:
url(r'^job/job_delete/$', views.delete_job),
html:
<button type="button" class="btn btn-primary" onclick="doDelete()">Dissolve</button>
<script>
function doDelete(){
$.ajax({
url: '/job/job_delete/',
data: {
'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
'Jobid': {{job.id}}
},
dataType: 'json',
complete: function (response) {
// $('#status').html(response.responseText);
},
error: function () {
// $('#status').html('Bummer: there was an error!');
},
});
return false;
}
I tried all the ways that are commented out in the try section of views.py. Please help. Thanks
The following will work
from django.http import JsonResponse
# codes here
job.delete()
return JsonResponse({'url':'main/communitypartner_dash.html'}) # whatever the url is
# or return JsonResponse({'url':reverse('url_name',kwargs={"arg":arg})})
js
// codes here
complete: function (response) {
window.location.href = response.url
},
error: function () {
// $('#status').html('Bummer: there was an error!');
},

Categories