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!!
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 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
Each form's input is associated with a unique data-comment-pk. I'm trying to access the value of data-comment-pk of the input which is submitted. Currently, the AJAX success function's alert(comment_pk) is only fetching me the comment_pk of the first form. How can I access the comment_pk of the form which is submitted instead of getting the comment_pk of the first form?
html template
{% for comment in object_list %}
<h3>{{comment.comment}} by {{comment.username}}</h3>
<form class="score-form">
<input type="submit" value="Up" name="up" class="Up" data-comment-pk="{{comment.pk}}" />
<input type="submit" value="Down" name="down" />
</form>
{% endfor %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script>
$(".score-form").submit(function (e) {
e.preventDefault();
var comment_pk = $(".Up").attr("data-comment-pk");
var url = comment_pk + "/vote";
console.log(url)
$.ajax({
type: 'GET',
url: url,
data: { "up": 'UP' },
success: function (response) {
if (response["valid"]) {
alert(comment_pk);
}
},
error: function (response) {
console.log(response)
}
})
})
</script>
models.py
class CommentModel(VoteModel, models.Model):
comment = models.TextField()
username = models.ForeignKey(User, on_delete=models.CASCADE)
views.py
class CommentView(ListView):
model = CommentModel
def comment_vote(request, comment_id):
if request.is_ajax and request.method == "GET":
# do some stuff
return JsonResponse({"valid": True}, status=200)
Here is the solution to this problem :
var comment_pk = $(".Up", this ).attr("data-comment-pk");
Using this will return the current HTML element.
try: add "this" to before .Up in the comment_pk.
let me know if it works.
this- will get the currect form that have been submit and get the .Up Class
<script>
$(".score-form").submit(function (e) {
e.preventDefault();
var comment_pk = $("this .Up").attr("data-comment-pk");
var url = comment_pk + "/vote";
console.log(url)
$.ajax({
type: 'GET',
url: url,
data: { "up": 'UP' },
success: function (response) {
if (response["valid"]) {
alert(comment_pk);
}
},
error: function (response) {
console.log(response)
}
})
})
</script>
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
I use this light sortable plugin to sort my data by drag and drop
http://farhadi.ir/projects/html5sortable/
Now, how to update my sort order
$('.sortable').sortable().bind('sortupdate', function() {
//Triggered when the user stopped sorting and the DOM position has changed.
});
views.py
def filter_order(request):
if request.method == 'POST':
order = request.POST.getlist('filter[]')
count = 0
for id in order:
count += 1
filter = FilterModel().objects.get(pk=id)
filter.sort_order = count
filter.save()
return HttpResponse('Successfully updating rules order.')
else:
return HttpResponse("Error updating rules order.")
urls.py
urlpatterns = patterns('transactions.views',
............
url(r'^filter-order/$', 'filter_order',
name='filter_order'),
)
rules.html
<ul class="sortable" id="filter-items">
{% for filter in filters %}
<li id="{{ filter.id }}">{{filter.rules}}</li>
{% endfor %}
</ul>
<script>
$('.sortable').sortable().bind('sortupdate', function() {
datas = new Array();
var i = 0;
$('#filter-items li').each(function() {
datas[i] = $(this).attr('id');
i++;
});
$.ajax({
type: "POST",
data: {
'filter[]': datas,
'csrfmiddlewaretoken': '{{csrf_token}}'
},
url:"/transactions/filter-order/",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data) {
notify('', 'Successfully updating rules order.', { autoClose: true, delay: 1000 });
},
error: function(ts) {
notify('', ts.responseText, { autoClose: true, delay: 1000 });
}
});
});
</script>