I had to figure this out for a CMS I manage. Some of the answers here are close, but aren't completely right. You need to provide the class
in the attrs
parameter, as at least one other response has mentioned, but you should provide inline li
. If you provide style
, then the style will get applied to the the input
element, instead of the li
.
I couldn't find anything in their documentation that lists the available CSS classes for their components, so I discovered this by using DevTools in Firefox to look at the available styles, and then finding inline li
in their forms.css
.
This solution makes it possible change the alignment without needing to mess with templates or making my own CSS file.
from django import forms
from .models import MyModel
MyForm = forms.modelform_factory(
MyModel,
widgets={"field_name": forms.RadioSelect(attrs={"class": "inline li"})},
fields="__all__",
)
To figure out what other classes are available so you can more conveniently modify the the layout of various form elements, run python manage.py collectstatic
(make sure STATIC_ROOT
is defined), and you can find forms.css
under STATIC_ROOT/static/admin/css
.
In this particular repo, I have STATIC_ROOT
set to ./lib
in my local_settings.py:
$ python manage.py collectstatic
1408 static files copied to './lib/static'.
$ ls -1 lib/static/admin/css/
autocomplete.css
base.css
changelists.css
dashboard.css
fonts.css
forms.css
login.css
nav_sidebar.css
responsive.css
responsive_rtl.css
rtl.css
vendor/
widgets.css
Once I actually got it displaying horizontally with a clean solution, I also wanted to hide the blank option from the list of choices, so ended up creating my own CSS file to do that, since the documentation for that was easy to find
/* BASE_DIR/static/css/my_customizations.css */
#id_field_name li:has(input[value='']) {
visibility: hidden;
padding: 0;
margin: 0;
height: 0;
}
from django import forms
from .models import MyModel
class MyForm(
forms.modelform_factory(
MyModel,
widgets={"field_name": forms.RadioSelect(attrs={"class": "inline li"})},
fields="__all__",
)
):
class Media:
css = {"all": ("css/my_customizations.css",)}
(Though, as of January 2023, :has
is not yet supported by Firefox, but will hopefully be supported sometime this year)