2

I am trying to make all of the fields in my Django form have the same size to look tidy. I have text input, drop down and text area. I am creating the form using the Ticket model so I am not defining the form fields explicitly. I was able to resize the text input, but what is the attribute in a drop-down field that controls the width? Note that the choices in the drop-down are basically foreign keys from another table that are defined in the model.

class NewTicket(forms.ModelForm):

    class Meta:
        model=Ticket

        fields = ('subject','business','project','description')

        widgets={
            'subject': forms.TextInput(attrs={'size': '20px'}),
            'business': forms.Select(attrs={'size': '20px'}) #this line does not work
            }
Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Ibo
  • 4,081
  • 6
  • 45
  • 65

2 Answers2

10

I know you said no CSS but is this an option?

class NewTicket(forms.ModelForm):

    class Meta:
        model=Ticket

        fields = ('subject','business','project','description')

        widgets={
            'subject': forms.TextInput(attrs={'style': 'width:20px'}),
            'business': forms.Select(attrs={'style': 'width:20px'})
            }
Cyrlop
  • 1,894
  • 1
  • 17
  • 31
  • it worked, do you know how I can apply this to all of the fields without mentioning one by one explicitly? – Ibo Aug 21 '18 at 21:58
  • This is another question but you can either do that with CSS in your templates or dynamically change the widget with something like `form.fields['subject'].widget = forms.TextInput(attrs={'style': 'width:20px'})` – Cyrlop Aug 21 '18 at 22:21
  • you are mentioning the field `subject` explicitly, I meant using something like `__all__`etc – Ibo Aug 21 '18 at 22:24
  • 1
    That's an example, you can loop through your fields, take a look at [this](https://stackoverflow.com/questions/46283636/set-attribute-of-all-fields-in-django-modelform-in-init-method) :) – Cyrlop Aug 21 '18 at 22:27
0

You should be able to set the widget attributes, eg. in the __init__() as

mystyle = {"style": "width:400px;", "size": 8, "rows": 8}
self.fields["something"].widget.attrs = mystyle

See here: https://docs.djangoproject.com/en/4.1/ref/forms/widgets/#django.forms.Widget.attrs

Will N.
  • 21
  • 3