JS
$(function(){
var count=1;
$("#btn").click(function(){
count++;
})
})
views.py
def setparam(request):
counts=range(1,count)
eg.
Like this I want use JS's count to view.py .How can I get it ,is it possible?
You need send this to server.
I guess you ajax for your example.
JS
function send_cont(cont) {
$.ajax({
url: '{% url "your_app.views.your_view" %}',
type: "GET",
data: {
cont: cont
},
success: function (json) {
//Something
},
error: function (json) {
//Something
}
});
}
View
def your_view(request):
cont = request.GET.get('cont'))
#More code
Related
I'm trying to validate a field while typing based on another question (How to validate django form field while it is typing?).
The js doesn't cal validation view
form
{{ form.num }}
<p id="validate_number" class="help is-danger is-hidden ">nome já utilizado</p>
js
<script>
$('#id_num').on('input', function () {
var id_number = $(this).val();
$.ajax({
url: '{% url 'validate-num' %}',
data: {
'num': id_number
},
dataType: 'json',
success: function (data) {
if (data.is_taken) {
$("#validate_number").show();
document.getElementById('id_num').style.borderColor = "red";
document.getElementById("submit_change").disabled = true;
}
else {
$("#validate_number").hide();
document.getElementById('id_num').style.borderColor = "#e7e7e7";
document.getElementById("submit_change").disabled = false;
}
}
});
});
</script>
url.py
urlpatterns = [
# ...
path('validatenum/', validate_inventory_number, name='validate-num'),
# ...
]
view
def validate_inventory_number(request):
number = request.GET.get('num', None)
data = {
'is_taken': InventoryNumber.objects.filter(num=number).exists()
}
return JsonResponse(data)
I am using Django and Ajax.
Im my view I have:
class MainView(View):
def get(self, request):
if not request.is_ajax():
return render(request, "main.html")
# hard coded both options for testing
return JsonResponse({"data": "xyz"}, status=400)
# return JsonResponse({"data": "xyz"}, status=200)
my ajax function looks like:
$("#start_calculation_button").click(function () {
$.ajax({
url: "/",
type: 'get',
data: {
...
},
success: function (response) {
console.log(response.data);
},
error: function (response) {
console.log(response.data);
}
})
})
But only the success function works? While the error part just gives back undefined
Any idea's why it is that way?
How can I fix it?
The parameters of success and error are different, in case of a success, these parameters are result, status, and xhr whereas for error, the parameters are xhr, status, and error. You thus should parse the xhr data with:
$("#start_calculation_button").click(function () {
$.ajax({
// ⋮
success: function (response) {
console.log(response.data);
},
error: function(xhr) {
var err = JSON.parse(xhr.responseText);
console.log(err.data);
}
})
})
I have two Models classes
class Dishes(models.Model):
dishName=models.CharField()
class Hotels(models.Model):
hotelname=models.CharField()
dishes = models.ManyToManyField('Dishes')
In views.py
def check_dishes(request):
HotelId = request.GET.get('Id', None)
hotelObj = Hotels.objects.get(pk=HotelId )
dishesObj= hotelObj.dishes.all()
data = {
'HotelName': hotelObj.hotelname
}
Dlist=[]
for dish in dishesObj:
Dlist.append(dish.dishName)
data.update([
('dishes_list', Dlist),
])
print(data)
*** output as below
{'HotelName': 'DeMart', 'dishes_list': ['pizza','burger']}***
return JsonResponse(data,safe=False)
In hotels.html we have an ajax call like
$("#getHotelDishes").keyup(function () {
$.ajax({
url: "{% url 'check_dishes' %}",
dataType: 'json',
data: {
"hotelId": Id
},
// on success
success: function (data) {
{% for dishes in data.dishes_list%}
//print dish Names of this Hotel
{% endfor %}
},
// on error
error: function (response) {
console.log(response.responseJSON.errors)
}
})
});
Is this the right way to pass Queryset data via Ajax call,I could not get any result in for loop
I got it, I was using template tags to iterator the list which is not working, I just deleted and updated the ajax function as below
// on success
success: function (data) {
for (i = 0; i< data.dishes_list.length; i++) {
//do something
}
},
But why is that the template tag failed to work,I still wonder!!
I want to show the dropdown list with data response via Ajax call. Everything is working fine but I am getting this ValueError: Cannot use None as a query value error.
view:
def load_brand(request):
if request.is_ajax():
term = request.GET.get('term')
brand = Brand.objects.all().filter(brand__icontains=term)
return JsonResponse(list(brand.values()), safe=False)
ajax:
$('#id_brand').select2({
ajax: {
url: '/brand/ajax/load-brand/',
dataType: 'json',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {id: item.id, text: item.brand};
})
};
}
},
minimumInputLength: 1
});
In your ajax call you have not send the data i.e : which user type inside select2 and you are accessing them i.e : request.GET.get('term') which is empty so your .filter(brand__icontains=term) giving you error because term value is null.
Instead you can add below as well in your ajax call :
$('#id_brand').select2({
ajax: {
url: '/brand/ajax/load-brand/',
dataType: 'json',
data: function(params) {
var query = {
term: params.term, //this will be paass
type: 'public' //optional..
}
// Query parameters will be ?term=[values]&type=public
return query;
},
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
id: item.id,
text: item.brand
};
})
};
}
},
minimumInputLength: 1
});
Also , at your server end you can check if the term has any value i.e :
if term:
brand = Brand.objects.all().filter(brand__icontains=term)
For more information check this
I am using quill editor to upload an image and the an ajax function is used to send the image to views.py.
This is the python function for uploading the image.
views.py
def upload_image(request):
if request.method == 'POST':
handle_uploaded_file(request.FILES.get('file'))
return HttpResponse("Successful")
return HttpResponse("Failed")
def handle_uploaded_file(file):
with open('upload/', 'wb+' ) as destination:
for chunk in file.chunk():
destination.write(chunk)
This is the ajax request:
function upload(file, callback) {
console.log('called');
var formData = new FormData();
formData.append('file', file);
$.ajax({
url : '{% url 'dashboard:upload_image' %} ',
type : 'POST',
data : formData,
contentType: 'multipart/form-data',
headers: { "X-CSRFToken": $.cookie("csrftoken") },
processData: false,
success: function(data) {
console.log('success');
callback(data.url)
}
});
}
Function calling upload() :
function(value) {
let fileInput = this.container.querySelector('input.ql-image[type=file]');
if (fileInput == null) {
fileInput = document.createElement('input');
fileInput.setAttribute('type', 'file');
fileInput.setAttribute('accept', 'image/*');
fileInput.classList.add('ql-image');
fileInput.addEventListener('change', () => {
if (fileInput.files != null) {
upload();
}
});
this.container.appendChild(fileInput);
}
fileInput.click();
}
}
Error in string
with open('upload/', 'wb+' ) as destination:
Wrong path. Set the file name.