场景:用户上传CSV文件,并在后端将CSV保存为文件。现在,我正在尝试将那些csv文件以表格式保存在数据库中。当csv保存数据库时,它将显示类似pandas dataframe的数据。
我已经看到了django-import-export之类的一些软件包。但这不是我想要的。最主要的是,在该程序包中,在上传文件之前先创建模型。但是我不会在用户上传文件之前创建模型。
这是我的django代码。
model.py
from django.db import models
# Create your models here.
from django.db import models
# Create your models here.
class DataUpload(models.Model):
fileId = models.AutoField(primary_key=True)
data_upload = models.FileField(upload_to='files/')
class Meta:
db_table = 'DataUpload'
forms.py
from django import forms
from .models import DataUpload
class PostForm(forms.ModelForm):
class Meta:
model = DataUpload
fields = ['data_upload']
urls.py
from django.urls import path
from .views import dataview , FileView, ResultView
# from .views import BonolothaDataView
urlpatterns = [
path('', dataview.as_view()),
path('fileview/', FileView.as_view(), name='fileview'),
path('result/', ResultView.viewResult, name='result'),
# path('bonolotha/', BonolothaDataView.as_view(), name='bonolotha'),
]
views.py
class dataview(View):
model = DataUpload
form_class = PostForm
initial = {'key': 'value'}
template_name = 'post.html'
fileview_url = reverse_lazy('fileview')
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial) # pribt html form
return render(request, self.template_name, {'form':form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST, request.FILES)
context = {
'form': form,
}
if form.is_valid():
form.save()
return redirect(self.fileview_url)
else:
form = self.form_class()
return render(request, self.template_name, context)