views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
import tkinter as tk
import pandas as pd
from io import StringIO
from .forms import TextAreaForm
from .models import MyData
def index(request):
return render(request, 'travel/index.html')
def test(request):
if request.method == 'POST':
form = TextAreaForm(request.POST)
if form.is_valid():
data = form.cleaned_data['text']
df = pd.read_csv(StringIO(data), sep='\t')
empty_df = df.empty
# データベースに取り込む
for index, row in df.iterrows():
imported_data = MyData()
for i in range(len(row)):
setattr(imported_data, f'column{i+1}', row[i])
imported_data.save()
else:
form = TextAreaForm()
df = pd.DataFrame()
empty_df = df.empty
context = {'form': form, 'df': df, 'empty_df': empty_df}
return render(request, 'travel/test.html', context)
test.html
{% extends 'travel/base.html' %}
{% block content %}
{% load static %}
Import Data
{% csrf_token %} {{ form.as_p }} Import{% if not empty_df %}
{{ column }} | {% endfor %}
---|
{{ value }} | {% endfor %}
{% endblock %}
``
{% extends 'travel/base.html' %}
{% block content %}
{% load static %}
{% extends 'travel/base.html' %}
{% block content %}
{% load static %}
Import Data
{% csrf_token %} {{ form.as_p }} Import{% if not empty_df %}
{{ column }} | {% endfor %}
---|
{{ value }} | {% endfor %}
{% endblock %}
``
forms.py
from django import forms
class TextAreaForm(forms.Form):
text = forms.CharField(widget=forms.Textarea(attrs={'rows': 10}))