简体   繁体   English

如何创建csv文件并将其保存到以Django模型归档的文件中?

[英]How to create csv file and save to file filed in django model?

I'm using django csv ( https://docs.djangoproject.com/en/1.11/howto/outputting-csv/ ) and i want to save generated csv file to file field in below model 我正在使用django csv( https://docs.djangoproject.com/en/1.11/howto/outputting-csv/ ),我想将生成的csv文件保存到以下模型中的file字段中

class CsvDoc(models.Model):
    csv_file = models.FileField(
    upload_to="path")

For save this file you need to write down one function in views.py and then save the file. 要保存此文件,您需要在views.py中写下一个函数,然后保存该文件。 Code is below: 代码如下:

def upload_file(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/url/')
    else:
        form = UploadFileForm()
    return render_to_response('file.html', {'form': form})

where UploadForm is a form class and you need to write down that in forms.py file: 其中UploadForm是一个表单类,您需要将其记录在forms.py文件中:

class UploadForm(forms.ModelForm):
class Meta:
    model = CsvDoc

And in file.html: 并在file.html中:

<form enctype="multipart/form-data" action="/file/" name="test" method="post">
{% csrf_token %}
{{form.as_p}}
<input id="formSubmit" type="submit" value="Submit">

Try this, and tell me that it is works fine or not. 试试这个,告诉我它是否正常。 Thanks. 谢谢。

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

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