Skip to content

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.

def new_view(request):  
    # View code here...  
    t = loader.get_template('newapp/index.html')  
    c = {'foo': 'bar'}  
    return HttpResponse(t.render(c, request), content_type='application/xhtml+xml') 

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.

Syntax

redirect(to, *args, permanent=False, **kwargs)  
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:

from django.http import Http404   
def my_view(request):  
    try:  
            obj = MyModel.objects.get(pk=1)  
    except MyModel.DoesNotExist:  
            raise Http404("No MyModel matches the given query.")  

It returns the results of filter() on a given model manager cast to a list, raising Http404 if the resulting list is empty. The syntax is same as get_object_or_404.

from django.shortcuts import get_list_or_404  
def my_view(request):  
    my_objects = get_list_or_404(MyModel, published=True)  
from django.http import Http404  
def my_view(request):  
    my_objects = list(MyModel.objects.filter(published=True))  
    if not my_objects:  
    raise Http404("No MyModel matches the given query.")  

Reference