jazzblue
jazzblue

Reputation: 2437

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.ForeignKey(User, blank=True, null=True)
   my_field = models.CharField(max_length=200, default="sample_field")

File views.py

from django.forms.models import inlineformset_factory
from django.contrib.auth.models import User
from myapp.models import MyClass

@login_required
def index(request):

    username = User.objects.get(username=request.user.username)

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

    formset = MyClassFormSet(instance=username) 
    ...

What is the easiest way to add CSS class to the field my_field here? (I saw some answers on SO for forms, but not for models).

Upvotes: 1

Views: 4724

Answers (1)

Anurag Uniyal
Anurag Uniyal

Reputation: 88837

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

class MyForm(ModelForm):
    class Meta:
        model = MyClass
        fields = ('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)

Upvotes: 2

Related Questions