Django-Admin: CharField as TextArea

前端 未结 9 2032
一个人的身影
一个人的身影 2020-12-07 09:20

I have

class Cab(models.Model):
    name  = models.CharField( max_length=20 )
    descr = models.CharField( max_length=2000 )

class Cab_Admin(admin.ModelAd         


        
相关标签:
9条回答
  • 2020-12-07 10:04

    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.

    0 讨论(0)
  • 2020-12-07 10:04

    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 TextFields 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.

    0 讨论(0)
  • 2020-12-07 10:07

    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.

    0 讨论(0)
提交回复
热议问题