Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 941
Paul Avatar asked Jul 18 '14 03:07

Paul


People also ask

What is HTTP request in Django?

Django uses request and response objects to pass state through the system. 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.

What is QueryDict Django?

In an HttpRequest object, the GET and POST attributes are instances of django. http. QueryDict , a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple> , pass multiple values for the same key.

How do I increase my 404 in Django?

The Http404 exceptionIf you raise Http404 at any point in a view function, Django will catch it and return the standard error page for your application, along with an HTTP error code 404. In order to show customized HTML when Django returns a 404, you can create an HTML template named 404.

What is get and post method in Django?

GET and POSTDjango's login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.


2 Answers

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")
like image 168
alecxe Avatar answered Oct 21 '22 14:10

alecxe


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")
like image 11
awaik Avatar answered Oct 21 '22 13:10

awaik