menu

Questions & Answers

How to change the width of a drop-down field in a django form using widget attributes not css

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
            }
Answers(2) :

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'})
            }
Comments:
2023-01-25 00:55:11
it worked, do you know how I can apply this to all of the fields without mentioning one by one explicitly?
2023-01-25 00:55:11
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'})
2023-01-25 00:55:11
you are mentioning the field subject explicitly, I meant using something like __all__etc
2023-01-25 00:55:11
That's an example, you can loop through your fields, take a look at this :)

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