Python django:从视图中返回字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24817007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:17:24  来源:igfitidea点击:

django: return string from view

pythondjangodjango-views

提问by Paul

I know this is a simple question, sorry. I just want to return a simple string, no templates.

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

I have my view:

我有我的看法:

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

I don't remember the command. Thanks

我不记得命令了。谢谢

采纳答案by alecxe

According to the documentation:

根据文档

A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response.

Each view function is responsible for returning an HttpResponse object.

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

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

In other words, your view should return a HttpResponseinstance:

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

from django.http import HttpResponse

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

回答by ThePhi

You can't send directly a string, but you can send a JSON object:

您不能直接发送字符串,但可以发送 JSON 对象:

from django.http import JsonResponse

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

Then process that. With Javascript for example if the page was requested by AJAX:

然后处理那个。例如,如果页面是由 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

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

回答by vinodsesetti

we use HttpResponse to render the Data

我们使用 HttpResponse 来呈现数据

HttpResponse to render the Text

HttpResponse 呈现文本

from django.http import HttpResponse
def Index(request):
    return HttpResponse("Hello World")

HttpResponse to render the HTML

用于呈现 HTML 的 HttpResponse

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

回答by awaik

If you create a chat-bot or need this response on post request for confirmation - you should add decorator, otherwise Django block post requests. More info you can find here https://docs.djangoproject.com/en/2.1/ref/csrf/

如果您创建了一个聊天机器人或需要对 post 请求进行确认的响应 - 您应该添加装饰器,否则 Django 会阻止 post 请求。您可以在此处找到更多信息https://docs.djangoproject.com/en/2.1/ref/csrf/

Also in my case I had to add content_type="text/plain".

同样在我的情况下,我必须添加 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")

回答by Thusitha Deepal

According Django documentation Django uses request and response objects to pass state through the system.

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

When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.Do as follows

当请求一个页面时,Django 创建一个 HttpRequest 对象,其中包含有关请求的元数据。然后 Django 加载适当的视图,将 HttpRequest 作为第一个参数传递给视图函数。每个视图负责返回一个HttpResponse对象。执行如下

from django.http import HttpResponse

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

回答by Yilmaz

urls.py

网址.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

视图.py

from django.http import HttpResponse

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

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