Я создаю представление, которое добавляет данные из файла. fucntion отправит обратно два словаря один с данными для сохранения и один с данными об ошибках
Я бы хотел отсылать обратно в шаблон ошибки только при наличии ошибок.
спасибо за помощь
Мой реальный код отправляет мне сообщение об ошибке: отменить для 'importXLS.views.import_choices' с аргументами '([' miss .....
urls.py
path('import_choices/', views.import_choices, name='import-choices'),
# views function
url(r'^data_upload_coa$', views.data_upload_coa, name='data_upload_coa'),
view.py
def data_upload_coa(request): # importing chart of account
if request.method == 'POST':
# Get the form data from the request.
company = request.POST.get('company')
excel_file = {}
excel_file = request.FILES["excel_file"]
# return two dictionnaries from coa
accounts, errors = parse_coa(excel_file)
# Add accounts to chart of accounts table
for account in accounts:
# Create a new record with the data if does not exists before.
upload_data = ChartOfAccount.objects.get_or_create(
field_account=account['field_account'],
field_account_libaccount=account['field_account_libaccount'],
field_type=account['field_type'],
field_subtype=account['field_subtype'],
)
# company=company, TO BE ADDED WHEN DEVELOPPING MULTI FIRMS DATA
# Add save success message
messages.success(request, 'Chart of accounts updated')
test = len(errors)
if test == 0:
return redirect(import_choices)
else:
return redirect(import_choices, errors)
else:
# error message
messages.info(request, 'Uploading error')
return redirect(import_choices)
import_choice.html
{% extends 'layouts/base.html' %}
{% load bootstrap3 %}
{% block title %}Import Choices{% endblock %}
{% block heading %}<h3 class="page-header-center">File to import</h3>
{% endblock %}
<hr>
<hr>
{% block page %}
<script> // logic for validation of file
var _validFileExtensions = [".xlsx", ".xls"];
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
</script>
<script> // Recupere le path du fichier
var file = document.getElementById("upload");
file.addEventListener("change", function() {
for (var i = 0; i < file.files.length; i++) {
console.log(file.files[i].name);
}
}, false);
</script>
</br>
</br>
<div class="container">
<div class="panel-heading">
<h4 class="panel-title col-md-6">Please choose a type of file to import:</h4>
</div>
</br>
</br>
<!----------------Accordeon ----------------->
<div class="panel-group col-md-6" id="Choices" >
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" data-target="#Choice-COA" data-toggle="collapse" data-parent="#Choices">Chart of Accounts</h3>
</div>
<!--accordeon part 1 -->
<div class="panel-collapse collapse" id="Choice-COA">
<div class="panel-body">
<div class="row col-md-4" >
<form method="POST" action="{% url 'data_upload_coa' %}" method="post" id="fileupload" name="fileupload" enctype="multipart/form-data" data-ajax="false" onsubmit="return Validate(this);">
{% csrf_token %}
<table class="table">
<tr>
<td>
<input type="text" placeholder="Enter Company Name " name="company" id="company" required>
</td>
</br>
<td>
<input type="file" title="Upload excel file" name="excel_file" id="myfile" required="required">
</br>
<button type="submit" class="btn btn-primary btn-sm pull-right">Upload</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</br>
<!--accordeon part 2 -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" data-target="#import-bv" data-toggle="collapse" data-parent="#Choices">Balance of verification</h3>
</div>
<div class="panel-collapse collapse" id="import-bv">
<div class="panel-body">
<p>To be complete Balance of verification
test</p>
</div>
</div>
</div>
</div>
Результат должен быть:
Если словарь с ошибками пуст, вернитесь к import_choice.html
Если нет
вернитесь к import_choice.html со списком ошибок, отображаемым