Expand the Textarea of the TextField in Admin

Django
2011-06-11 01:17 (13 years ago) ytyng

Here's the English translation of the provided Japanese blog article:


When working with Django models,

from django.db import models

class Article(models.Model):
    text = models.TextField()

and you view the Django Admin management site, you will see HTML output like <textarea .... rows="10" ... .

If you want to change the value of the rows attribute, you can do so in admin.py like this:

# -*- coding: utf-8 -*-

from django.contrib import admin
from blog.models import Article, Category
from django.db import models

from django import forms
class AdminTextareaWidgetLarge(forms.Textarea):
    def __init__(self, attrs=None):
        final_attrs = {'class': 'vLargeTextField', 'rows': 40}
        if attrs is not None:
            final_attrs.update(attrs)
        super(AdminTextareaWidgetLarge, self).__init__(attrs=final_attrs)

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

admin.site.register(Article, ArticleAdmin)

You can create a new widget like this and put it into formfield_overrides.

If possible, I would like to achieve this by defining only 'rows': 40 somewhere, but I couldn’t figure out how to do it.

There's also the option of directly rewriting django.forms.widgets.Textarea, but that’s not a good idea.


Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011