Skip to content Skip to sidebar Skip to footer

Define Css Style In Django Model Field

Suppose I have a following code: File models.py: from django.db import models from django.contrib.auth.models import User class MyClass(models.Model): username = models.Foreign

Solution 1:

Create a form from the model and define UI attributes there, that is the correct place to do it e.g.

classMyForm(ModelForm):
    classMeta:
        model = MyClassfields= ('my_field')
        widgets = {
            'my_field': TextInput(attrs={'class': 'mycssclass'}),
        }

That should set correct class for your field, then in HTML file set the needed css attributes e.g.

.mycssclass {
    color: red;
}

If you are using inlineformset_factory you can still pass a widgets dict to it, where widgets is a dictionary of model field names mapped to a widget, or you can pass a custom form to it, so you can do something like this

MyClassFormSet = inlineformset_factory(User, MyClass, form=MyForm, can_delete=False, extra=5)

Post a Comment for "Define Css Style In Django Model Field"