django rest框架:如何向ModelSerializer添加自定义css类

django rest框架:如何向ModelSerializer添加自定义css类,django,django-rest-framework,Django,Django Rest Framework,我使用的是django rest框架,我想向PostSerializer的字段添加额外的css类名。这是我的代码: models.py class Post(models.Model): title = models.CharField(default="New Post", max_length=50) text = models.TextField(blank=True, null=True) class PostSerializer(serializers.ModelSe

我使用的是django rest框架,我想向PostSerializer的字段添加额外的css类名。这是我的代码:

models.py

class Post(models.Model):
    title = models.CharField(default="New Post", max_length=50)
    text = models.TextField(blank=True, null=True)
class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('id', 'title', 'text')

serializers.py

class Post(models.Model):
    title = models.CharField(default="New Post", max_length=50)
    text = models.TextField(blank=True, null=True)
class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('id', 'title', 'text')
类似于
title
的字段将呈现为:

<div class="form-group ">
    <label >Title</label>
    <input name="title" class="form-control" type="text"  value="" >    
</div>

标题

已经存在一个类
表单控件
,我想添加另一个,如何实现它?

要在API中为序列化程序字段设置自定义类,您应该为字段类型定义自定义模板,然后使用此自定义模板定义序列化程序字段

首先为输入字段创建自定义模板,它是rest框架内置的
input.html
的副本,在
表单控件
旁边添加了
{{style.class}}
。将其放在模板文件夹中,或者放在应用程序的模板文件夹中,或者放在项目的模板文件夹中

custom_input.html

<div class="form-group {% if field.errors %}has-error{% endif %}">
  {% if field.label %}
    <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">
      {{ field.label }}
    </label>
  {% endif %}

  <div class="col-sm-10">
    <input name="{{ field.name }}" {% if style.input_type != "file" %}class="form-control {{ style.class }}"{% endif %} type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value is not None %}value="{{ field.value }}"{% endif %} {% if style.autofocus and style.input_type != "hidden" %}autofocus{% endif %}>

    {% if field.errors %}
      {% for error in field.errors %}
        <span class="help-block">{{ error }}</span>
      {% endfor %}
    {% endif %}

    {% if field.help_text %}
      <span class="help-block">{{ field.help_text|safe }}</span>
    {% endif %}
  </div>
</div>