to have autocompletion on an input,I do this:
in views.py:
def getpositions(request):
if request.is_ajax():
query = request.GET.get("term", "")
positions=Position.objects.filter(name__icontains=query)
results = []
for position in positions:
position_json={}
position_json['name']=position.name
results.append(position_json)
data=simplejson.dumps(results)
else:
data = 'error'
return HttpResponse(data, mimetype='application/json')
in template:
$(document).ready(function(){
$("#positions").autocomplete({
source: "{% url CompanyHub.views.getPositions%}",
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.name,
value: item.name
}
}));
},
minLength: 2,
});
});
and #positions is : <input type="text" id="positions" />
every thing is ok,but it just show Undefined instead of showing list of results,I tryed many things but no way!!
jQuery UI autocomplete doesnt have a success option you are using to format your data. Check the option list here http://jqueryui.com/demos/autocomplete/ . Instead You can use a callback function for source option and handle your own ajax call yourself and format data like you want.
$("#positions").autocomplete({
source: function( req,resp ) {
$.get("{% url CompanyHub.views.getPositions%}",
{term:req.term},function(data){
resp( $.map( data, function( item ) {
return {
label: item.name,
value: item.name
};
})
);
});
},
minLength: 2,
});
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 created a checkbox in each row of the table. After selecting multiple check boxes, click the Add Teacher button to add the currently logged in user name (request.user.first_name) to the 'teacher' field of the checked row. I succeeded in getting the id to the page with the table using ajax, but it keeps failing to add the field value of obejct(teacher field) at once. view.py needs to be edited, does anyone know how to fix it?
[urls.py]
path('/study/add_teacher/', views.add_teacher, name='add_teacher'),
path('/study/student/', views.student), ----> page with table
[views.py]
def add_teacher(request):
if request.method == 'POST':
ids = request.POST.getlist('chkArray')
for id in ids:
student = Student.objects.get(pk=id)
student.teacher = request.user.first_name
student.save()
return HttpResponseRedirect(f'/study/student/') ----> page with table
[stduent.js]
$(function () {
('button.addteacher').on('click',function () {
$checkbox = $('.Checked');
var chkArray = [];
var updateTeacher = confirm("업데이트하시겠습니까?");
chkArray = $.map($checkbox, function(el){
if(el.checked) { return el.id };
});
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
$.ajax({
type:'post',
url: '/study/add_teacher/',
headers: {"X-CSRFTOKEN": "{{ csrf_token }}"},
data:{
"chkArray" : chkArray.toString(),
"csrfmiddlewaretoken": "{{ csrf_token }}",
},
success:function(data){
console.log(chkArray);
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
});
});
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
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>