0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ddjango データをdbにインポート

Last updated at Posted at 2023-04-15

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 %}

{% for column in df.columns %} {% endfor %} {% for index, row in df.iterrows %} {% for value in row %} {% endfor %} {% endfor %}
{{ column }}
{{ value }}
{% endif %}

{% 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 %}

{% for column in df.columns %} {% endfor %} {% for index, row in df.iterrows %} {% for value in row %} {% endfor %} {% endfor %}
{{ column }}
{{ value }}
{% endif %}

{% endblock %}
``

forms.py

from django import forms

class TextAreaForm(forms.Form):
text = forms.CharField(widget=forms.Textarea(attrs={'rows': 10}))

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?