Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added detail views. Added request back into a few methods so decorato…

…rs work again (and tested!)
  • Loading branch information...
commit 6e46bcc16c3df815e4197e7bbfb81bd14a2b2682 1 parent 5beb0cc
@bfirsh authored
View
33 class_based_views/base.py
@@ -3,6 +3,7 @@
from django.core import serializers
from django.core.exceptions import ImproperlyConfigured
from django.template import RequestContext
+from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
class View(object):
@@ -32,19 +33,21 @@ def __init__(self, *args, **kwargs):
def __call__(self, request, *args, **kwargs):
view = copy.copy(self)
- view.request = request
- callback = view.get_callback()
+ view.request = request # FIXME: Maybe remove? Should this be encouraged?
+ callback = view.get_callback(request)
if callback:
- return callback(*args, **kwargs)
+ # The request is passed around with args and kwargs like this so
+ # they appear as views for decorators
+ return callback(request, *args, **kwargs)
allowed_methods = [m for m in view.allowed_methods if hasattr(view, m)]
return http.HttpResponseNotAllowed(allowed_methods)
- def get_callback(self):
+ def get_callback(self, request):
"""
Based on the request's HTTP method, get the callback on this class that
returns a response. If the method isn't allowed, None is returned.
"""
- method = self.request.method.upper()
+ method = request.method.upper()
if method not in self.allowed_methods:
if self.strict_allowed_methods:
return None
@@ -57,8 +60,8 @@ def get_callback(self):
callback = decorator(callback)
return callback
- def GET(self, *args, **kwargs):
- content = self.get_content(*args, **kwargs)
+ def GET(self, request, *args, **kwargs):
+ content = self.get_content(request, *args, **kwargs)
mimetype = self.get_mimetype()
return self.get_response(content, mimetype=mimetype)
@@ -68,14 +71,14 @@ def get_response(self, content, **httpresponse_kwargs):
"""
return http.HttpResponse(content, **httpresponse_kwargs)
- def get_content(self, *args, **kwargs):
+ def get_content(self, request, *args, **kwargs):
"""
Get the content to go in the response.
"""
format = self.get_format()
- return getattr(self, 'render_%s' % format)(*args, **kwargs)
+ return getattr(self, 'render_%s' % format)(request, *args, **kwargs)
- def get_resource(self, *args, **kwargs):
+ def get_resource(self, request, *args, **kwargs):
"""
Get a dictionary representing the resource for this view.
"""
@@ -99,11 +102,11 @@ def get_format(self):
format = self.default_format
return format
- def render_html(self, *args, **kwargs):
+ def render_html(self, request, *args, **kwargs):
"""
Render a template with a given resource
"""
- context = self.get_context(*args, **kwargs)
+ context = self.get_context(request, *args, **kwargs)
return self.get_template().render(context)
def get_template(self):
@@ -142,13 +145,13 @@ def get_template_loader(self):
import django.template.loader
return self.template_loader or django.template.loader
- def get_context(self, *args, **kwargs):
+ def get_context(self, request, *args, **kwargs):
"""
Get the template context. Must return a Context (or subclass) instance.
"""
- resource = self.get_resource(*args, **kwargs)
+ resource = self.get_resource(request, *args, **kwargs)
context_processors = self.get_context_processors()
- return RequestContext(self.request, resource, context_processors)
+ return RequestContext(request, resource, context_processors)
def get_context_processors(self):
"""
View
99 class_based_views/detail.py
@@ -1,7 +1,7 @@
-import re
+from class_based_views import View
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.http import Http404
-from class_based_views import View
+import re
class DetailView(View):
"""
@@ -11,21 +11,32 @@ class DetailView(View):
view will support display of *any* object by overriding `get_object()`.
"""
- queryset = None
- slug_field = 'slug'
- template_object_name = None
- template_name_field = None
-
- def get_object(self, request, pk=None, slug=None, object_id=None, queryset=None):
+ def __init__(self, **kwargs):
+ self._load_config_values(kwargs,
+ queryset = None,
+ slug_field = 'slug',
+ template_resource_name = 'object',
+ template_name_field = None,
+ )
+ super(DetailView, self).__init__(**kwargs)
+
+ def get_resource(self, request, *args, **kwargs):
"""
- Get the object this request wraps. By default this requires
+ Get the resource this request wraps. By default this requires
`self.queryset` and a `pk` or `slug` argument in the URLconf, but
subclasses can override this to return any object.
"""
+ obj = self.get_object(request, *args, **kwargs)
+ return {self.get_template_resource_name(obj): obj}
+
+ def get_object(self, request, pk=None, slug=None):
+ """
+ FIXME: Does separating this out from get_resource suck?
+ This might suck.
+ """
# Use a custom queryset if provided; this is required for subclasses
# like DateDetailView
- if queryset is None:
- queryset = self.get_queryset(request)
+ queryset = self.get_queryset()
# Next, try looking up by primary key.
if pk:
@@ -33,19 +44,9 @@ def get_object(self, request, pk=None, slug=None, object_id=None, queryset=None)
# Next, try looking up by slug.
elif slug:
- slug_field = self.get_slug_field(request)
+ slug_field = self.get_slug_field()
queryset = queryset.filter(**{slug_field: slug})
- # Finally, look for the (deprecated) object_id argument.
- elif object_id:
- import warnings
- warnings.warn(
- "The 'object_id' parameter to generic views is deprecated. "\
- "Use 'pk' instead.",
- PendingDeprecationWarning
- )
- queryset = queryset.filter(pk=object_id)
-
# If none of those are defined, it's an error.
else:
raise AttributeError("Generic detail view %s must be called with "\
@@ -53,12 +54,17 @@ def get_object(self, request, pk=None, slug=None, object_id=None, queryset=None)
% self.__class__.__name__)
try:
- return queryset.get()
+ # FIXME: This is horrible, but is needed for get_template_names
+ # What concerns me about this method of passing data around, is
+ # any change in the order of the methods being called in
+ # superclasses may break it.
+ self.obj = queryset.get()
except ObjectDoesNotExist:
raise Http404("No %s found matching the query" % \
(queryset.model._meta.verbose_name))
-
- def get_queryset(self, request):
+ return self.obj
+
+ def get_queryset(self):
"""
Get the queryset to look an object up against. May not be called if
`get_object` is overridden.
@@ -66,21 +72,23 @@ def get_queryset(self, request):
if self.queryset is None:
raise ImproperlyConfigured("%(cls)s is missing a queryset. Define "\
"%(cls)s.queryset, or override "\
- "%(cls)s.get_object()." % {'cls': self.__class__.__name__})
+ "%(cls)s.get_object()." % {
+ 'cls': self.__class__.__name__
+ })
return self.queryset._clone()
- def get_slug_field(self, request):
+ def get_slug_field(self):
"""
Get the name of a slug field to be used to look up by slug.
"""
return self.slug_field
- def get_template_names(self, request, obj):
+ def get_template_names(self):
"""
Return a list of template names to be used for the request. Must return
a list. May not be called if get_template is overridden.
"""
- names = super(DetailView, self).get_template_names(request, obj)
+ names = super(DetailView, self).get_template_names()
# If self.template_name_field is set, grab the value of the field
# of that name from the object; this is the most specific template
@@ -92,30 +100,21 @@ def get_template_names(self, request, obj):
# The least-specific option is the default <app>/<model>_detail.html;
# only use this if the object in question is a model.
- if hasattr(obj, '_meta'):
- names.append("%s/%s_detail.html" % (obj._meta.app_label,
- obj._meta.object_name.lower()))
+ if hasattr(self, 'obj') and hasattr(self.obj, '_meta'):
+ names.append("%s/%s_detail.html" % (
+ self.obj._meta.app_label,
+ self.obj._meta.object_name.lower()
+ ))
return names
- def get_context(self, request, obj):
+ def get_template_resource_name(self, obj):
"""
- Get the context. Must return a Context (or subclass) instance.
- """
- context = super(DetailView, self).get_context(request, obj, {'object': obj})
- nicename = self.get_template_object_name(request, obj)
- if nicename:
- context[nicename] = obj
- return context
-
- def get_template_object_name(self, request, obj):
+ Get the name to use for the resource.
"""
- Get the name of the object to use in the context.
- """
- if self.template_object_name:
- return self.template_object_name
- elif hasattr(obj, '_meta'):
- return re.sub('[^a-zA-Z0-9]+', '_', obj._meta.verbose_name.lower())
+ if hasattr(obj, '_meta'):
+ return re.sub('[^a-zA-Z0-9]+', '_',
+ obj._meta.verbose_name.lower())
else:
- return None
-
+ return self.template_resource_name
+
View
0  class_based_views/tests/templates/views/about.html → class_based_views/tests/templates/tests/about.html
File renamed without changes
View
0  ...sed_views/tests/templates/views/apple_detail.html → ...sed_views/tests/templates/tests/apple_detail.html
File renamed without changes
View
0  ...ed_views/tests/templates/views/author_detail.html → ...ed_views/tests/templates/tests/author_detail.html
File renamed without changes
View
0  ...sed_views/tests/templates/views/book_archive.html → ...sed_views/tests/templates/tests/book_archive.html
File renamed without changes
View
0  ...views/tests/templates/views/book_archive_day.html → ...views/tests/templates/tests/book_archive_day.html
File renamed without changes
View
0  ...ews/tests/templates/views/book_archive_month.html → ...ews/tests/templates/tests/book_archive_month.html
File renamed without changes
View
0  ...iews/tests/templates/views/book_archive_week.html → ...iews/tests/templates/tests/book_archive_week.html
File renamed without changes
View
0  ...iews/tests/templates/views/book_archive_year.html → ...iews/tests/templates/tests/book_archive_year.html
File renamed without changes
View
0  ...ased_views/tests/templates/views/book_detail.html → ...ased_views/tests/templates/tests/book_detail.html
File renamed without changes
View
0  class_based_views/tests/templates/views/detail.html → class_based_views/tests/templates/tests/detail.html
File renamed without changes
View
0  class_based_views/tests/templates/views/list.html → class_based_views/tests/templates/tests/list.html
File renamed without changes
View
3  class_based_views/tests/tests/__init__.py
@@ -1 +1,2 @@
-from class_based_views.tests.tests.base import *
+from class_based_views.tests.tests.base import ViewTest, DecoratorViewTest
+from class_based_views.tests.tests.detail import DetailViewTest
View
35 class_based_views/tests/tests/base.py
@@ -1,11 +1,12 @@
from class_based_views.base import View
from class_based_views.tests.utils import RequestFactory
from django.core.exceptions import ImproperlyConfigured
+from django.test import TestCase
from django.utils import simplejson
import unittest
class AboutView(View):
- template_name = 'views/about.html'
+ template_name = 'tests/about.html'
class PostAboutView(AboutView):
@@ -14,33 +15,33 @@ class PostAboutView(AboutView):
class StrictAboutView(AboutView):
strict_allowed_methods = True
-
+
class HashView(View):
- def get_content(self):
+ def get_content(self, request):
return unicode(hash(self))
class JsonView(View):
- template_name = 'views/apple_detail.html'
+ template_name = 'tests/apple_detail.html'
def __init__(self, *args, **kwargs):
super(JsonView, self).__init__(*args, **kwargs)
self.allowed_formats.append('json')
self.format_mimetypes['json'] = 'application/json'
- def render_json(self, *args, **kwargs):
- return simplejson.dumps(self.get_resource(*args, **kwargs))
+ def render_json(self, request, *args, **kwargs):
+ return simplejson.dumps(self.get_resource(request, *args, **kwargs))
- def get_resource(self, color='red', **kwargs):
+ def get_resource(self, request, color='red', **kwargs):
return {'apple': {
'color': color,
}}
class ContextArgsJsonView(JsonView):
- def get_context(self, extra='', **kwargs):
- context = super(ContextArgsJsonView, self).get_context()
+ def get_context(self, request, extra='', **kwargs):
+ context = super(ContextArgsJsonView, self).get_context(request)
context['extra'] = extra
return context
@@ -50,8 +51,8 @@ class DefaultJsonView(JsonView):
class ContextJsonView(JsonView):
- def get_context(self, *args, **kwargs):
- context = super(ContextJsonView, self).get_context(*args, **kwargs)
+ def get_context(self, request, *args, **kwargs):
+ context = super(ContextJsonView, self).get_context(request, *args, **kwargs)
context['tasty'] = True
return context
@@ -191,4 +192,16 @@ def test_context_arguments(self):
response.content,
'This is a red apple. That is good'
)
+
+class DecoratorViewTest(TestCase):
+ urls = 'class_based_views.tests.urls'
+
+ def test_decorators(self):
+ """
+ Test any decorators applied with the ``decorators`` attribute are
+ applied.
+ """
+ res = self.client.get('/about/login-required/')
+ self.assertEqual(res.status_code, 302)
+ self.assertRedirects(res, 'http://testserver/accounts/login/?next=/about/login-required/')
View
33 class_based_views/tests/tests/detail.py
@@ -0,0 +1,33 @@
+from class_based_views.tests.models import Author
+from django.core.exceptions import ImproperlyConfigured
+from django.test import TestCase
+
+class DetailViewTest(TestCase):
+ fixtures = ['generic-views-test-data.json']
+ urls = 'class_based_views.tests.urls'
+
+ def test_simple_object(self):
+ res = self.client.get('/detail/obj/')
+ self.assertEqual(res.status_code, 200)
+ self.assertEqual(res.context['object'], {'foo': 'bar'})
+ self.assertTemplateUsed(res, 'tests/detail.html')
+
+ def test_detail_by_pk(self):
+ res = self.client.get('/detail/author/1/')
+ self.assertEqual(res.status_code, 200)
+ #self.assertEqual(res.context['object'], Author.objects.get(pk=1))
+ self.assertEqual(res.context['author'], Author.objects.get(pk=1))
+ self.assertTemplateUsed(res, 'tests/author_detail.html')
+
+ def test_detail_by_slug(self):
+ res = self.client.get('/detail/author/byslug/scott-rosenberg/')
+ self.assertEqual(res.status_code, 200)
+ #self.assertEqual(res.context['object'], Author.objects.get(slug='scott-rosenberg'))
+ self.assertEqual(res.context['author'], Author.objects.get(slug='scott-rosenberg'))
+ self.assertTemplateUsed(res, 'tests/author_detail.html')
+
+ def test_invalid_url(self):
+ self.assertRaises(AttributeError, self.client.get, '/detail/author/invalid/url/')
+
+ def test_invalid_queryset(self):
+ self.assertRaises(ImproperlyConfigured, self.client.get, '/detail/author/invalid/qs/')
View
122 class_based_views/tests/urls.py
@@ -2,73 +2,75 @@
from django.conf.urls.defaults import *
urlpatterns = patterns('',
- # ListView
- (r'^list/dict/$', views.DictList()),
- url(r'^list/authors/$', views.AuthorList(), name="authors_list"),
- (r'^list/authors/paginated/$', views.AuthorList(paginate_by=30)),
- (r'^list/authors/paginated/(?P<page>\d+)/$', views.AuthorList(paginate_by=30)),
- (r'^list/authors/notempty/$', views.AuthorList(allow_empty=False)),
- (r'^list/authors/template_object_name/$', views.AuthorList(template_object_name='author')),
- (r'^list/authors/invalid/$', views.AuthorList(queryset=None)),
-
+ # base
+ (r'^about/login-required/$', views.DecoratedAboutView()),
+
# DetailView
(r'^detail/obj/$', views.ObjectDetail()),
url(r'^detail/author/(?P<pk>\d+)/$', views.AuthorDetail(), name="author_detail"),
- (r'^detail/author/(?P<pk>\d+)/restricted/$', views.AuthorDetailRestricted()),
(r'^detail/author/byslug/(?P<slug>[\w-]+)/$', views.AuthorDetail()),
(r'^detail/author/invalid/url/$', views.AuthorDetail()),
(r'^detail/author/invalid/qs/$', views.AuthorDetail(queryset=None)),
- # EditView
- (r'^edit/authors/create/$', views.AuthorCreate()),
- (r'^edit/authors/create/restricted/$', views.AuthorCreateRestricted()),
- (r'^edit/author/(?P<pk>\d+)/update/$', views.AuthorUpdate()),
- (r'^edit/author/(?P<pk>\d+)/delete/$', views.AuthorDelete()),
-
- # ArchiveView
- (r'^dates/books/$', views.BookArchive()),
- (r'^dates/books/invalid/$', views.BookArchive(queryset=None)),
-
- # YearView
- # Mixing keyword and possitional captures below is intentional; the views
- # ought to be able to accept either.
- (r'^dates/books/(?P<year>\d{4})/$', views.BookYearArchive()),
- (r'^dates/books/(\d{4})/make_object_list/$', views.BookYearArchive(make_object_list=True)),
- (r'^dates/books/(\d{4})/allow_empty/$', views.BookYearArchive(allow_empty=True)),
- (r'^dates/books/(\d{4})/allow_future/$', views.BookYearArchive(allow_future=True)),
- (r'^dates/books/no_year/$', views.BookYearArchive()),
-
- # MonthView
- (r'^dates/books/(\d{4})/([a-z]{3})/$', views.BookMonthArchive()),
- (r'^dates/books/(\d{4})/(\d{1,2})/$', views.BookMonthArchive(month_format='%m')),
- (r'^dates/books/(\d{4})/([a-z]{3})/allow_empty/$', views.BookMonthArchive(allow_empty=True)),
- (r'^dates/books/(\d{4})/([a-z]{3})/allow_future/$', views.BookMonthArchive(allow_future=True)),
- (r'^dates/books/(\d{4})/no_month/$', views.BookMonthArchive()),
-
- # WeekView
- (r'^dates/books/(\d{4})/week/(\d{1,2})/$', views.BookWeekArchive()),
- (r'^dates/books/(\d{4})/week/(\d{1,2})/allow_empty/$', views.BookWeekArchive(allow_empty=True)),
- (r'^dates/books/(\d{4})/week/(\d{1,2})/allow_future/$', views.BookWeekArchive(allow_future=True)),
- (r'^dates/books/(\d{4})/week/no_week/$', views.BookWeekArchive()),
-
- # DayView
- (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/$', views.BookDayArchive()),
- (r'^dates/books/(\d{4})/(\d{1,2})/(\d{1,2})/$', views.BookDayArchive(month_format='%m')),
- (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/allow_empty/$', views.BookDayArchive(allow_empty=True)),
- (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/allow_future/$', views.BookDayArchive(allow_future=True)),
- (r'^dates/books/(\d{4})/([a-z]{3})/no_day/$', views.BookDayArchive()),
-
- # TodayView
- (r'dates/books/today/$', views.BookTodayArchive()),
- (r'dates/books/today/allow_empty/$', views.BookTodayArchive(allow_empty=True)),
-
- # DateDetailView
- (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/(\d+)/$', views.BookDetail()),
- (r'^dates/books/(\d{4})/(\d{1,2})/(\d{1,2})/(\d+)/$', views.BookDetail(month_format='%m')),
- (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/(\d+)/allow_future/$', views.BookDetail(allow_future=True)),
- (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/nopk/$', views.BookDetail()),
-
- (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{1,2})/byslug/(?P<slug>[\w-]+)/$', views.BookDetail()),
+ # # EditView
+ # (r'^edit/authors/create/$', views.AuthorCreate()),
+ # (r'^edit/authors/create/restricted/$', views.AuthorCreateRestricted()),
+ # (r'^edit/author/(?P<pk>\d+)/update/$', views.AuthorUpdate()),
+ # (r'^edit/author/(?P<pk>\d+)/delete/$', views.AuthorDelete()),
+ #
+ # # ArchiveView
+ # (r'^dates/books/$', views.BookArchive()),
+ # (r'^dates/books/invalid/$', views.BookArchive(queryset=None)),
+ #
+ # # ListView
+ # (r'^list/dict/$', views.DictList()),
+ # url(r'^list/authors/$', views.AuthorList(), name="authors_list"),
+ # (r'^list/authors/paginated/$', views.AuthorList(paginate_by=30)),
+ # (r'^list/authors/paginated/(?P<page>\d+)/$', views.AuthorList(paginate_by=30)),
+ # (r'^list/authors/notempty/$', views.AuthorList(allow_empty=False)),
+ # (r'^list/authors/template_object_name/$', views.AuthorList(template_object_name='author')),
+ # (r'^list/authors/invalid/$', views.AuthorList(queryset=None)),
+ #
+ # # YearView
+ # # Mixing keyword and possitional captures below is intentional; the views
+ # # ought to be able to accept either.
+ # (r'^dates/books/(?P<year>\d{4})/$', views.BookYearArchive()),
+ # (r'^dates/books/(\d{4})/make_object_list/$', views.BookYearArchive(make_object_list=True)),
+ # (r'^dates/books/(\d{4})/allow_empty/$', views.BookYearArchive(allow_empty=True)),
+ # (r'^dates/books/(\d{4})/allow_future/$', views.BookYearArchive(allow_future=True)),
+ # (r'^dates/books/no_year/$', views.BookYearArchive()),
+ #
+ # # MonthView
+ # (r'^dates/books/(\d{4})/([a-z]{3})/$', views.BookMonthArchive()),
+ # (r'^dates/books/(\d{4})/(\d{1,2})/$', views.BookMonthArchive(month_format='%m')),
+ # (r'^dates/books/(\d{4})/([a-z]{3})/allow_empty/$', views.BookMonthArchive(allow_empty=True)),
+ # (r'^dates/books/(\d{4})/([a-z]{3})/allow_future/$', views.BookMonthArchive(allow_future=True)),
+ # (r'^dates/books/(\d{4})/no_month/$', views.BookMonthArchive()),
+ #
+ # # WeekView
+ # (r'^dates/books/(\d{4})/week/(\d{1,2})/$', views.BookWeekArchive()),
+ # (r'^dates/books/(\d{4})/week/(\d{1,2})/allow_empty/$', views.BookWeekArchive(allow_empty=True)),
+ # (r'^dates/books/(\d{4})/week/(\d{1,2})/allow_future/$', views.BookWeekArchive(allow_future=True)),
+ # (r'^dates/books/(\d{4})/week/no_week/$', views.BookWeekArchive()),
+ #
+ # # DayView
+ # (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/$', views.BookDayArchive()),
+ # (r'^dates/books/(\d{4})/(\d{1,2})/(\d{1,2})/$', views.BookDayArchive(month_format='%m')),
+ # (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/allow_empty/$', views.BookDayArchive(allow_empty=True)),
+ # (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/allow_future/$', views.BookDayArchive(allow_future=True)),
+ # (r'^dates/books/(\d{4})/([a-z]{3})/no_day/$', views.BookDayArchive()),
+ #
+ # # TodayView
+ # (r'dates/books/today/$', views.BookTodayArchive()),
+ # (r'dates/books/today/allow_empty/$', views.BookTodayArchive(allow_empty=True)),
+ #
+ # # DateDetailView
+ # (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/(\d+)/$', views.BookDetail()),
+ # (r'^dates/books/(\d{4})/(\d{1,2})/(\d{1,2})/(\d+)/$', views.BookDetail(month_format='%m')),
+ # (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/(\d+)/allow_future/$', views.BookDetail(allow_future=True)),
+ # (r'^dates/books/(\d{4})/([a-z]{3})/(\d{1,2})/nopk/$', views.BookDetail()),
+ #
+ # (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{1,2})/byslug/(?P<slug>[\w-]+)/$', views.BookDetail()),
# Useful for testing redirects
(r'^accounts/login/$', 'django.contrib.auth.views.login')
View
181 class_based_views/tests/views.py
@@ -1,100 +1,107 @@
-from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
+from django.core.urlresolvers import reverse
from django.utils.decorators import method_decorator
-from models import Author, Book
-from forms import AuthorForm
+from class_based_views.tests.models import Author, Book
+from class_based_views.tests.forms import AuthorForm
import class_based_views
-class DictList(class_based_views.ListView):
- """A ListView that doesn't use a model."""
- items = [
- {'first': 'John', 'last': 'Lennon'},
- {'last': 'Yoko', 'last': 'Ono'}
- ]
- template_name = 'tests/list.html'
-
-class AuthorList(class_based_views.ListView):
- queryset = Author.objects.all()
- template_name = 'tests/list.html'
-
-class AuthorDetail(class_based_views.DetailView):
- queryset = Author.objects.all()
-
-class AuthorDetailRestricted(AuthorDetail):
- decorators = [login_required, ]
-
-class AuthorCreate(class_based_views.CreateView):
- queryset = Author.objects.all()
- template_name = 'tests/list.html'
- methods = ['GET', 'POST']
-
- def get_form(self, request, obj, *args, **kwargs):
- return AuthorForm(request.POST or None)
-
- def process_form(self, request, obj, data):
- Author.objects.create(**data)
-
- def redirect_to(self, request, obj):
- return reverse('authors_list')
-
-
-class AuthorCreateRestricted(AuthorCreate):
- post = method_decorator(login_required)(AuthorCreate.post)
-
-
-class AuthorUpdate(class_based_views.UpdateView):
- queryset = Author.objects.all()
- template_name = 'tests/detail.html'
- methods = ['GET', 'POST', 'PUT']
-
- def get_form(self, request, obj, *args, **kwargs):
- return AuthorForm(request.REQUEST or None)
-
- def process_form(self, request, obj, data):
- for k, v in data.iteritems():
- setattr(obj, k, v)
- obj.save()
-
- def redirect_to(self, request, obj):
- return reverse('author_detail', args=[obj.id,])
-
-
-class AuthorDelete(class_based_views.DeleteView):
- queryset = Author.objects.all()
- template_name = 'tests/detail.html'
- methods = ['GET', 'POST', 'DELETE']
-
- def redirect_to(self, request, obj):
- return reverse('authors_list')
-
-
class ObjectDetail(class_based_views.DetailView):
template_name = 'tests/detail.html'
+
def get_object(self, request, **kwargs):
return {'foo': 'bar'}
-class BookConfig(object):
- queryset = Book.objects.all()
- date_field = 'pubdate'
-
-class BookArchive(BookConfig, class_based_views.ArchiveView):
- pass
-
-class BookYearArchive(BookConfig, class_based_views.YearView):
- pass
-class BookMonthArchive(BookConfig, class_based_views.MonthView):
- pass
-
-class BookWeekArchive(BookConfig, class_based_views.WeekView):
- pass
-
-class BookDayArchive(BookConfig, class_based_views.DayView):
- pass
+class AuthorDetail(class_based_views.DetailView):
+ queryset = Author.objects.all()
-class BookTodayArchive(BookConfig, class_based_views.TodayView):
- pass
-class BookDetail(BookConfig, class_based_views.DateDetailView):
- pass
+class DecoratedAboutView(class_based_views.View):
+ template_name = 'tests/about.html'
+ decorators = [login_required,]
+
+
+
+# class DictList(class_based_views.ListView):
+# """A ListView that doesn't use a model."""
+# items = [
+# {'first': 'John', 'last': 'Lennon'},
+# {'last': 'Yoko', 'last': 'Ono'}
+# ]
+# template_name = 'tests/list.html'
+#
+# class AuthorList(class_based_views.ListView):
+# queryset = Author.objects.all()
+# template_name = 'tests/list.html'
+
+
+
+# class AuthorCreate(class_based_views.CreateView):
+# queryset = Author.objects.all()
+# template_name = 'tests/list.html'
+# methods = ['GET', 'POST']
+#
+# def get_form(self, request, obj, *args, **kwargs):
+# return AuthorForm(request.POST or None)
+#
+# def process_form(self, request, obj, data):
+# Author.objects.create(**data)
+#
+# def redirect_to(self, request, obj):
+# return reverse('authors_list')
+#
+#
+# class AuthorCreateRestricted(AuthorCreate):
+# post = method_decorator(login_required)(AuthorCreate.post)
+#
+#
+# class AuthorUpdate(class_based_views.UpdateView):
+# queryset = Author.objects.all()
+# template_name = 'tests/detail.html'
+# methods = ['GET', 'POST', 'PUT']
+#
+# def get_form(self, request, obj, *args, **kwargs):
+# return AuthorForm(request.REQUEST or None)
+#
+# def process_form(self, request, obj, data):
+# for k, v in data.iteritems():
+# setattr(obj, k, v)
+# obj.save()
+#
+# def redirect_to(self, request, obj):
+# return reverse('author_detail', args=[obj.id,])
+#
+#
+# class AuthorDelete(class_based_views.DeleteView):
+# queryset = Author.objects.all()
+# template_name = 'tests/detail.html'
+# methods = ['GET', 'POST', 'DELETE']
+#
+# def redirect_to(self, request, obj):
+# return reverse('authors_list')
+
+# class BookConfig(object):
+# queryset = Book.objects.all()
+# date_field = 'pubdate'
+#
+# class BookArchive(BookConfig, class_based_views.ArchiveView):
+# pass
+#
+# class BookYearArchive(BookConfig, class_based_views.YearView):
+# pass
+#
+# class BookMonthArchive(BookConfig, class_based_views.MonthView):
+# pass
+#
+# class BookWeekArchive(BookConfig, class_based_views.WeekView):
+# pass
+#
+# class BookDayArchive(BookConfig, class_based_views.DayView):
+# pass
+#
+# class BookTodayArchive(BookConfig, class_based_views.TodayView):
+# pass
+#
+# class BookDetail(BookConfig, class_based_views.DateDetailView):
+# pass
Please sign in to comment.
Something went wrong with that request. Please try again.