[英]How to save text input as a file in HTML and Django
I am building a site where users can input text and submit the text so that it can be saved and accessed as a file on the server. 我正在构建一个站点,用户可以在其中输入文本并提交文本,以便可以将其保存并作为服务器上的文件进行访问。 Unfortunately, I am not quite sure how I would take the inputted text and save it aas a file.
不幸的是,我不太确定如何将输入的文本保存为文件。
Could anyone point me in the right direction as to how I might do this or detail the steps I will have to take? 任何人都可以指出我正确的方向,如何做到这一点或详细说明我将采取的步骤? Preemptive apologizes if I have missed an obvious Google result.
如果我错过了明显的谷歌搜索结果,那就先发制人道歉。 Being somewhat new to Django, I may have inadvertently glossed over helpful resources.
对Django来说有点新鲜,我可能无意中掩盖了有用的资源。
Here is the relevant HTML, mostly a form copied from a file upload form: 这是相关的HTML,主要是从文件上传表单复制的表单:
<form name="myWebForm" id="submissionCode_codeEditor" action="uploadFile/" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="500" />
<input type="text" name="title" placeholder="File Name"/>
<input type="hidden" name="taskID" value={{ taskID }} />
<input type="submit" value="Submit This Code" />
</form>
Here is the relevant Django model: 这是相关的Django模型:
class Upload(models.Model):
title = models.CharField(max_length=50)
fileUpload = models.FileField(upload_to='file_uploads')
userID = models.ForeignKey(User)
task = models.ForeignKey(Task)
uploadTime = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
You're looking for ContentFile
. 您正在寻找
ContentFile
。 It's a Django File
subclass that instantiates with a string of text instead of a literal file. 它是一个Django
File
子类,用一串文本而不是文字文件进行实例化。 You can then save the ContentFile
to your FileField
. 然后,您可以将
ContentFile
保存到FileField
。
from django.core.files.base import ContentFile
content = ContentFile(some_text)
upload_instance.fileUpload.save('/path/to/where/file/should/save.txt', content)
upload_instance.save()
First of all create a file in your media folder using command, i am assuming user posted text with name content 首先使用命令在媒体文件夹中创建一个文件,我假设用户发布了带有名称内容的文本
from app.models import Upload
from django.conf import settings
content = request.GET("content")
file_object = open("%s/%s"%(settings.MEDIA_ROOT, filename),w) #Take file name as hash of content posted and username so that no class
upload = Upload(title=title, fileUpload=filename,user_id=request.user.id)
Your file is uploaded and can be acceseed using MEDIA_URL from settings 您的文件已上传,可以使用MEDIA_URL从设置中接收
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.