Django Rest Framework序列化器单独呈现表单

时间:2016-01-29 06:10:59

标签: python django django-rest-framework

我知道如何渲染序列化程序的形式作为一个整体,但我不知道如何单独渲染它类似于模板上的django表单,如

{{ form.name }}
{{ form.name.errors }}

我当前的文件和代码如下:

models.py

# Create your models here.
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles

LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())


class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)

    class Meta:
        ordering = ('created',)

serializers.py

from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES


class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

form.html

{% extends 'main/base.html' %}
{% load rest_framework %}

{% block content %}
    <div class="container">
        <form method="POST" id="id-login-form" class="panel-body">
            {% csrf_token %}
            {% render_form serializer %}
            <!-- {% render_form serializer template_pack='rest_framework/horizontal' %}
            {% render_form serializer template_pack='rest_framework/vertical' %} -->
            <!-- {{ serializer }} -->

            <input type="submit" value="Save">
        </form>
    </div>
{% endblock %}

1 个答案:

答案 0 :(得分:7)

除了名为{% render_form %}的{​​{1}}之外,DRF还提供了另一个模板标记,实际上used within the former可以呈现所有字段。

所以你的 views.py 看起来像这样(你需要在你的回复中发送这个{% render_field %}字典):

style

然后在你的模板中你就可以做到:

class SnippetCreate(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'snippets/snippet_create.html'
    style = {'template_pack': 'rest_framework/vertical/'}

    def get(self, request):
        serializer = SnippetSerializer()
        return Response({'serializer': serializer, 'style': self.style})

    def post(self, request):
        serializer = SnippetSerializer(data=request.data)
        return Response({'serializer': serializer, 'style': self.style})

了解正在发生的事情的最佳方法实际上是查看源本身: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/templatetags/rest_framework.py#L35

然后调用

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/renderers.py#L325