Resize fields in Django Admin

后端 未结 14 2009
一生所求
一生所求 2020-12-22 15:12

Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 chara

相关标签:
14条回答
  • 2020-12-22 15:53

    Here is a simple, yet flexible solution. Use a custom form to override some widgets.

    # models.py
    class Elephant(models.Model):
        name = models.CharField(max_length=25)
        age = models.IntegerField()
    
    # forms.py
    class ElephantForm(forms.ModelForm):
    
        class Meta:
            widgets = {
                'age': forms.TextInput(attrs={'size': 3}),
            }
    
    # admin.py
    @admin.register(Elephant)
    class ElephantAdmin(admin.ModelAdmin):
        form = ElephantForm
    

    The widgets given in ElephantForm will replace the default ones. The key is the string representation of the field. Fields not specified in the form will use the default widget.

    Note that although age is an IntegerField we can use the TextInput widget, because unlike the NumberInput, TextInput accepts the size attribute.

    This solution is described in this article.

    0 讨论(0)
  • 2020-12-22 15:57

    It's well described in Django FAQ:

    Q: How do I change the attributes for a widget on a field in my model?

    A: Override the formfield_for_dbfield in the ModelAdmin/StackedInline/TabularInline class

    class MyOtherModelInline(admin.StackedInline):
        model = MyOtherModel
        extra = 1
    
        def formfield_for_dbfield(self, db_field, **kwargs):
            # This method will turn all TextFields into giant TextFields
            if isinstance(db_field, models.TextField):
                return forms.CharField(widget=forms.Textarea(attrs={'cols': 130, 'rows':30, 'class': 'docx'}))
            return super(MyOtherModelInline, self).formfield_for_dbfield(db_field, **kwargs)
    
    0 讨论(0)
提交回复
热议问题