django: return string from view
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
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.
In other words, your view should return a HttpResponse
instance:
from django.http import HttpResponse
def myview(request):
return HttpResponse("return this string")
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/
Also in my case I had to add 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")
You can't send directly a string, but you can send a JSON object:
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({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
we use HttpResponse to render the Data
HttpResponse to render the Text
from django.http import HttpResponse
def Index(request):
return HttpResponse("Hello World")
HttpResponse to render the HTML
from django.http import HttpResponse
def Index(request):
text = """<h1>Hello World</h1>"""
return HttpResponse(text)
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>")