我使用Django Rest框架(DRF)构建了以下基于泛型类的视图
class ExampleDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Example.objects.all()
serializer_class = ExampleSerializer
renderer_classes = (JSONRenderer, TemplateHTMLRenderer)
def get(self, request, *args, **kwargs):
response = self.retrieve(request, *args, **kwargs)
if request.accepted_renderer.format == 'html':
form = ExampleForm(data=response.data)
return Response({'data': response.data, 'form': form}, template_name='example.html')
return response
此视图允许我通过指定format = json或html从同一端点获取JSON数据或HTML表单。
我想以编程方式调用该视图以从另一个视图中获取呈现的HTML表单,以便将此表单包含在另一个包含更多内容的页面中。
答案 0 :(得分:27)
我在文档中找到了解决方案...... https://docs.djangoproject.com/en/1.7/topics/class-based-views/mixins/
提示来自他们的例子:
class AuthorDetail(View):
def get(self, request, *args, **kwargs):
view = AuthorDisplay.as_view()
return view(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
view = AuthorInterest.as_view()
return view(request, *args, **kwargs)
答案 1 :(得分:20)
Sub Mail_Outlook()
Dim OutApp As Object
Dim OutMail As Object, signature As String
Dim irow, i As Integer
Dim objItem As Object
irow = InputBox("How many Invites do you want to send?")
Set OutApp = CreateObject("Outlook.Application")
LastRow = ActiveSheet.Range("E" & Rows.Count).End(xlUp).Row
For i = 0 To irow - 1
Set OutMail = OutApp.CreateItem(o)
If Cells(LastRow - i, 1).Value <> "" Then
Mailto = Cells(LastRow - i, 5).Value
If Mailto = "Colleague1" Or _
Mailto = " Colleague2" Or _
Mailto = " Colleague3" Then
Mailto = Mailto & "@hotmail.com"
End If
End If
MailSubject = Cells(LastRow - i, 4).Value & " – Important Message"
MailBody = "Hi " & Cells(LastRow - i, 5).Value & "," & vbNewLine & vbNewLine & _
" I’m inviting you for the conference being held today." & _
vbNewLine
With OutMail
.Display
signature = .body
.Subject = MailSubject
.To = Mailto
.body = MailBody & vbNewLine & signature
End With
Next i
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
OR
html_from_view = ExampleDetail.as_view({'get': 'list'})(request).content
答案 2 :(得分:9)
从Django 2.2和DRF 3.9.2开始,我可以使用以下代码获得响应。
response = UserItemsApiView.as_view()(request=request._request).data
以上示例解决了以下问题:
request
参数必须是django.http.HttpRequest
的实例,而不是rest_framework.request.Request
content
属性代替了data
,从该视图中获得了结果。答案 3 :(得分:0)
我没有尝试过,但是我认为以下应该可行。
调用DRF并通过url.open或请求进行轮询
示例:
import requests
from django.shortcuts import render
def home(request):
# get the list of todos
response =
requests.get('https://jsonplaceholder.typicode.com/todos/')
# transfor the response to json objects
todos = response.json()
return render(request, "main_app/home.html", {"todos": todos})
您可以调用DRF并通过ajax请求从任何其他视图指向。
答案 4 :(得分:-6)
如果我理解正确,你需要从视图B中获取结果,同时在视图A中。
使用请求 / urllib2 和 json 库可以解决您的问题(如this answer中所述)。
要获取URL,您可以结合使用 request.get_absolute_uri()和/或 request.get_host()和 django.core.urlresolvers .reverse