How do I send django object list to javascript? - javascript

I want to django query to javascript.so I changed queries to list. I sended list to javascript.But list were not displayed by console log.
class Comment_List_TV(ListView):
template_name = 'account/user_comment_list_tv.html'
def get_queryset(self):
Comment_list_query = list(Comment_tv.objects.none())
if self.request.user.is_authenticated:
Comment_list_query = list(Comment_tv.objects.filter(user=self.request.user))
print(Comment_list_query)
return Comment_list_query
Print display object list. But
const mydata = "{{Comment_list_query}}";
console.log(mydata);
Console log does not display django's object list.
why?
How do I send django object list to javascript?

Console log does return nothing because Comment_list_query in django template is called object_list, so you should use...
const mydata = "{{ object_list }}";
console.log(mydata)
But it won't work, because you probably needs parsed values.
So, you should write view like this:
#csrf_exempt
def get_comments(request):
comment_list_query = list(Comment_tv.objects.all())
return JsonResponse({'result': comment_list_query})
And receive it from AJAX call (for example using AJAX method from jQuery package).

Related

Render template in Django view after AJAX post request

I have managed to send & receive my JSON object in my views.py with a POST request (AJAX), but am unable to return render(request, "pizza/confirmation.html"). I don't want to stay on the same page but rather have my server, do some backend logic on the database and then render a different template confirming that, but I don't see any other way other than AJAX to send across a (large) JSON object. Here is my view:
#login_required
def basket(request):
if request.method == "POST":
selection = json.dumps(request.POST)
print(f"Selection is", selection) # selection comes out OK
context = {"test": "TO DO"}
return render(request, "pizza/confirmation.html", context) # not working
I have tried checking for request.is_ajax() and also tried render_to_string of my html page, but it all looks like my mistake is elsewhere. Also I see in my terminal, that after my POST request, a GET request to my /basket url is called - don't understand why.
Here is my JavaScript snippet:
var jsonStr = JSON.stringify(obj); //obj contains my data
const r = new XMLHttpRequest();
r.open('POST', '/basket');
const data = new FormData();
data.append('selection', jsonStr);
r.onload = () => {
// don't really want any callback and it seems I can only use GET here anyway
};
r.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
r.send(data);
return false;
In your basket view function, you always render the template as response. You can pass the parameters to your js snippet via HttpResponse. After request completed and you have response in your js function, you can use window.location.href to redirect the page you want. You can also look this answer to get more information.

How to render data in django to AJAX?

I am trying to send a json value to ajax from django class based view and the data i am sending will be appended in html through ajax. but i am not able to send value from back end to front end successfully.
class DetailView(TemplateView):
template_name = 'list.html'
def get_context_data(self,*args, **kwargs):
context = super(DetailView,self).get_context_data()
list_view = GetList().get_data(self.request)
movie_list = list.json()
context['list']= movie_list
print(movie_list)
return context
So this code is sending only template value to the ajax data, when i do the console.log(data) on success call it shows me whole html code of the 'list.html' in both alert and console.log . But it prints all the values in cmd console.
cclass DetailView(TemplateView):
template_name = 'list.html'
def get(self,request):
list_view = GetList().get_data(self.request)
movie_list = list.json()
return HttpResponse(json.dumps(movie_list))
this code prints all the values on respective html, but doesnt call ajax function.so no values showing in console.log.
this is my ajax call,first i am trying to just see weather i'm successfully getting the values on success call or not.
<script>
$(document).ready(function(){
$.ajax({
method :'GET',
url: '/detail',
success: function(data){
alert(data)
console.log(data)
},
})
})
</script>
So, how can i achieve my desired result? I want to get value in ajax call so i cal show those values in a table which is in a list form
You can use JsonResponse to send json data. (You can see detail in docs here)
like below
from django.http import JsonResponse
class DetailView(TemplateView):
template_name = 'list.html'
def get(self,request):
list_view = GetList().get_data(self.request)
movie_list = list.json()
return JsonResponse(movie_list, status=200)
btw, you have to aware your data type. JsonResponse automatically serialize your data so you don't have to use json() for your data.

How to save Json in the django database from Javascript

I will generate a json and save it in a string variable, and I need to save the whole json in my database.
I have a view
class DashboardView(TemplateView):
template_name = 'votes/dashboard.html'
in this template, I have javascript, and in this javascript I'm generating Json and saving it in a js variable, and I want to put the json in the variable into the DB.
As I'm gonna create a object for the jsons, I'll change templateview to CreateView as It's gonna save.
But how is this json going to become available for the view to be saved ?
brief instruction
using jquery ajax:
$.post( "/your/url/for/store/json/data", { jsonField: jsonData } );
in your view:
def save_json_data(request):
...
data = request.POST.get("jsonField", "")
model = YourModel(json_field=data)
model.save()
...

