将数据从CSV文件存储到数据库中 [英] Storing Data from a CSV File into a database

查看:70
本文介绍了将数据从CSV文件存储到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旅馆的Django模型,其中有一个字段FileUpload,将从中获取CSV文件并填充数据库,过去两天我一直在尝试搜索操作方法,但无法正常工作这个如何将csv数据导入django模型的问题是可行的,但是仅当我具有文件的路径,并且尝试了多种方法但未成功时.同样在那之后,我尝试更难地搜索在Django中上传后如何获得文件的绝对路径?我看到了,但即使这样我仍然无法正常工作,因为它显示了一些错误

I have a Django model of a hostel with one of the field FileUpload from which I will take a CSV file and populate the database, I have been trying for past two days searching how to do that, but could not get that working This how to import csv data into django models question works but only if I have the path for the file, and I tried many ways but were not successful. Also after that I tried searching harder How do I get a files absolute path after being uploaded in Django? I saw this but even then I could not get it working as it shows some errors

我使用了此URL映射 url(r'^ test/$',views.FileUpload.as_view(),name ="test")

I used this URL mapping url(r'^test/$',views.FileUpload.as_view(),name="test")

但是它显示了一些名称空间错误.请告诉我我应该怎么做,如果您对我有一些建议,我应该如何重新开始,我感到很迷失.我想从用户那里获取一个文件,然后填充数据库

But it is showing some namespace error. Please tell me how should I do it, if you have some suggestions to me how should I start again, I am feeling really lost. I want to get a file from a user and then populate the database

这可以吗(

Can this(How do I transfer data in .csv file into my sqlite database in django?) be made like we could create a form with a filefield that accepts csv and then populating the database by parsing that, Problem in that is we could not hard code the path. So how should we do that.

编辑 views.py

from django.views import View
class FileUpload(View):
    def post(self, request):
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            initial_obj = form.save(commit=False)
            data=initial_obj['document']
            with open((data),'rb') as csvfile:
                spamreader = csv.reader(csvfile)
                for row in spamreader:
                    _, created=Document.objects.get_or_create(
                    name=row[0],
                    description = row[1],
                    importance=row[2],
                    )

            initial_obj.save()
            form.save()
            return redirect('/')
        else:
            return render(request,'file_upload_form.html',{'form':form})

    def get(self, request):
        return render(request, 'file_upload_form.html', {'form': form,})

forms.py

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('description', 'document', )

models.py

class Document(models.Model):
    name=models.CharField(max_length=50,blank=True)
    description=models.CharField(max_length=255, blank=True)
    importance=models.CharField(max_length=10, default="High")
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.description

我没有收到任何错误,但是它没有将CSV文件中的数据保存到数据库中,而是将我重定向到必须执行上载的同一页面,并在文档字段中显示错误此字段是必需的".

I am not getting any errors but it is not saving data in the database from the CSV file and redirects me to the same page where uploading has to be done and shows the error "This field is required" for the document field.

更新:我在此处

推荐答案

您可以轻松覆盖表单的 clean()方法,并将自定义数据内容保存到数据库中

You can easily override the clean() method of your form, and save your custom data content into database

 def clean(self):
    super(DocumentForm, self).clean()
    import csv
    with open((self.cleaned_data['file']), 'rb') as csvfile:
    spamreader = csv.reader(csvfile)
    for row in spamreader:
        // DO WHATEVER YOU WANT

这篇关于将数据从CSV文件存储到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