109π
You will have to create a forms.ModelForm
that will describe how you want the descr
field to be displayed, and then tell admin.ModelAdmin
to use that form. For example:
from django import forms
class CabModelForm( forms.ModelForm ):
descr = forms.CharField( widget=forms.Textarea )
class Meta:
model = Cab
class Cab_Admin( admin.ModelAdmin ):
form = CabModelForm
The form
attribute of admin.ModelAdmin
is documented in the official Django documentation. Here is one place to look at.
67π
For this case, the best option is probably just to use a TextField instead of CharField in your model. You can also override the formfield_for_dbfield
method of your ModelAdmin
class:
class CabAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(CabAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'descr':
formfield.widget = forms.Textarea(attrs=formfield.widget.attrs)
return formfield
- [Django]-Django test runner not finding tests
- [Django]-How to go from django image field to PIL image and back?
- [Django]-Effects of changing Django's SECRET_KEY
36π
Ayaz has pretty much spot on, except for a slight change(?!):
class MessageAdminForm(forms.ModelForm):
class Meta:
model = Message
widgets = {
'text': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
}
class MessageAdmin(admin.ModelAdmin):
form = MessageAdminForm
admin.site.register(Message, MessageAdmin)
So, you donβt need to redefine a field in the ModelForm to change itβs widget, just set the widgets dict in Meta.
- [Django]-How to manage local vs production settings in Django?
- [Django]-Django migration strategy for renaming a model and relationship fields
- [Django]-How to format time in django-rest-framework's serializer?
23π
You donβt need to create the form class yourself:
from django.contrib import admin
from django import forms
class MyModelAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
kwargs['widgets'] = {'descr': forms.Textarea}
return super().get_form(request, obj, **kwargs)
admin.site.register(MyModel, MyModelAdmin)
See ModelAdmin.get_form.
- [Django]-How can I access environment variables directly in a Django template?
- [Django]-Django: Get an object form the DB, or 'None' if nothing matches
- [Django]-Error: No module named staticfiles
14π
You can subclass your own field with needed formfield
method:
class CharFieldWithTextarea(models.CharField):
def formfield(self, **kwargs):
kwargs.update({"widget": forms.Textarea})
return super(CharFieldWithTextarea, self).formfield(**kwargs)
This will take affect on all generated forms.
- [Django]-Sending HTML email in django
- [Django]-Does SQLAlchemy have an equivalent of Django's get_or_create?
- [Django]-How to debug Django commands in PyCharm
8π
If you are trying to change the Textarea on admin.py, this is the solution that worked for me:
from django import forms
from django.contrib import admin
from django.db import models
from django.forms import TextInput, Textarea
from books.models import Book
class BookForm(forms.ModelForm):
description = forms.CharField( widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}))
class Meta:
model = Book
class BookAdmin(admin.ModelAdmin):
form = BookForm
admin.site.register(Book, BookAdmin)
If you are using a MySQL DB, your column length will usually be autoset to 250 characters, so you will want to run an ALTER TABLE to change the length in you MySQL DB, so that you can take advantage of the new larger Textarea that you have in you Admin Django site.
- [Django]-Combining Django F, Value and a dict to annotate a queryset
- [Django]-Django β Overriding the Model.create() method?
- [Django]-Token Authentication for RESTful API: should the token be periodically changed?
- [Django]-Jquery template tags conflict with Django template!
- [Django]-How to debug in Django, the good way?
- [Django]-How to add data into ManyToMany field?
5π
You can use models.TextField
for this purpose:
class Sample(models.Model):
field1 = models.CharField(max_length=128)
field2 = models.TextField(max_length=1024*2) # Will be rendered as textarea
- [Django]-How to send email via Django?
- [Django]-How can I create a deep clone of a DB object in Django?
- [Django]-How do I install psycopg2 for Python 3.x?
3π
Wanted to expand on Carl Meyerβs answer, which works perfectly till this date.
I always use TextField
instead of CharField
(with or without choices) and impose character limits on UI/API side rather than at DB level. To make this work dynamically:
from django import forms
from django.contrib import admin
class BaseAdmin(admin.ModelAdmin):
"""
Base admin capable of forcing widget conversion
"""
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(BaseAdmin, self).formfield_for_dbfield(
db_field, **kwargs)
display_as_charfield = getattr(self, 'display_as_charfield', [])
display_as_choicefield = getattr(self, 'display_as_choicefield', [])
if db_field.name in display_as_charfield:
formfield.widget = forms.TextInput(attrs=formfield.widget.attrs)
elif db_field.name in display_as_choicefield:
formfield.widget = forms.Select(choices=formfield.choices,
attrs=formfield.widget.attrs)
return formfield
I have a model name Post
where title
, slug
& state
are TextField
s and state
has choices. The admin definition looks like:
@admin.register(Post)
class PostAdmin(BaseAdmin):
list_display = ('pk', 'title', 'author', 'org', 'state', 'created',)
search_fields = [
'title',
'author__username',
]
display_as_charfield = ['title', 'slug']
display_as_choicefield = ['state']
Thought others looking for answers might find this useful.
- [Django]-Django: how to do calculation inside the template html page?
- [Django]-Django datefield filter by weekday/weekend
- [Django]-"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.