Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-Admin: CharField as TextArea

I have

class Cab(models.Model):     name  = models.CharField( max_length=20 )     descr = models.CharField( max_length=2000 )  class Cab_Admin(admin.ModelAdmin):     ordering     = ('name',)     list_display = ('name','descr', )     # what to write here to make descr using TextArea?  admin.site.register( Cab, Cab_Admin ) 

how to assign TextArea widget to 'descr' field in admin interface?

upd:
In Admin interface only!

Good idea to use ModelForm.

like image 272
maxp Avatar asked Jan 10 '09 05:01

maxp


People also ask

Which code will give us a textarea form field in Django?

CharField() is a Django form field that takes in a text input. It has the default widget TextInput, the equivalent of rendering the HTML code <input type="text" ...> .

What is CharField in Django?

CharField in Django Forms is a string field, for small- to large-sized strings. It is used for taking text inputs from the user. The default widget for this input is TextInput.

What is Attrs Django?

attrs . A dictionary containing HTML attributes to be set on the rendered DateInput and TimeInput widgets, respectively. If these attributes aren't set, Widget. attrs is used instead.

How do I add a class or id attribute to a Django form field?

In order to add a class or id attribute to a form in Django, we have to place a widget=form. TextInput (or widget= form. EmailInput, if email input) within the form field (because it's a text field). Inside of this widget, we then have to put, attrs={'class':'some_class'}.


2 Answers

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.

like image 111
ayaz Avatar answered Oct 20 '22 05:10

ayaz


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 
like image 43
Carl Meyer Avatar answered Oct 20 '22 06:10

Carl Meyer