Django: из загруженного файла с помощью models.FileField создать визуализацию данных
В моем проекте пользователь может загрузить стандартный файл excel благодаря models.FileField. Файл выглядит примерно так:
total partial [...]
user 10 4
other 18 6
С помощью этой информации я хотел бы создать график и графику, используя Chart.js, которые сравнивали бы информацию от пользователя и другого человека, а затем показать их пользователю на html-странице для каждого загруженного файла, конечно. Итак, мой план состоит в том, чтобы прочитать файл excel с помощью openpyxl и создать переменную для создания графика в цикле. Хороший ли это подход? Вот мой код сейчас, и я получаю эту ошибку 'tuple' object has no attribute 'append'
:
MODELS
class Document(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
docfile = models.FileField()
def __str__(self):
return self.docfile
'tuple' object has no attribute 'append'
VIEWS
import from openpyxl import load_workbook
def upload_file(request):
message = 'Upload as many files as you want!'
row = []
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
wb = load_workbook(filename=request.FILES['docfile'].file)
sheet = wb.active
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
for row in sheet.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True):
for cell in row:
row.append(cell)
return redirect('upload_file')
else:
message = 'The form is not valid. Fix the following error:'
else:
form = DocumentForm()
documents = Document.objects.filter(user=request.user.userinformation).all()
context = {
'documents': documents,
'form': form,
'message': message,
'row': row
}
return render(request, 'list.html', context)
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
All documents in the database:
<ul>
{% for document in documents %}
<li><a href="{{ document.docfile.url }}">{{ document.docfile.name }} </a></li>
<div class="size">{{document.docfile.size|filesizeformat}}</div>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<form action="{% url "upload_file" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p><input type="submit" value="Upload"/></p>
</form>
</body>
</html>
{% endblock %}
Также файлы имеют всего две строки, но что-то около 80 столбцов, которые описывают различные категории (время, длина, размер...) и я задался вопросом, было бы разумно (и возможно) работать в excel файле в другой функции. Что-то вроде этого:
def cell_categories(request):
row_time = []
row_size = []
#select the data about the time
for row in sheet.iter_rows(min_row=5, max_col=29, max_row=6, values_only=True):
for cell in row:
row_time.append(cell)
#select the data about the size
for row in sheet.iter_rows(min_row=30, max_col=33, max_row=31, values_only=True):
for cell in row:
row_size.append(cell)