41

I managed to override the look of a TextArea Widget in the django admin interface with two different ways:

using formfield_overrides

in admin.py:

class RulesAdmin(admin.ModelAdmin):
formfield_overrides = {
    models.TextField: {'widget': Textarea(
                       attrs={'rows': 1,
                              'cols': 40})},
}

...
admin.site.register(Rules, RulesAdmin)

This way is a bit of an overkill, since it will change all the TextField for that model.

with a custom form:

in forms.py:

from django.forms import ModelForm, Textarea
from TimePortal.models import Rules


class RulesModelForm(ModelForm):
    class Meta:
        model = Rules
        widgets = {
            'parameters': Textarea(attrs={'cols': 30, 'rows': 1}),
   }

in admin.py

from AppName.forms import RulesModelForm

class RulesAdmin(admin.ModelAdmin):

    form = RulesModelForm

Both solutions resize the TextArea. However in both solutions the actual size of the text area is more than 1 row (actually 2 rows). Here is how the rendered HTML looks like:

    <div class="form-row field-parameters">
            <div>
                <label for="id_parameters" class="required">Parameters:</label>
                <textarea id="id_parameters" rows="1" cols="30" name="parameters">{}</textarea> 
           <p class="help">Enter a valid Python Dictionary</p>
         </div>
    </div>

And here is a screentshot:

Form

According to W3C referecnce for text area:

The size of a textarea can also be specified by the CSS height and width properties.

So, my questions are:

  • Is django's own css theme is the responsible here for the "odd" behavior of this widget?
  • Can some suggest a way to solve this issue?
4

1 回答 1

48

This is a browser-specific problem.

According to the thread Height of textarea does not match the rows in Firefox:

Firefox always adds an extra line after the textfield. If you want it to have a constant height, use CSS ...

You can set a style attribute of the textarea:

from django.db import models
from django.forms import Textarea

class RulesAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.TextField: {'widget': Textarea(
                           attrs={'rows': 1,
                                  'cols': 40,
                                  'style': 'height: 1em;'})},
    }

Works for me - tested on Firefox v. 23 and Chrome v. 29.

Hope that helps.

于 2013-09-11T10:27:53.490 回答