在Django模型字段中定义CSS样式 [英] Define CSS style in Django model field

查看:153
本文介绍了在Django模型字段中定义CSS样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

文件models.py:

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) 
    ...

什么是最简单的方法添加CSS类到字段my_field这里?
(我看到一些答案对于形式,但不是为模型)。

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).

推荐答案

模型和定义UI属性,这是正确的地方做它

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'}),
        }

这应该为您的字段设置正确的类,然后在HTML文件中设置需要css属性,例如

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

.mycssclass {
    color: red;
}

如果您使用 inlineformset_factory 你仍然可以传递一个 widgets dict,其中<​​code> widgets 是映射到或者您可以向其传递自定义表单,以便您可以执行此类操作

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)

这篇关于在Django模型字段中定义CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