Django Shortcuts
Django shortcuts module is a collection of helper functions that are generally used in view function/classes. There are many shortcuts available in module django.shortcuts
. In other words, these function/classes introduce controlled coupling for convenience's sake.
Example
It combines a given template with a dictionary and returns the HttpResponse object with that rendered text. Following is the syntax of the render() function.
from django.shortcuts import render
def new_view(request):
# View code here...
return render(
request, 'newapp/index.html',
{
'foo': 'bar',
},
content_type='application/xhtml+xml'
)
It is equivalent to the below code.
The redirect() function is used to redirect to the specific URL. It returns an HttpResponseRedirect to the appropriate URL for the argument passed. Let's see the following syntax.
def blog_view(request, post_id):
blog = Post.objects.get(pk=post_id)
return redirect(blog)
# equivalent to: return HttpResponseRedirect(blog.get_absolute_url())
def blog_view(request, post_id):
return redirect('blog_details', id=post_id)
# equivalent to: return HttpResponseRedirect(reverse('blog_details', args=(post_id, )))
def relative_url_view(request):
return redirect('/blogs/archive/')
# equivalent to: return HttpResponseRedirect('/blogs/archive/')
It returns the DoesNotExist exception if the searched object is not found. On the other hand, get()
method raise Http404.
from django.shortcuts import get_object_or_404
def my_view(request):
obj = get_object_or_404(MyModel, pk=1)
It is equivalent to: