Pau*_*aul 44 python django django-views
我知道这是一个简单的问题,抱歉.我只想返回一个简单的字符串,没有模板.
我有我的看法:
def myview(request):
return "return this string"
Run Code Online (Sandbox Code Playgroud)
我不记得这个命令.谢谢
ale*_*cxe 75
根据文件:
视图函数或简称视图只是一个Python函数,它接受Web请求并返回Web响应.
每个视图函数负责返回一个HttpResponse对象.
换句话说,您的视图应该返回一个HttpResponse实例:
from django.http import HttpResponse
def myview(request):
return HttpResponse("return this string")
Run Code Online (Sandbox Code Playgroud)
awa*_*aik 10
如果您创建了一个聊天机器人或需要对 post 请求进行确认的响应 - 您应该添加装饰器,否则 Django 会阻止 post 请求。您可以在此处找到更多信息https://docs.djangoproject.com/en/2.1/ref/csrf/
同样在我的情况下,我必须添加 content_type="text/plain"。
from django.views.decorators.csrf import csrf_protect
from django.http import HttpResponse
@csrf_exempt
def Index(request):
return HttpResponse("Hello World", content_type="text/plain")
Run Code Online (Sandbox Code Playgroud)
您不能直接发送字符串,但可以发送 JSON 对象:
from django.http import JsonResponse
def myview(request):
return JsonResponse({'mystring':"return this string"})
Run Code Online (Sandbox Code Playgroud)
然后处理那个。例如,如果页面是由 AJAX 请求的,则使用 Javascript:
$.ajax({url: '/myview/', type: 'GET',
data: data,
success: function(data){
console.log(data.mystring);
...
}
})
Run Code Online (Sandbox Code Playgroud)
https://docs.djangoproject.com/en/1.11/ref/request-response/#jsonresponse-objects