Django Rest框架表单 [英] Django Rest Framework Form
问题描述
Django Rest框架附带一个从串行器返回HTML表单的渲染器 [1] 。在浏览文档然后通过代码之后,我仍然无法弄清楚如何让它呈现一个空白的表单。
Django Rest Framework comes with a renderer for returning a HTML form from a serializer[1]. After poring through the docs and then through the code, I still cannot figure out how to get it to render a blank form.
我无法弄清楚如何实例化一个空白的串行器。在DRF的文档中,他们说serializer与django的表单有非常相似的API。当您想在模板中使用空白表单时,使用MyForm()实例化一个表单,并将其传递给模板上下文。但是,当我尝试使用序列化程序时,.data属性只是 {'detail':'Not Found。'}
I can't figure out how to instantiate a blank serializer. In the docs for DRF they say the serializer has a very similar API to django's forms. When you want a blank form in a template, you instantiate one with MyForm() and pass it to the template context. However when I try that with a serializer, the .data attribute is just {'detail': 'Not Found.'}
我觉得我一定会错过一些显而易见的事情,因为渲染一个空白的表单似乎是HTMLFormRenderer的一个很大的用例。 >
一些源代码
I feel like I must be missing something blindingly obvious because rendering a blank form seems like a pretty major use case for an HTMLFormRenderer.
class CustomViewSet(ModelViewSet):
lookup_field = 'id'
pagination_class = MyCustomPagination
serializer_class = MyModelSerializer
renderer_classes = (JSONRenderer, BrowsableAPIRenderer, HTMLFormRenderer)
def create(self, request, *args, **kwargs):
# return an html form for GET requests to /api/my_model/create/.form
我很确定我的urlconf正确连接,请求最终在正确的地方,因为当我GET / api / my_model /< pk> /。form
我收到一个表单作为回应,与模型属性预先输入。我只想要一种方式来获得一个空白的表单...
I'm pretty sure I have the urlconf wired up right that the request ends up in the right place, because when I GET /api/my_model/<pk>/.form
I get a form in response, with the model attributes pre-entered. I just want a way to get a blank form...
推荐答案
我设法返回一个表单的html代码片段,使用以下方法在我的观点:
I managed to return an html snippet for a form using the following method on my viewset:
class CustomViewSet(ModelViewSet):
@list_route()
def form(self, request, *args, **kwargs):
serializer = self.get_serializer()
renderer = HTMLFormRenderer()
form_html = renderer.render(serializer.data, renderer_context={
'template': 'rest_framework/api_form.html',
'request': request
})
return HttpResponse(form_html)
我需要使用一个香草django HttpResponse,而不是休息框架的Response对象,以防止Response对象尝试重新呈现form_html与viewset的默认渲染器。此外,需要使用list_route装饰器来获取rest_framework的DefaultRouter来添加一个 my_model / form /
端点,但这并不意味着视图必须返回一个列表。
I needed to use a vanilla django HttpResponse, rather than rest framework's Response object, to prevent the Response object trying to re-render the form_html with the viewset's default renderer. Also, the list_route decorator is needed to get rest_framework's DefaultRouter to add a my_model/form/
endpoint, it doesn't mean the view has to return a list.
这篇关于Django Rest框架表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!