简体   繁体   English

将数据从CSV文件存储到数据库中

[英]Storing Data from a CSV File into a database

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. 我有一个宿舍的同场的FileUpload从中我会采取一个CSV文件,并填充数据库之一的Django模型,我一直在试图为过去两天搜索如何做到这一点,但不能让该工作该如何导入csv数据到django模型中,问题是可行的,前提是我只有文件的路径,并且尝试了多种方法但未成功。 Also after that I tried searching harder How do I get a files absolute path after being uploaded in Django? 此外,在此之后,我尝试更努力地搜索, 在Django中上传后如何获得文件的绝对路径? I saw this but even then I could not get it working as it shows some errors 我看到了这个,但是即使那样我仍然无法正常工作,因为它显示了一些错误

I used this URL mapping url(r'^test/$',views.FileUpload.as_view(),name="test") 我使用了此URL映射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. 这样( 我如何将.csv文件中的数据传输到Django的sqlite数据库中? )是否可以像我们可以创建一个带有接受csv的文件字段的表单,然后通过解析该表单来填充数据库那样,问题在于我们无法硬编码路径。 So how should we do that. 那么我们该怎么做。

EDIT views.py 编辑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 forms.py

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

models.py 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

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

Updates : I solved the problem more details here 更新 :我在这里解决了更多问题

You can easily override the clean() method of your form, and save your custom data content into database 您可以轻松地覆盖表单的clean()方法,并将自定义数据内容保存到数据库中

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM