Michael
Michael

Reputation: 1058

How to store a file as a string in a model text field?

I am pretty new to Django. I need some help.

I am working on an admin page that allows me to edit objects. My model has a text field that I want to fill with a file contents which will be uploaded with a FileInput widget in a form.

So I want to read the file contents, put it in a string and store it in the model text field. Therefore it should be saved in the database.

Any help with this? I dont know how to get the file , read it and store it in my model as string. I am using a ModelAdmin btw.

Upvotes: 0

Views: 1061

Answers (1)

Doug Dresser
Doug Dresser

Reputation: 154

First off, you might want to just use a model.FileField (https://docs.djangoproject.com/en/2.0/ref/models/fields/#filefield). The database only has to store a path to the file, instead of the entire contents of the file. You might not want to store the contents of a file directly in the database, especially if its a large file.

But if you do want to read a file in to your model. Try something along the lines of:

models.py

class SomeModel(Model):
    textfield = TextField()

views.py or whatever script you are calling

with open('data.txt', 'r') as myfile:
    data=myfile.read()
newmodel = SomeModel()
newmodel.textfield = data
newmodel.save()

Upvotes: 1

Related Questions