Book Image

Mastering Django: Core

By : Nigel George
Book Image

Mastering Django: Core

By: Nigel George

Overview of this book

Mastering Django: Core is a completely revised and updated version of the original Django Book, written by Adrian Holovaty and Jacob Kaplan-Moss - the creators of Django. The main goal of this book is to make you a Django expert. By reading this book, you’ll learn the skills needed to develop powerful websites quickly, with code that is clean and easy to maintain. This book is also a programmer’s manual that provides complete coverage of the current Long Term Support (LTS) version of Django. For developers creating applications for commercial and business critical deployments, Mastering Django: Core provides a complete, up-to-date resource for Django 1.8LTS with a stable code-base, security fixes and support out to 2018.
Table of Contents (33 chapters)
Mastering Django: Core
Credits
About the Author
www.PacktPub.com
Preface
Free Chapter
1
Introduction to Django and Getting Started

Simple generic views


The module django.views.generic.base contains simple views that handle a couple of common cases: rendering a template when no view logic is needed and issuing a redirect.

Rendering a template-TemplateView

This view renders a given template, passing it a context with keyword arguments captured in the URL.

Example:

Given the following URLconf:

from django.conf.urls import url 
 
    from myapp.views import HomePageView 
 
    urlpatterns = [ 
        url(r'^$', HomePageView.as_view(), name='home'), 
    ] 

And a sample views.py:

from django.views.generic.base import TemplateView 
from articles.models import Article 
 
class HomePageView(TemplateView): 
 
    template_name = "home.html" 
 
    def get_context_data(self, **kwargs): 
        context = super(HomePageView, self).get_context_data(**kwargs) 
        context['latest_articles'] = Article.objects.all()[:5] 
        return context 

a request to / would render the template home.html, returning a context containing a list of the top 5 articles.

Redirecting to another URL

django.views.generic.base.RedirectView() redirects to a given URL.

The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output.

If the given URL is None, Django will return an HttpResponseGone (410).

Example views.py:

from django.shortcuts import get_object_or_404 
 
from django.views.generic.base import RedirectView 
 
from articles.models import Article 
 
class ArticleCounterRedirectView(RedirectView): 
 
    permanent = False 
    query_string = True 
    pattern_name = 'article-detail' 
 
    def get_redirect_url(self, *args, **kwargs): 
        article = get_object_or_404(Article, pk=kwargs['pk']) 
        article.update_counter() 
        return super(ArticleCounterRedirectView,  
                     self).get_redirect_url(*args, **kwargs) 

Example urls.py:

from django.conf.urls import url 
from django.views.generic.base import RedirectView 
 
from article.views import ArticleCounterRedirectView, ArticleDetail 
 
urlpatterns = [ 
    url(r'^counter/(?P<pk>[0-9]+)/$',  
        ArticleCounterRedirectView.as_view(),  
        name='article-counter'), 
    url(r'^details/(?P<pk>[0-9]+)/$',  
        ArticleDetail.as_view(), 
        name='article-detail'), 
    url(r'^go-to-django/$',  
        RedirectView.as_view(url='http://djangoproject.com'),  
        name='go-to-django'), 
] 

Attributes

url

The URL to redirect to, as a string. Or None to raise a 410 (Gone) HTTP error.

pattern_name

The name of the URL pattern to redirect to. Reversing will be done using the same *args and **kwargs as are passed in for this view.

permanent

Whether the redirect should be permanent. The only difference here is the HTTP status code returned. If True, then the redirect will use status code 301. If False, then the redirect will use status code 302. By default, permanent is True.

query_string

Whether to pass along the GET query string to the new location. If True, then the query string is appended to the URL. If False, then the query string is discarded. By default, query_string is False.

Methods

get_redirect_url(*args, **kwargs) constructs the target URL for redirection.

The default implementation uses url as a starting string and performs expansion of % named parameters in that string using the named groups captured in the URL.

If url is not set, get_redirect_url() tries to reverse the pattern_name using what was captured in the URL (both named and unnamed groups are used).

If requested by query_string, it will also append the query string to the generated URL. Subclasses may implement any behavior they wish, as long as the method returns a redirect-ready URL string.