0

I have a Django model with a TextField. When I use a ModelForm to collect data to add/edit this model, I get a textarea in the HTML form, but I'd like to use a file input instead.

I think what I need to do is to set the widget for this field on my form class using django.forms.FileInput, or maybe a subclass of that input, but it isn't clear to me how to make this work (and I'm not positive this is the right approach).

So, how can I use a file input to collect data for a model using a ModelForm?

Crag
  • 1,723
  • 17
  • 35
  • Why don't you just use a FileField() in the model? – art Jan 17 '19 at 07:35
  • @art06 Because a FileField wouldn't get the text replicated across databases- it uses the file system for the file and a reference to it in the database. – Crag Jan 22 '19 at 16:23
  • Have you seen https://stackoverflow.com/questions/4915397/django-blob-model-field ? – art Jan 23 '19 at 00:20

1 Answers1

1

Here's what I came up with, elided and condensed for succinctness:

from django.contrib.gis.db.models import Model, TextField
from django import forms

class Recipe(Model):
    source = TextField(null=False, blank=True)
    ...

class AsTextFileInput(forms.widgets.FileInput):
    def value_from_datadict(self, data, files, name):
        return files.get(name).read()

class RecipeForm(forms.ModelForm):
    class Meta:
        model = Recipe
        fields = ('source', ...)
        widgets = {'source': AsTextFileInput(), ...}
Crag
  • 1,723
  • 17
  • 35