gpt4 book ai didi

python - Django Rest Framework 序列化程序单独呈现表单

转载 作者:行者123 更新时间:2023-11-28 20:19:13 25 4
gpt4 key购买 nike

我知道如何将序列化程序的形式作为一个整体呈现,但我不知道如何将其单独呈现,类似于模板上的 django 形式

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

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

模型.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',)

序列化器.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 %}

最佳答案

DRF提供了另外一个模板标签,除了{% render_form %},叫做{% render_field %},实际上是used within the former呈现所有字段。

所以你的 views.py 看起来像这样(你需要在你的响应中发送这个 style dict):

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

然后在您的模板中您可以这样做:

{% render_field serializer.title style=style %}

{% render_field serializer.code style=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

关于python - Django Rest Framework 序列化程序单独呈现表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35077982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com