Crag
Crag

Reputation: 1841

Use a file input for a text field?

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?

Upvotes: 0

Views: 887

Answers (1)

Crag
Crag

Reputation: 1841

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(), ...}

Upvotes: 1

Related Questions