Using list from views in Django 1.8.1 as an array in javascript template

I have a piece of code in views.py that gets the file names from a directory:
def imgArray(request):
filepath = STATIC_PATH+"\\images"
imageArray=[]
ext='.jpg'
for i in os.listdir(filepath):
if(os.path.splitext(i)[1] == ext):
imageArray.append( i )
context = {'imageArray': imageArray}
print context
return render(request, 'imgpage/add_category.html',context)
def add_category(request):
# A HTTP POST?
if request.method == 'POST':
#Do some actions
else:
# If the request was not a POST, display the form to enter details.
imageArray = imgArray(request)
return render(request, 'imgpage/add_category.html')
I want to use this array of image files in javascript. I want to use the array of file names so that I can use js to change image source.
The print context statement yields the following output in the python console:
{'imageArray': ['image0.jpg', 'image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.
jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg']}
But I am not able to access the imageArray at all in the template. Here are the scripts I tried to test if the array has been passed, in the template html file:
In add_category.html file:
{% for img in imageArray %}
<li>{{ img|safe }}</li>
<li>{{ img }}</li>
<p>img</p>
{% endfor %}
Also, note that the "img" inside <p> tags are also not rendered on the screen.
<script type="text/javascript">
var images = "{{imageArray|safe}}";
console.log(images);
console.log("imgx="+images[1]);
document.getElementsByTagName("img")[0].src = DJANGO_STATIC_URL+images[2];
</script>
In the above script, the first console log prints empty line in the console, while the 2nd prints "imgx=undefined"
Please suggest me ways I can use the python list as JS array. I use Django 1.8.1, but the service I would host on uses 1.7.x. So something that would work on both would be great.
You have a very peculiar structure here. imageArray() is a view, which returns a full HttpResponse; but you call it from within another view, add_category. What's more, you do nothing at all with the result; it is thrown away and never passed anywhere. So, naturally, it's always going to be blank in the template.
I'm not sure exactly what you're doing, so it's hard to know what you really want here. But I suspect that imageArray() should be a normal utility method, which simply returns a list of images:
def imgArray():
filepath = os.path.join(STATIC_PATH, "\\images")
images =[f for f in os.listdir(filepath) if f.endswith('.jpg')]
return images
Then you need to actually do something with that value in your add_category function:
def add_category(request):
...
else:
imageArray = imgArray()
return render(request, 'imgpage/add_category.html', {imageArray: imageArray})
So here is what I did:
views.py
#importing json
import json
from django.core.serializers.json import DjangoJSONEncoder
def imgArray(request):
filepath = STATIC_PATH+"\\images"
imageArray=[]
ext='.jpg'
for i in os.listdir(filepath):
if(os.path.splitext(i)[1] == ext):
imageArray.append( i )
json_list = json.dumps(list(imageArray), cls=DjangoJSONEncoder)
return json_list
def add_category(request):
# A HTTP POST?
if request.method == 'POST':
#Do something
else:
# If the request was not a POST, display the form to enter details.
imageArray = imgArray(request)
context = {'imageArray': imageArray}
return render(request, 'imgpage/add_category.html',context)
return render(request, 'imgpage/add_category.html')
And in add_category.html:
<script type="text/javascript">
var images = {{imageArray|safe}};
document.getElementsByTagName("img")[0].src = DJANGO_STATIC_URL+"images/"+images[1];
</script>
Hope this helps someone :)
Cheers!

Accessing Django dictionary in Javascript

I'm passing a dictionary from my Django view and want to access the dictionary in my code.
view code:
res.responses is a dictionary
def index(request):
import pprint
pprint.pprint(res.responses)
print 'type = ', type(res.responses)
return render_to_response("deploy/index.html", {"responses":res.responses})
Javascript code:
$(document).ready(function(){
//{% for each in responses%}
// console.log(Hi)
//{% endfor %}
var response = "{{responses}}"
console.log(response)
I tried accessing the variable directly using for loop and also accessing the variable directly. Both throw me an error. Please provide some suggestion.
You can do both.
Option 1:
Provide the script via a template that will send the code with the values. Will look ugly but work. Your javascript file or even the html must be parsed by the django template engine. They can't be static
Option 2:
Provide a new view with a json response, that is accessed from your javascript code (ie: via JQuery)

Categories

Resources