Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Here is the relevant HTML, mostly a form copied from a file upload form:

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

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
like image 749
twoxmachine Avatar asked Oct 15 '25 19:10

twoxmachine


1 Answers

You're looking for ContentFile. It's a Django File subclass that instantiates with a string of text instead of a literal file. You can then save the ContentFile to your 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()
like image 186
Chris Pratt Avatar answered Oct 18 '25 09:10

Chris Pratt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!