#javascript #python #html #django
#javascript #питон #HTML #джанго
Вопрос:
У меня возникли проблемы, почему это продолжает говорить мне
Неперехваченная ошибка синтаксиса: отсутствует) после списка аргументов
У меня есть список, и я хочу получить его, перейдя в javascript. Кто-нибудь знает, в чем проблема? Пожалуйста, помогите мне. Вот как это выглядит:
views.py
:
def sample(request):
getlist = request.POST.getlist('batch[]')
format = {'list': getlist}
return render(request,'sample.html', format)
sample.html
:
{% if list %}
<button type="button" id="reports_btn" class="btn btn-secondary round btn-min-width mr-1 mb-1" onClick = "reports('{{list}}')" >sample</button>
{% endif %}
javascript:
function reports (list) {
console.log(list)
}
Обновлена моя функция views.py
:
@login_required(login_url='log_permission')
def sap_payroll(request):
classifications = Person.objects.all().values('classification').distinct()
category = Person.objects.all().values('category').distinct()
payroll_batch = Person.objects.all().values('payroll_batch').distinct()
batch_it = Person.objects.all().values('batch_it').distinct()
paid = Person.objects.all().values('paid').distinct()
type_payout = Person.objects.all().values('type_payout').distinct()
paid_with = Person.objects.all().values('paid_by').distinct()
province = request.POST.get('province', False)
municipality = request.POST.get('municipality', False)
barangay = request.POST.get('barangay', False)
payout_type = request.POST.get('type_payout', False)
status = request.POST.get('stats', False)
dte_from = request.POST.get('dte_from', None)
dte_to = request.POST.get('dte_to', None)
getlist = request.POST.getlist('batch[]')
if request.method=='POST':
shes = ['1','2'] # sample testing
print("doda")
print(type_payout)
if getlist and dte_from and dte_to :
user_list = Person.objects.filter(date_receive__range=[dte_from, dte_to] , payroll_batch__in = getlist )
bene = UserFilter(request.POST, queryset=user_list)
elif getlist:
user_list = Person.objects.filter(payroll_batch__in = getlist)
bene = UserFilter(request.POST, queryset=user_list)
elif dte_from and dte_to:
user_list = Person.objects.filter(date_receive__range=[dte_from, dte_to])
bene = UserFilter(request.POST, queryset=user_list)
else:
user_list = Person.objects.all()
bene = UserFilter(request.POST, queryset=user_list)
countsa = bene.qs.count()
total_amount =bene.qs.aggregate(Sum('amount')).get("amount__sum")
citys ="CITY OF"
formats = {'benefeciaries':bene,'municipal':municipality,'province':province,'barangay':barangay,'total':countsa,'amount':total_amount,'cities':citys,'classification':classifications,'category':category,'payroll_batch':payroll_batch,'batch_it':batch_it,'paid':paid,'type_payout':type_payout,'paid_with':paid_with,'payout_type':payout_type,'shes':shes}
return render(request, 'payroll.html', formats)
else:
lists = ['1','2'] #samplee testing
user_list = Person.objects.all()
bene = UserFilter(request.GET, queryset=user_list)
countsa = bene.qs.count()
formats = {'benefeciaries':bene,'classification':classifications,'category':category,'payroll_batch':payroll_batch,'batch_it':batch_it,'paid':paid,'type_payout':type_payout,'paid_with':paid_with,'payout_type':payout_type,'shes':shes}
return render (request,'payroll.html',formats)
payroll.html
(Не могу опубликовать все, так как оно слишком длинное):
{% if municipal or province or barangay or payout_type or shes %}
<button type="button" id="reports_btn" class="btn btn-secondary round btn-min-width mr-1 mb-1" onClick = "reportss('{{municipal}}','{{province}}','{{barangay}}','{{payout_type}}','{{shes|safe}}')" >Reports</button>
<button type="button" id="remarks_v2" class="btn btn-secondary round btn-min-width mr-1 mb-1" >Amount/Remarks</button>
{% endif %}
Мой javascript:
function reportss (municipal,province,barangay,payout_type , list ) {
console.log(municipal province barangay)
console.log(list) //this is list to pass
if (barangay==""){
$.ajax({
url: "{% url 'reports' %}",
data: {
'id': municipal,
'prov':province,
'barangay':barangay,
'mun': municipal,
'p_type': payout_type
},
success: function(response){
document.getElementById("total_paidss").innerHTML = response.paid;
document.getElementById("total_unpaidss").innerHTML = response.unpaid;
document.getElementById("total_amounts").innerHTML = response.amount;
document.getElementById("total_counts").innerHTML = response.counts;
document.getElementById("paid_total_amount").innerHTML = response.paid_total_amount;
document.getElementById("unpaid_total_amount").innerHTML = response.unpaid_total_amount;
$("#rports").modal('show');
$("#rports").val(null).trigger("change");
}
});
}
else {
console.log("else")
console.log(municipal)
$.ajax({
url: "{% url 'reports' %}",
data: {
'id': municipal,
'prov':province,
'barangay':barangay,
'mun': municipal,
'p_type': payout_type
},
success: function(response){
document.getElementById("total_paidss").innerHTML = response.paid;
document.getElementById("total_unpaidss").innerHTML = response.unpaid;
document.getElementById("total_amounts").innerHTML = response.amount;
document.getElementById("total_counts").innerHTML = response.counts;
document.getElementById("paid_total_amount").innerHTML = response.paid_total_amount;
document.getElementById("unpaid_total_amount").innerHTML = response.unpaid_total_amount;
$("#rports").modal('show');
$("#rports").val(null).trigger("change");
}
});
}
}
Комментарии:
1. Я предлагаю вам вывести значение
getlist
на консоль. Python использует одинарную кавычку char ('
) в строковых представлениях массива, поэтому может возникнуть конфликт, потому что вы тоже его используете. Но я не уверен, что вам{{list}}
вообще нужны цитаты.2. Можете ли вы предоставить дополнительную информацию? Это очень неясно.
3. @Shayan ссылка , у меня есть это
4. @Shayan Я не знаю, почему он продолжает сообщать мне об отсутствии (и теперь я попробовал фиктивный список, но всегда появляется ошибка) возможно, моя ошибка в этой строке?
getlist = request.POST.getlist('batch[]')
5. @HannahMae,
request.POST.getlist()
возвращает список. Вы передаете списокformat()
функции, которая будет вызыватьсяrepr()
для получения строкового представления. В вашем шаблоне вы передаете все аргументы в виде строк, но здесь вы получили синтаксическую ошибку, потому что строковое представление списка содержит одинарные кавычки, и вы также используете одинарные кавычки в своем js.