【发布时间】:2017-11-14 01:26:46
【问题描述】:
我正在尝试创建一个使用 CSV 数据的 django Web 应用程序。我创建了一个 django 模型来容纳来自这些 csv 的数据,我已经将所有 csv 存储在 STATIC_ROOT 中。当我加载页面时,调用的模板(datalandingpage.html)加载没有问题。但是,当我检查 django admin 时,没有导入任何 CSV。如果我猜测,我认为缺点与 django 无法找到文件有关(虽然我只是猜测,但我很可能是错误的,因为我是一个相对较新的开发人员)。以下是我尝试编写的所有相关代码。
编辑:所以看起来我的视图函数可能会直接跳到渲染部分,这可能是我在运行时看不到任何错误的原因。关于为什么会出现这种情况的任何想法?
settings.py:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/data')
models.py:
from __future__ import unicode_literals
from django.db import models
from django.contrib import admin
class Data(models.Model):
# A bunch of model objects (CharField/IntegerFields mainly)
class Meta:
verbose_name_plural = 'Data Sets'
def __str__(self):
return self.someobject
views.py:
from __future__ import unicode_literals
from django.conf import settings
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from .models import Data
import csv
import os
def landing(request):
# Opens all csv files in specified directory
directory = os.path.join(settings.STATIC_ROOT)
for files in os.walk(directory):
for file in files:
if file.endswith(".csv"):
f = open(file, 'r')
reader = csv.reader(f)
#Checks the rows/columns and tries to find the specified string that marks the start of data
for i, row in enumerate(reader):
target_string = "Some string in the CSV"
if target_string in row:
target_row = i
return target_row
break
#Checks the rows/columns and tries to find the specified string that marks the end of data
for j, row in enumerate(reader):
end_target_string = "Another string in the CSV"
if end_target_string in row:
end_target_row = j
return end_target_row
break
#Begins parsing the csv, but skips until two rows past the target beginning string
for k, row in enumerate(reader):
#imports csv data when the row number is between target string and target end string
if k >= (target_row + 2):
row = row.split(',')
DataSource = Data.objects.create()
DataSource.someobject1 = row[0]
DataSource.someobject2 = row[1]
DataSource.save()
# When the parse gets to the row with the end string, it closes the file.
elif k >= end_target_row:
reader.close()
break
# Prints something if the file isn't a csv file
else:
print "This isn't a csv file"
return render(request, "Data/datalandingpage.html")
【问题讨论】:
-
在执行视图时是否看到任何错误?返回的状态码是什么?我在那里看到了一些错误,据我所知,这些错误应该会导致一些问题。
-
@sytech 我在执行视图时没有看到任何错误,只有状态码 200。所以我做了一些工作,可能函数只是跳到渲染部分。知道为什么会这样吗?
标签: python django csv django-models