Unable to display queryset using ajax and Django - ajax

I'm not able to display queryset while using ajax
here is my views.py:
if request.user.is_authenticated():
productid = request.GET.get('productId')
print productid
if request.is_ajax():
try:
queryset= StoreProduct.objects.get_size(productid)
except:
queryset= None
data = {
"queryset" : queryset
}
return JsonResponse(data)
Here is my ajax script:
<script type="text/javascript">
function getStoreView(event, productId) {
event.preventDefault();
var data = {
productId : productId
}
$.ajax({
type: "GET",
url: "{% url 'storeView' user=store.user %}",
data: data,
success: function(data) {
console.log(data.queryset)
},
error: function(response, error) {
alert(error);
}
});
};
</script>
What should I do to solve the problem above?
Thanks in advance

If you look at the error message from Django, you will see it complaining that the queryset is not JSON serializable. For ajax requests, you can see the response using your web browser's development tools when DEBUG=True.
The first thing to do is to use values(), which returns a queryset containing dictionaries for each instance in the queryset. Secondly, you need to coerce the queryset into a list.
queryset = StoreProduct.objects.get_size(productid)
values_list = list(queryset.values())

You cannot send queryset directory as json, because json is just a string. You could use django serializer to apply to your queryset:
from django.core import serializers
serialized_qs = serializers.serialize('json', queryset)
data = {"queryset" : serialized_qs}
return JsonResponse(data)
Also in your javascript you have to do data['queryset'] to access your queryset as json.

Related

Django generics view not showing HTML template (using AJAX to access the Django view)

I am trying to access Django view via AJAX and show the data returned by view in HTML page. I am using using Django Rest generics view.
Django view returns response successfully. Then, the page reloads.
But html page has not been shown.
HTML code:
Apply filters
Javascript code:
$("apply-link").click(function(){
filterData(j_data);
});
function filterData(j_data) {
let url = "filter";
const csrftoken = getCookie('csrftoken');
$.ajax({
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
url: url,
data: j_data,
success: function (result) {
console.log(result);
},
error: function (response) {
console.log("error");
}
});
}
views.py
class FilterView(generics.CreateAPIView):
template_name = 'pwa_app/filters.html'
serializer_class = ProductSerializer
def post(self, request):
data = request.data
page = self.paginate_queryset(all_products)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(all_products, many=True)
return Response(serializer.data)
urls.py
path('filter', FilterView.as_view(), name="filter")

Pass an object file from view to template in Django using Ajax

