django: return string from view - python

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>")

I need to clear the air should someone bump to this in the feature, like wanting to pass any sort of string.
I hard to do the following, starting with the view:
from django.http import HttpResponse
def myview(request):
text = """Visit W3Schools.com!"""
return HttpResponse(text)
Then urls, btw the endpoint here "submit/myview" can be anything
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>

According Django documentation 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. Each view is responsible for returning an HttpResponse object.Do as follows
from django.http import HttpResponse
def myview(request):
text="return this string"
return HttpResponse(text)

Related

'str' object has no attribute 'get' Django Middleware [duplicate]

This is a view written for my posts app in Django. The problem is that after filling the update form and submitting it happens successfully. But it creates confusion for the user because the same HTML page is there and how can I redirect into the updated object?
def post_update(request,id=None):
instance=get_object_or_404(Post,id=id)
if instance.created_user != request.user.username :
messages.success(request, "Post owned by another user, You are having read permission only")
return render(request,"my_blog/denied.html",{})
else :
form=PostForm(request.POST or None,request.FILES or None,instance=instance)
if form.is_valid():
instance=form.save(commit=False)
instance.save()
context={ "form":form,
"instance":instance }
return render(request,"my_blog/post_create.html",context)
As already suggested by #mdegis you can use the Django redirect function to redirect to another view or url.
from django.shortcuts import redirect
def view_to_redirect_to(request):
#This could be the view that handles the display of created objects"
....
perform action here
return render(request, template, context)
def my_view(request):
....
perform form action here
return redirect(view_to_redirect_to)
Read more about redirect here and here
You can pass positional or keyword argument(s) to the redirect shortcut using the reverse() method and the named url of the view you're redirecting to.
In urls.py
from news import views
url(r'^archive/$', views.archive, name='url_to_redirect_to')
In views.py
from django.urls import reverse
def my_view(request):
....
return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value}))
More about reverse Here
You can use redirect from http shortcuts.
from django.shortcuts import redirect
def my_view(request):
...
object = MyModel.objects.get(...)
return redirect(object) #or return redirect('/some/url/')
Here is the link to official docs.
To redirect from a view to another view, you need to give the conbination of the app name "myapp", colon ":" and the view name "dest_view" which is set in the path in "myapp/urls.py" as shown below. And, you don't need to modify the path in "myapp/urls.py" if you pass data with session with request.session['key'] as shown below:
# "myapp/views.py"
from django.shortcuts import render, redirect
def redirect_view(request):
# Here
request.session['person'] = {'name': 'John', 'age': 27}
# Here
return redirect("myapp:dest_view")
def destination_view(request):
return render(request, 'myapp/index.html', {})
You need to give the view name "dest_view" to path() in "myapp/urls.py" as shown below:
# "myapp/urls.py"
from django.urls import path
from . import views
app_name = "myapp"
urlpatterns = [ # This is view name
path('dest/', views.destination_view, name="dest_view")
]
Then, this is Django Template:
# "myapp/index.html"
{{ request.session.person.name }} {# John #}
{{ request.session.person.age }} {# 27 #}
from django.urls import reverse
def my_view(request):
....
return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value(object.id for specific id)}))

How to pass a query set to the context class in Django?

