Common views:

  • View

  • TemplateView

  • RedirectView


1. django.views.generic.base.View

This class is the base class of the general class, other classes are inherited from this class, generally do not use this class, I feel it is simpler to use the function.

[Python]

Plain text view
Copy the code

?
1
2
3
4
5
6
7
8
# views.py
from
django.http
import
HttpResponse
from
django.views.generic
import
View
class
MyView(View):

def
get(
self
, request,
*
args,
*
*
kwargs):

return
HttpResponse(
'Hello, World! '
)








[Python]

Plain text view
Copy the code

?
1
2
3
4
5
6
7
8
# urls.py
from
django.conf.urls
import
patterns, url
from
myapp.views
import
MyView
urlpatterns
=
patterns('',

url(r
'^mine/$'
, MyView.as_view(), name
=
'my-view'
),
)






2. django.views.generic.base.TemplateView

In the get_context_data() function, you can pass some extra content to the template

[Python]

Plain text view
Copy the code

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
# 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
(to) :
5
]

return
context








[Python]

Plain text view
Copy the code

?
1
2
3
4
5
6
7
8
9
# urls.py
from
django.conf.urls
import
patterns, url
from
myapp.views
import
HomePageView
urlpatterns
=
patterns('',

url(r
'^ $'
, HomePageView.as_view(), name
=
'home'
),
)






3. django.views.generic.base.RedirectView

For jumps, the default is permanent redirection (301) and can be used directly in urls.py, very conveniently:

[Python]

Plain text view
Copy the code

?
1
2
3
4
5
6
7
from
django.conf.urls
import
patterns, url
from
django.views.generic.base
import
RedirectView
urlpatterns
=
patterns('',

url(r
'^go-to-django/$'
, RedirectView.as_view(url
=
'http://djangoproject.com'
), name
=
'go-to-django'
),

url(r
'^go-to-ziqiangxuetang/$'
, RedirectView.as_view(url
=
'http://www.ziqiangxuetang.com'
,permant
=
False
), name
=
'go-to-zqxt'
),
)