Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Mastering Django: Core

You're reading from   Mastering Django: Core The Complete Guide to Django 1.8 LTS

Arrow left icon
Product type Paperback
Published in Dec 2016
Publisher
ISBN-13 9781787281141
Length 694 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Nigel George Nigel George
Author Profile Icon Nigel George
Nigel George
Arrow right icon
View More author details
Toc

Table of Contents (33) Chapters Close

Mastering Django: Core
Credits
About the Author
www.PacktPub.com
Preface
1. Introduction to Django and Getting Started FREE CHAPTER 2. Views and URLconfs 3. Templates 4. Models 5. The Django Admin Site 6. Forms 7. Advanced Views and URLconfs 8. Advanced Templates 9. Advanced Models 10. Generic Views 11. User Authentication in Django 12. Testing in Django 13. Deploying Django 14. Generating Non-HTML Content 15. Django Sessions 16. Djangos Cache Framework 17. Django Middleware 18. Internationalization 19. Security in Django 20. More on Installing Django 21. Advanced Database Management Model Definition Reference Database API Reference Generic View Reference Settings Built-in Template Tags and Filters Request and Response Objects Developing Django with Visual Studio

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images