简体   繁体   中英

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

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. 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:

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

And in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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