Control the Size Textarea Widget Look in Django Admin

Control the size TextArea widget look in django admin

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.

Using formfield_overrides to change textarea size in admin.TabularInline Form in Django

Yes, just use the same code in the corresponding Inline class,

Admin.py

YourInline(admin.TabularInline):

formfield_overrides = {
models.TextField: {'widget': Textarea(attrs={'rows':2, 'cols':25})},
}
...

Customizing size of django admin portal text fields

You have to modify your admin.py :

  1. import the forms class
  2. define a new forms.Textarea
  3. in your ModelAdmin class, override the form field

for example if you only want 1 row in your text area :

class RichTextEditorWidget(forms.Textarea):
def __init__(self, *args, **kwargs):
attrs = kwargs.setdefault('attrs', {})
attrs.setdefault('cols', 60)
attrs.setdefault('rows',1)

super(RichTextEditorWidget, self).__init__(*args, **kwargs)

class YourModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget' : RichTextEditorWidget},
}

admin.site.register(YourModel, YourModelAdmin)

https://docs.djangoproject.com/en/3.2/topics/forms/

Resize fields in Django Admin

You should use ModelAdmin.formfield_overrides.

It is quite easy - in admin.py, define:

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

class YourModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size':'20'})},
models.TextField: {'widget': Textarea(attrs={'rows':4, 'cols':40})},
}

admin.site.register(YourModel, YourModelAdmin)

How to customize a specific TextField inside the Django admin not all?

Add the following code to forms.py

from django.forms import ModelForm, Textarea
from .models import Lesson

class PostModelForm(ModelForm):

class Meta:
model = Lesson
fields = ('__all__')
widgets = {
'meta': Textarea(attrs={'cols': 80, 'rows': 5}),
}

and in admin.py do this

class PostModel(admin.ModelAdmin):
list_display = ('id', 'title', 'pub_date', 'course',)
search_fields = ('title', 'course__alias',)

form = PostModelForm


Related Topics



Leave a reply



Submit