I am trying to pass an object file (3d object) from a view to a html template using Ajax.
Here is the basic code in the view:
def guiMesh(request):
if request.method == 'POST':
if request.is_ajax():
obj = pywavefront.Wavefront( "test.obj")
context = {'meshObj': obj}
return render(request, 'template.html', context)
here is the code the template
$.ajax({
url : '', // the endpoint,commonly same url
type : "POST", // http method
data : { csrfmiddlewaretoken: csrftoken, cooVertex: cooVertex },
success : function(dataObj) {
console.log("dataObj " + dataObj.size)
})
The view side seems working as it does not give any error, but the template side seems not receiving the file correctly. Where am I doing wrong?
Thank you very much for your help!

In Django ,ajax to send the variable by Restful Api

I am a rookie in the Restful,I want to send some variables to the viewset to response some filtering data by "GET"Now I have finished some parts ,I can get the all data,but I don't understand how to send variables to a specific function in the viewset to response some filtering data , for example I crate a new function called "get_ajax_variable() " ,How could I to send variables to the
specific function ?
appreciate in Advance!
This is my Serializer
class CompanySerializer(serializers.HyperlinkedModelSerializer):
Brand = serializers.ReadOnlyField(source='brand_set.all', read_only=True)
class Meta:
model = Company
fields = data_export_setting.Company_form_stand
def create(self, validated_data):
validated_data['owner'] = self.context['request'].user
return Company.objects.create(**validated_data)
This is my viewset
class CompanyViewSet(viewsets.ModelViewSet):
queryset = Company.objects.all()
serializer_class = CompanySerializer
this is my ajax,the function of "showTable(json)" is a function to reload my company.html
<script type="text/javascript">
$(document).ready(function () {
$('#ab').click(function () {
var filter_2 = $("#insert_value").val();//for City
var filter_1 = $("#insert_value_1").val();// for Company type
var filter = $('#filter').val();//for search
$.ajax({
type: "GET",
data: {filter:filter, filter_1_value:filter_1,insert_value:insert_value},
url: "https://horizon-retail-sam-leon-ghibli.c9users.io/restful_api/companyviewset/?format=json",
cache: false,
dataType: "json",
contentType : 'application/json',
success: function (json) {
$('#ajax_search').empty();
showTable(json);
},
error: function () {
alert("false");
}
});
});
});
since it's a GET, why dont you send them as url params ?
I should've replied as a comment but I don't have enough privilege to do it. So please bear with me.
I assume you are using Django Rest Framework(DRF) given the code and tags you put in the question.
Basically, this url: "https://horizon-retail-sam-leon-ghibli.c9users.io/restful_api/companyviewset/?format=json", allows you to send a request along with data to your REST API server, which is DRF in your setup. And urls.py in django get to know the value you sent and direct you to a certain view/viewset, for example, CompanyViewSet in your example.
And in terms of how the view/viewset works with a serializer, you can take a look at http://www.django-rest-framework.org/api-guide/serializers/
and http://www.django-rest-framework.org/tutorial/1-serialization/. And this should suffice. I am not sure about how data got transferred from view/viewset to the serializer. It would be great if someone could explain. But in your serializer, your data should be in validated_data.
In that view/viewset, your data should be in request.data for POST and in GET, it usually in query.params but this really depends on how you construct the ajax call.
It is important to know the difference between POST and GET. You can simply google it.
HTH.
Yes!I have solve this problem ,the following is my step
the most important step is to overwrite function get_queryset(self): in the class of Viewset
in the template ,the ajax is as follows:
<script type="text/javascript">
$(document).ready(function () {
$('#ab').click(function () {
var filter_2 = $("#insert_value").val();//for City
var filter_1 = $("#insert_value_1").val();// for Company type
var filter = $('#filter').val();//for search
$.ajax({
type: "GET",
//data: {filter:filter, filter_1_value:filter_1,insert_value:insert_value},
url:"You_own_url"+format=json&a="+filter+"&b="+filter_1+"&c="+filter_2,
cache: false,
dataType: "json",
contentType : 'application/json',
success: function (json) {
$('#ajax_search').empty();
showTable(json);
},
error: function () {
alert("false");
}
});
});
in the Setting of Django,you should set the REST_FRAMEWORKas
'DEFAULT_FILTER_BACKENDS':('django_filters.rest_framework.DjangoFilterBackend',),
in the Url of Django,you should set the url as follows:
router.register(r'companysearch',CompanyViewSet)
in the viewset,I did not pull all function of get_queryset, you should set as follows:
serializer_class = CompanySerializer
filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
def get_queryset(self):# how to define the null and None
filter_1 = self.request.query_params.get('a')#, None)
filter_company_type = self.request.query_params.get('b', None)# company_type
filter_city_type = self.request.query_params.get('c', None)
....
then you can get the result correctly ,thanks anyone who helps

How to make an ajax request to a view

I am trying to figure out how I can make an ajax request (with jquery) from my template in order to execute a view on a button click. I don't want to redirect to another page. I just need to execute the code in the view.
This is my on button click event:
$(document.body).on("click", "#download_xls",function(e) {
selected_country = ($("#button-countries").val())
selected_subareas = $('#_all_values').val();
id = "?country=" + selected_country + "&" + "regions=" + selected_subareas
whole_url = "{% url 'test_download' %}" + id
$("#download_xls").attr("href", whole_url)
});
As I pass the values in my URL, I don't even need to pass some parameters through the ajax request. I just need to execute the code in the view.
The view is something like this:
def test_download(request):
print(request.GET.get('country'))
print(request.GET.get('regions'))
fileContent = "Your name is %s"
res = HttpResponse(fileContent)
res['Content-Disposition'] = 'attachment; filename=yourname.txt'
return res
EDITED
I have added the ajax GET request in my template as:
whole_url = "{% url 'test_download' %}"+id
$.ajax({
type: "GET",
url: whole_url,
success: function(data) {
alert('sd')
},
error: function(data) {
alert('error')
},
});
I get an error cause there is no corresponding template for this view. I think I need to add something in the urls.py file.
I read here that I need to modify urls.py as:
url(r'^link-to-fun1$', views.fun1),
But its not clear to me what should be the link-to-fun1.
I tried:
url(r'^create$', 'test_download', name='test_downlad'),
But gives an error: No Reverse Match.
You could use TemplateView add to your url and use JQuery to do something, like this:
views.py
class ajax_view(TemplateView):
def get(self, request, *args, **kwargs):
id_value = request.GET['id']
value = Model.objects.filter(id=id)
data = serializers.serialize('json', value, fields=('fieldone'))
return HttpResponse(data, content_type='application/json')
urls.py
url(r'^ajax/$', ajax_view.as_view()),
JQuery
$.ajax({
data: { 'id': id },
url: '/ajax/',
type: 'get',
success: function (data) {
// Do something with the data
}
})
That's in general how you can use Ajax with Django, the important is the use of TemplateView

Post selected rows with jquery to a Django 1.5 view

I have a table with multiple <tr> which each has a PK as ID. I am going to POST these <tr> to a Django 1.5 view, but I don't know how to send the data properly.
I've made this javascript function, and it posts successfully, but I don't know how to send the id's of selected_rows, and how to retrieve them in a class based Django view.
function update() {
var selected_rows = $(".ui-selected");
$.ajax({
type: "POST",
url: "/confirm/",
data: { name: "selected_rows" },
success: function(data) {
selected_rows.addClass('success');
}
});
}
I guess the Django view is something like
class ConfirmView(TemplateView):
def post(self, queryset=None):
return HttpResponse("POST")
I've also tried
function update() {
var selected_rows = $(".ui-selected");
selected_rows.each(function() {
$.ajax({
type: "POST",
url: "/confirm/",
data: { id: $(this).attr("id") },
success: function(data) {
$(this).addClass('success');
}
});
});
}
and
class ConfirmView(TemplateView):
def post(self, queryset=None):
if self.request.POST['id']:
ModelName.objects.filter(pk=self.request.POST['id']).update(is_confirmed=True)
return HttpResponse("POST")
But I guess it's better to handle all the rows in the same database query instead of splitting them as above. But if I split them as above, I could check whether or not they were updated successfully, so maybe it's better that way?
You need to do:
data: { name: selected_rows } //Do not put selected_rows in quotes
Also why are you using TemplateView here, it doesn't give you any advantage. You just need to create something and send a response which ajax will handle. You can just use a function view here.
If you use class based view, your signature of post has a bug:
It should be:
def post(self, request, *args, **kwargs):
name = request.POST['name']

Resources