Django: 从视图返回字符串

68

我知道这是一个简单的问题,抱歉。我只想返回一个简单的字符串,没有模板。

以下是我的视图:

def myview(request):
    return "return this string"

我不记得这个命令了。谢谢

7个回答

114

根据文档

视图函数(或简称为视图)只是一个Python函数,它接收Web请求并返回Web响应。

每个视图函数负责返回一个HttpResponse对象。

换句话说,你的视图应该返回一个HttpResponse实例:

from django.http import HttpResponse

def myview(request):
    return HttpResponse("return this string")

13

如果您创建了聊天机器人或需要在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")

6
您不能直接发送字符串,但可以发送JSON对象:
from django.http import JsonResponse

def myview(request):
    return JsonResponse({'mystring':"return this string"})

然后处理它。例如,如果页面是由AJAX请求的,则使用JavaScript:

$.ajax({url: '/myview/',    type: 'GET',
                            data: data,
                            success: function(data){ 
                                console.log(data.mystring);
                                ...
                                 }
                            })

https://docs.djangoproject.com/en/1.11/ref/request-response/#jsonresponse-objects


4
我们使用HttpResponse来呈现数据,使用HttpResponse来呈现文本。
from django.http import HttpResponse
def Index(request):
    return HttpResponse("Hello World")

将HttpResponse用于渲染HTML

from django.http import HttpResponse
    def Index(request):
        text = """<h1>Hello World</h1>"""
        return HttpResponse(text)    

2

urls.py

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]

views.py

from django.http import HttpResponse

def aboutview(request):
  return HttpResponse("<h1>about page</h1>")

def homeview(request):
  return HttpResponse("<h1>home page</h1>")

1

如果有人在未来遇到这种情况,比如想要传递任何类型的字符串,我需要澄清一下。我需要做以下操作,从视图开始:

from django.http import HttpResponse        
def myview(request):
    text = """<a href="https://www.w3schools.com">Visit W3Schools.com!</a>"""
    return HttpResponse(text)

顺便提一下,这里的端点“submit/myview”可以是任何东西。

 path('submit/myview', views.myview, name='myview'),

the ajax side of things on the template where you want to render this 

 
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    document.getElementById("demo").innerHTML =
    this.responseText;
  }
  xhttp.open("GET", "myview");
  xhttp.send();
}
</script>

0

根据Django文档,Django使用请求和响应对象在系统中传递状态。

当请求页面时,Django创建一个包含有关请求的元数据的HttpRequest对象。然后Django加载适当的视图,将HttpRequest作为视图函数的第一个参数传递。每个视图负责返回一个HttpResponse对象。请按照以下步骤操作:

from django.http import HttpResponse

def myview(request):
    text="return this string"
    return HttpResponse(text)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接