Я создаю записи моей модели School
по шаблону.
Проблема в том, что на странице не отображаются элементы, созданные после нажатия кнопки "Отправить". Я должен сделать refre sh, чтобы показать новые объекты в шаблоне. почему?
urls.py:
path('escuelas-csv/', views.schools_upload, name="schools_upload"),
views.py:
### Read CSV file to create records ###
import csv, io
from django.shortcuts import render
from django.contrib import messages
def schools_upload(request):
template = "scolarte/escuelas/escuelas.html"
data = School.objects.all()
prompt = {
'orden': 'El orden de las columnas del archivo CSV debe ser: escuela, direccion, referencia, provincia, cantón, parroquia',
'escuelas': data
}
if request.method == "GET":
return render(request, template, prompt)
csv_file = request.FILES['file']
if not csv_file.name.endswith('.csv'):
messages.error(request, 'El archivo no es un archivo CSV')
data_set = csv_file.read().decode('iso-8859-1')
io_string = io.StringIO(data_set)
next(io_string)
for column in csv.reader(io_string, delimiter=',', quotechar="|"):
_, created = School.objects.update_or_create(
name=column[0],
address=column[1],
address_reference=column[2],
provincia=column[3],
canton=column[4],
parroquia=column[5],
)
context = {}
return render(request, template, context)
html: scolarte/escuelas/escuelas.html
{% block content %}
{% if messages %}
{% for message in messages %}
<div>
<!-- | means OR operator-->
<strong>{{message|safe}}</strong>
</div>
{% endfor %}
{% else %}
<h1>Creación de escuelas</h1>
<p>{{orden}}</p>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label for="file1">Subir archivo</label>
<input type="file" id="file1" name="file"><br>
<small>Solo se aceptan CSV files</small>
<button type="submit">Crear escuelas</button>
</form>
{% endif %}
<h3> Escuelas disponibles </h3>
<table class="tg margin-top5">
<tr>
<th class="tg-0pky">Escuela</th>
<th class="tg-0pky">Dirección</th>
<th class="tg-0pky">Provincia</th>
<th class="tg-0pky">Fecha de creación</th>
</tr>
{% for escuela in escuelas %}
<tr>
<td class="tg-0pky">{{escuela.name}}</td>
<td class="tg-0pky">{{escuela.address}}</td>
<td class="tg-0pky">{{escuela.provincia}}</td>
<td class="tg-0pky">{{escuela.created_at}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}