django rest框架:如何将自定义CSS类添加到ModelSerializer

时间:2018-11-03 08:26:55

标签: 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)


serializers.py

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>

已经存在一个类form-control,我想添加另一个类,如何实现?

1 个答案:

答案 0 :(得分:1)

要在您的API中为序列化程序字段设置自定义类,您应该为该字段类型定义自定义模板,而不是使用此自定义模板定义序列化程序字段。

首先为输入字段创建一个自定义模板,该模板是rest框架的内置input.html的副本,并在{{ style.class }}旁边添加了form-control。将此放置在您的模板文件夹中,或者放在您应用的模板文件夹中,或者放在项目的模板文件夹中。

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>

然后用custom_input.html声明您的序列化器,并将class属性设置为所需的类。在此示例中,test1类和test2类将添加到form-control类的旁边。

serializers.py

class PostSerializer(serializers.ModelSerializer):

    title = serializers.CharField(style={'template': 'your_template_folder/custom_input.html', 'class': 'test1 test2'})

    class Meta:
        model = Post
        fields = ('id', 'title', 'text')