python - Django Rest Framework serializers render form individually -


i know how render form of serializers whole not know how render individually similar django forms on template like

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

my current files , codes following:

models.py

# create models here. django.db import models pygments.lexers import get_all_lexers pygments.styles import get_all_styles  lexers = [item item in get_all_lexers() if item[1]] language_choices = sorted([(item[1][0], item[0]) item in lexers]) style_choices = sorted((item, item) 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 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 %} 

drf provides template tag, in addition {% render_form %} called {% render_field %} that's used within former render fields.

so views.py (you need send style dict in response):

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

and in template do:

{% render_field serializer.title style=style %}  {% render_field serializer.code style=style %} 

best way understand what's going on @ source itself: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/templatetags/rest_framework.py#l35

which calls

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


Comments