I am trying to pass a queryset object to django context class, but doing so results in the following error: TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
Now i understand that the context accepts only a dictionary but i am following an example from a book called django_unleashed which uses Django version 1.8 and i am using django 2.0. and i guess it was done like that in previous versions.
So my question is how should i do this step correctly using django 2.0
from django.shortcuts import render
from django.http import HttpResponse
from .models import Tag
from django.template import Context, loader
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template('organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
As the error suggests, you should use a regular dictionary for the context:
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template('organizer/tag_list.html')
context = {'tag_list': tag_list}
output = template.render(context)
return HttpResponse(output)
In practice, you would usually use the render shortcut rather than manually rendering the template:
from django.shortcuts import render
def homepage(request):
tag_list = Tag.objects.all()
context = {'tag_list': tag_list}
return render(request, 'organizer/tag_list.html', context)
'''you have a model class named 'Tag',
wish your template is on ' Project directory/ app directory/ template/ same name of app directory'
example: let your project name is 'Website' and app name is 'organizer' then the template will be on: 'Website/ organizer/ templates/ organizer/ tag_list.html' Confirm your TEMPLATES setting is default on setting.py file."'
from django.shortcuts import render
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
context = { 'tag_list' : tag_list}
return render ( request, 'organizer/tag_list.html', context)

The view app.views.model didn't return an HttpResponse object

This is my views.py file. i am on the way to generate xml file, The data i am getting from mysql. First time its working but i make some changes then i cant remember what i did now it s not working ...
in the views.py
def MessageHeaderModel2(request):
if request.method == "POST":
form = MessageHeaderForm(request.POST)
if form.is_valid():
DDEX_Party_Id = request.POST.get('DDEX_Party_Id',None)
data = serializers.serialize("xml", MessageHeaderModel2.objects.all())
with open("file.xml", "w") as out:
xml_serializer.serialize(MessageHeaderModel2.obj ects.all(), stream=out)
The error now i am gettin is
>Exception Type:ValueError
Exception Value:The view app.views.MessageHeaderModel2 didn't return an HttpResponse object.
Like stated in the error, your view isn't sending any response to the client.
Add at the end of your view a line like :
return render(request, 'template.html')
Or any other response, that you need
You in fact are not returning an HttpResponse object!
Django views must return an instance of HttpResponse so at the end of your view:
from django.http import HttpResponse
def view(request):
...
return HttpResponse("the page content")
You can also return may other subclasses of HttpResponse, see the documentation for a list.
You can also use some of the shortcut functions to render a page using the django templating system, again the documentation is helpful here, but briefly:
from django.shortcuts import render_to_response
def view(request):
...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
A complete example using your code from above:
def view(request):
if request.method == "POST":
form = MessageHeaderForm(request.POST)
if form.is_valid():
DDEX_Party_Id = request.POST.get('DDEX_Party_Id',None)
data = serializers.serialize("xml", MessageHeaderModel2.objects.all())
with open("file.xml", "w") as out:
out.write(data)
return HttpResponse(data)
else:
# return error response?
return HttpResponseNotAllowed(['POST'])
You are not returning anything so that's why you have such an error...
You can also for example return Success value or redirect to other view..

unable to redirect to some view in Django python

AoA,
I am trying to redirect to some view, but failed to do so.
here is the code
views.py
def logout(request):
c = {'username': 'Create Account', 'status': ''}
c.update(csrf(request))
response = render_to_response("home.html",c)
response.delete_cookie('id')
request.session['id'] = 'None'
return redirect('/home/')
def home(request):
#some code here
return render_to_response('blah blah')
urls.py
url(r'^home/$', 'contacts.views.home_Page'),
url(r'^logout/$', 'contacts.views.logout'),
the above code redirect me to -- let's suppose current URL(127.0.0.1/account)
it redirects me to (127.0.0.1/account/home) but i want to redirect to 127.0.0.1/home
how can I redirect to specific view ?
redirect(to[, permanent=False], *args, **kwargs) returns an HttpResponseRedirect to the appropriate URL for the arguments passed. You need to return the HttpResponseRedirect object in the view function.
BTW, you should try to avoid hardcoding urls in you code, instead you should use view names.
e.g:
urls.py:
url(r'^home/$', home, name='home_view')
...
view.py:
def logout(request):
...
redirect('home_view')
django provides a built-in logout that you should use:
from django.shortcuts import redirect
from django.contrib.auth import logout
def log_out(request):
logout(request)
return redirect('home')
Now 'home' can be many things; but the easiest way to make sure its pointing to the right place is to name your urls. So in your urls.py:
url(r'home/$', home, name='home')

Not work variables in django templates

My context dictionary not sending to my templates.
I have function
from django.shortcuts import render_to_response
from django.template import RequestContext
def home(request):
return render_to_response('home.html',{'test':'test'},context_instance=RequestContext(request))
and i have simple template such as:
<html>
<body>
my test == {{test}}
</body>
</html>
When i open my site in browser, i have "my test == ".
settings.py is default. I dont use something custom. What the problem?
Server is apache with wsgi module.
I know, but I see your post just now. You did great, but you need something more to do. Here is the view
def home(request):
# You need to retrieve something from the database or create a variable here
test = Test.Objects.all()
# Use Context Dic
context = {
'test': test,
}
# Then Use the return
return render(request, 'home.html', context)
(EDITED)
Now this will work.

Categories