desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Accepts a template object, path-to-template or list of paths'
def resolve_template(self, template):
if isinstance(template, (list, tuple)): return loader.select_template(template) elif isinstance(template, basestring): return loader.get_template(template) else: return template
'Converts context data into a full Context object (assuming it isn\'t already a Context object).'
def resolve_context(self, context):
if isinstance(context, Context): return context else: return Context(context)
'Returns the freshly rendered content for the template and context described by the TemplateResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property.'
@property def rendered_content(self):
template = self.resolve_template(self.template_name) context = self.resolve_context(self.context_data) content = template.render(context) return content
'Adds a new post-rendering callback. If the response has already been rendered, invoke the callback immediately.'
def add_post_render_callback(self, callback):
if self._is_rendered: callback(self) else: self._post_render_callbacks.append(callback)
'Renders (thereby finalizing) the content of the response. If the content has already been rendered, this is a no-op. Returns the baked response instance.'
def render(self):
retval = self if (not self._is_rendered): self._set_content(self.rendered_content) for post_callback in self._post_render_callbacks: newretval = post_callback(retval) if (newretval is not None): retval = newretval return retval
'Sets the content for the response'
def _set_content(self, value):
super(SimpleTemplateResponse, self)._set_content(value) self._is_rendered = True
'Convert context data into a full RequestContext object (assuming it isn\'t already a Context object).'
def resolve_context(self, context):
if isinstance(context, Context): return context return RequestContext(self._request, context, current_app=self._current_app)
'Returns a tuple containing the source and origin for the given template name.'
def load_template_source(self, template_name, template_dirs=None):
raise NotImplementedError
'Resets any state maintained by the loader instance (e.g., cached templates or cached loader modules).'
def reset(self):
pass
'Empty the template cache.'
def reset(self):
self.template_cache.clear()
'Loads templates from Python eggs via pkg_resource.resource_string. For every installed app, it tries to get the resource (app, template_name).'
def load_template_source(self, template_name, template_dirs=None):
if (resource_string is not None): pkg_name = ('templates/' + template_name) for app in settings.INSTALLED_APPS: try: return (resource_string(app, pkg_name).decode(settings.FILE_CHARSET), ('egg:%s:%s' % (app, pkg_name))) except: pass raise T...
'Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don\'t lie inside one of the template dirs are excluded from the result set, for security reasons.'
def get_template_sources(self, template_name, template_dirs=None):
if (not template_dirs): template_dirs = settings.TEMPLATE_DIRS for template_dir in template_dirs: try: (yield safe_join(template_dir, template_name)) except UnicodeDecodeError: raise except ValueError: pass
'Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don\'t lie inside one of the template dirs are excluded from the result set, for security reasons.'
def get_template_sources(self, template_name, template_dirs=None):
if (not template_dirs): template_dirs = app_template_dirs for template_dir in template_dirs: try: (yield safe_join(template_dir, template_name)) except UnicodeDecodeError: raise except ValueError: pass
'Returns what to display in error messages for this node'
def display(self):
return self.id
'Set a variable in the current context'
def __setitem__(self, key, value):
self.dicts[(-1)][key] = value
'Get a variable\'s value, starting at the current context and going upward'
def __getitem__(self, key):
for d in reversed(self.dicts): if (key in d): return d[key] raise KeyError(key)
'Delete a variable from the current context'
def __delitem__(self, key):
del self.dicts[(-1)][key]
'Returns a new context with the same properties, but with only the values given in \'values\' stored.'
def new(self, values=None):
new_context = copy(self) new_context._reset_dicts(values) return new_context
'Pushes other_dict to the stack of dictionaries in the Context'
def update(self, other_dict):
if (not hasattr(other_dict, '__getitem__')): raise TypeError('other_dict must be a mapping (dictionary-like) object.') self.dicts.append(other_dict) return other_dict
'Return a list of tokens from a given template_string'
def tokenize(self):
(result, upto) = ([], 0) for match in tag_re.finditer(self.template_string): (start, end) = match.span() if (start > upto): result.append(self.create_token(self.template_string[upto:start], (upto, start), False)) upto = start result.append(self.create_token(self.t...
'The flatpage admin form correctly validates urls'
def test_flatpage_admin_form_url_validation(self):
self.assertTrue(FlatpageForm(data=dict(url='/new_flatpage/', **self.form_data)).is_valid()) self.assertTrue(FlatpageForm(data=dict(url='/some.special~chars/', **self.form_data)).is_valid()) self.assertTrue(FlatpageForm(data=dict(url='/some.very_special~chars-here/', **self.form_data)).is_valid()) self.a...
'The flatpage admin form correctly enforces url uniqueness among flatpages of the same site'
def test_flatpage_admin_form_url_uniqueness_validation(self):
data = dict(url='/myflatpage1/', **self.form_data) FlatpageForm(data=data).save() f = FlatpageForm(data=data) self.assertFalse(f.is_valid()) self.assertEqual(f.errors, {'__all__': [u'Flatpage with url /myflatpage1/ already exists for site example.com']})
'Existing flatpages can be edited in the admin form without triggering the url-uniqueness validation.'
def test_flatpage_admin_form_edit(self):
existing = FlatPage.objects.create(url='/myflatpage1/', title='Some page', content='The content') existing.sites.add(settings.SITE_ID) data = dict(url='/myflatpage1/', **self.form_data) f = FlatpageForm(data=data, instance=existing) self.assertTrue(f.is_valid(), f.errors) updated = f.save(...
'A flatpage can be served through a view, even when the middleware is in use'
def test_view_flatpage(self):
response = self.client.get('/flatpage_root/flatpage/') self.assertEqual(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>")
'A non-existent flatpage raises 404 when served through a view, even when the middleware is in use'
def test_view_non_existent_flatpage(self):
response = self.client.get('/flatpage_root/no_such_flatpage/') self.assertEqual(response.status_code, 404)
'A flatpage served through a view can require authentication'
def test_view_authenticated_flatpage(self):
response = self.client.get('/flatpage_root/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/') User.objects.create_user('testuser', 'test@example.com', 's3krit') self.client.login(username='testuser', password='s3krit') response = self.client.get('/flatpage_root/...
'A flatpage can be served by the fallback middlware'
def test_fallback_flatpage(self):
response = self.client.get('/flatpage/') self.assertEqual(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>")
'A non-existent flatpage raises a 404 when served by the fallback middlware'
def test_fallback_non_existent_flatpage(self):
response = self.client.get('/no_such_flatpage/') self.assertEqual(response.status_code, 404)
'POSTing to a flatpage served through a view will raise a CSRF error if no token is provided (Refs #14156)'
def test_post_view_flatpage(self):
response = self.client.post('/flatpage_root/flatpage/') self.assertEqual(response.status_code, 403)
'POSTing to a flatpage served by the middleware will raise a CSRF error if no token is provided (Refs #14156)'
def test_post_fallback_flatpage(self):
response = self.client.post('/flatpage/') self.assertEqual(response.status_code, 403)
'POSTing to an unknown page isn\'t caught as a 403 CSRF error'
def test_post_unknown_page(self):
response = self.client.post('/no_such_page/') self.assertEqual(response.status_code, 404)
'The flatpage template tag retrives unregistered prefixed flatpages by default'
def test_get_flatpages_tag(self):
out = Template('{% load flatpages %}{% get_flatpages as flatpages %}{% for page in flatpages %}{{ page.title }},{% endfor %}').render(Context()) self.assertEqual(out, 'A Flatpage,A Nested Flatpage,')
'The flatpage template tag retrives unregistered flatpages for an anonymous user'
def test_get_flatpages_tag_for_anon_user(self):
out = Template('{% load flatpages %}{% get_flatpages for anonuser as flatpages %}{% for page in flatpages %}{{ page.title }},{% endfor %}').render(Context({'anonuser': AnonymousUser()})) self.assertEqual(out, 'A Flatpage,A Nested Flatpage,')
'The flatpage template tag retrives all flatpages for an authenticated user'
def test_get_flatpages_tag_for_user(self):
out = Template('{% load flatpages %}{% get_flatpages for me as flatpages %}{% for page in flatpages %}{{ page.title }},{% endfor %}').render(Context({'me': self.me})) self.assertEqual(out, 'A Flatpage,A Nested Flatpage,Sekrit Nested Flatpage,S...
'The flatpage template tag retrives unregistered prefixed flatpages by default'
def test_get_flatpages_with_prefix(self):
out = Template("{% load flatpages %}{% get_flatpages '/location/' as location_flatpages %}{% for page in location_flatpages %}{{ page.title }},{% endfor %}").render(Context()) self.assertEqual(out, 'A Nested Flatpage,')
'The flatpage template tag retrives unregistered prefixed flatpages for an anonymous user'
def test_get_flatpages_with_prefix_for_anon_user(self):
out = Template("{% load flatpages %}{% get_flatpages '/location/' for anonuser as location_flatpages %}{% for page in location_flatpages %}{{ page.title }},{% endfor %}").render(Context({'anonuser': AnonymousUser()})) self.assertEqual(out, 'A Nested ...
'The flatpage template tag retrive prefixed flatpages for an authenticated user'
def test_get_flatpages_with_prefix_for_user(self):
out = Template("{% load flatpages %}{% get_flatpages '/location/' for me as location_flatpages %}{% for page in location_flatpages %}{{ page.title }},{% endfor %}").render(Context({'me': self.me})) self.assertEqual(out, 'A Nested Flatpage,Sekrit ...
'The prefix for the flatpage template tag can be a template variable'
def test_get_flatpages_with_variable_prefix(self):
out = Template('{% load flatpages %}{% get_flatpages location_prefix as location_flatpages %}{% for page in location_flatpages %}{{ page.title }},{% endfor %}').render(Context({'location_prefix': '/location/'})) self.assertEqual(out, 'A Nested Flatpage,')...
'There are various ways that the flatpages template tag won\'t parse'
def test_parsing_errors(self):
render = (lambda t: Template(t).render(Context())) self.assertRaises(TemplateSyntaxError, render, '{% load flatpages %}{% get_flatpages %}') self.assertRaises(TemplateSyntaxError, render, '{% load flatpages %}{% get_flatpages as %}') self.assertRaises(TemplateSyntaxError...
'A flatpage can be served through a view'
def test_view_flatpage(self):
response = self.client.get('/flatpage_root/flatpage/') self.assertEqual(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>")
'A non-existent flatpage raises 404 when served through a view'
def test_view_non_existent_flatpage(self):
response = self.client.get('/flatpage_root/no_such_flatpage/') self.assertEqual(response.status_code, 404)
'A flatpage served through a view can require authentication'
def test_view_authenticated_flatpage(self):
response = self.client.get('/flatpage_root/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/') User.objects.create_user('testuser', 'test@example.com', 's3krit') self.client.login(username='testuser', password='s3krit') response = self.client.get('/flatpage_root/...
'A fallback flatpage won\'t be served if the middleware is disabled'
def test_fallback_flatpage(self):
response = self.client.get('/flatpage/') self.assertEqual(response.status_code, 404)
'A non-existent flatpage won\'t be served if the fallback middlware is disabled'
def test_fallback_non_existent_flatpage(self):
response = self.client.get('/no_such_flatpage/') self.assertEqual(response.status_code, 404)
'A flatpage with special chars in the URL can be served through a view'
def test_view_flatpage_special_chars(self):
fp = FlatPage.objects.create(url='/some.very_special~chars-here/', title='A very special page', content="Isn't it special!", enable_comments=False, registration_required=False) fp.sites.add(settings.SITE_ID) response = self.client.get('/flatpage_root/some.very_special~chars-here/') self.a...
'A flatpage can be served through a view and should add a slash'
def test_redirect_view_flatpage(self):
response = self.client.get('/flatpage_root/flatpage') self.assertRedirects(response, '/flatpage_root/flatpage/', status_code=301)
'A non-existent flatpage raises 404 when served through a view and should not add a slash'
def test_redirect_view_non_existent_flatpage(self):
response = self.client.get('/flatpage_root/no_such_flatpage') self.assertEqual(response.status_code, 404)
'A fallback flatpage won\'t be served if the middleware is disabled and should not add a slash'
def test_redirect_fallback_flatpage(self):
response = self.client.get('/flatpage') self.assertEqual(response.status_code, 404)
'A non-existent flatpage won\'t be served if the fallback middlware is disabled and should not add a slash'
def test_redirect_fallback_non_existent_flatpage(self):
response = self.client.get('/no_such_flatpage') self.assertEqual(response.status_code, 404)
'A flatpage with special chars in the URL can be served through a view and should add a slash'
def test_redirect_view_flatpage_special_chars(self):
fp = FlatPage.objects.create(url='/some.very_special~chars-here/', title='A very special page', content="Isn't it special!", enable_comments=False, registration_required=False) fp.sites.add(1) response = self.client.get('/flatpage_root/some.very_special~chars-here') self.assertRedirects(r...
'A flatpage can be served through a view, even when the middleware is in use'
def test_view_flatpage(self):
response = self.client.get('/flatpage_root/flatpage/') self.assertEqual(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>")
'A non-existent flatpage raises 404 when served through a view, even when the middleware is in use'
def test_view_non_existent_flatpage(self):
response = self.client.get('/flatpage_root/no_such_flatpage/') self.assertEqual(response.status_code, 404)
'A flatpage served through a view can require authentication'
def test_view_authenticated_flatpage(self):
response = self.client.get('/flatpage_root/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/') User.objects.create_user('testuser', 'test@example.com', 's3krit') self.client.login(username='testuser', password='s3krit') response = self.client.get('/flatpage_root/...
'A flatpage can be served by the fallback middlware'
def test_fallback_flatpage(self):
response = self.client.get('/flatpage/') self.assertEqual(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>")
'A non-existent flatpage raises a 404 when served by the fallback middlware'
def test_fallback_non_existent_flatpage(self):
response = self.client.get('/no_such_flatpage/') self.assertEqual(response.status_code, 404)
'A flatpage served by the middleware can require authentication'
def test_fallback_authenticated_flatpage(self):
response = self.client.get('/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/sekrit/') User.objects.create_user('testuser', 'test@example.com', 's3krit') self.client.login(username='testuser', password='s3krit') response = self.client.get('/sekrit/') self.assertEqual(response.st...
'A flatpage with special chars in the URL can be served by the fallback middleware'
def test_fallback_flatpage_special_chars(self):
fp = FlatPage.objects.create(url='/some.very_special~chars-here/', title='A very special page', content="Isn't it special!", enable_comments=False, registration_required=False) fp.sites.add(1) response = self.client.get('/some.very_special~chars-here/') self.assertEqual(response.status_co...
'A flatpage can be served through a view and should add a slash'
def test_redirect_view_flatpage(self):
response = self.client.get('/flatpage_root/flatpage') self.assertRedirects(response, '/flatpage_root/flatpage/', status_code=301)
'A non-existent flatpage raises 404 when served through a view and should not add a slash'
def test_redirect_view_non_existent_flatpage(self):
response = self.client.get('/flatpage_root/no_such_flatpage') self.assertEqual(response.status_code, 404)
'A flatpage can be served by the fallback middlware and should add a slash'
def test_redirect_fallback_flatpage(self):
response = self.client.get('/flatpage') self.assertRedirects(response, '/flatpage/', status_code=301)
'A non-existent flatpage raises a 404 when served by the fallback middlware and should not add a slash'
def test_redirect_fallback_non_existent_flatpage(self):
response = self.client.get('/no_such_flatpage') self.assertEqual(response.status_code, 404)
'A flatpage with special chars in the URL can be served by the fallback middleware and should add a slash'
def test_redirect_fallback_flatpage_special_chars(self):
fp = FlatPage.objects.create(url='/some.very_special~chars-here/', title='A very special page', content="Isn't it special!", enable_comments=False, registration_required=False) fp.sites.add(1) response = self.client.get('/some.very_special~chars-here') self.assertRedirects(response, '/som...
'A flatpage at / should not cause a redirect loop when APPEND_SLASH is set'
def test_redirect_fallback_flatpage_root(self):
fp = FlatPage.objects.create(url='/', title='Root', content='Root', enable_comments=False, registration_required=False) fp.sites.add(1) response = self.client.get('/') self.assertEqual(response.status_code, 200) self.assertContains(response, '<p>Root</p>')
'Returns the static files serving handler wrapping the default handler, if static files should be served. Otherwise just returns the default handler.'
def get_handler(self, *args, **options):
handler = super(Command, self).get_handler(*args, **options) use_static_handler = options.get('use_static_handler', True) insecure_serving = options.get('insecure_serving', False) if (use_static_handler and (settings.DEBUG or insecure_serving)): return StaticFilesHandler(handler) return hand...
'Set instance variables based on an options dict'
def set_options(self, **options):
self.interactive = options['interactive'] self.verbosity = int(options.get('verbosity', 1)) self.symlink = options['link'] self.clear = options['clear'] self.dry_run = options['dry_run'] ignore_patterns = options['ignore_patterns'] if options['use_default_ignore_patterns']: ignore_pa...
'Perform the bulk of the work of collectstatic. Split off from handle_noargs() to facilitate testing.'
def collect(self):
if self.symlink: if (sys.platform == 'win32'): raise CommandError(('Symlinking is not supported by this platform (%s).' % sys.platform)) if (not self.local): raise CommandError("Can't symlink to a remote destination.") if self.clear: ...
'Small log helper'
def log(self, msg, level=2):
msg = smart_str(msg) if (not msg.endswith('\n')): msg += '\n' if (self.verbosity >= level): self.stdout.write(msg)
'Deletes the given relative path using the destinatin storage backend.'
def clear_dir(self, path):
(dirs, files) = self.storage.listdir(path) for f in files: fpath = os.path.join(path, f) if self.dry_run: self.log((u"Pretending to delete '%s'" % smart_unicode(fpath)), level=1) else: self.log((u"Deleting '%s'" % smart_unicode(fpath)), level=1) ...
'Checks if the target file should be deleted if it already exists'
def delete_file(self, path, prefixed_path, source_storage):
if self.storage.exists(prefixed_path): try: target_last_modified = self.storage.modified_time(prefixed_path) except (OSError, NotImplementedError, AttributeError): pass else: try: source_last_modified = source_storage.modified_time(path) ...
'Attempt to link ``path``'
def link_file(self, path, prefixed_path, source_storage):
if (prefixed_path in self.symlinked_files): return self.log((u"Skipping '%s' (already linked earlier)" % path)) if (not self.delete_file(path, prefixed_path, source_storage)): return source_path = source_storage.path(path) if self.dry_run: self.log((u"Pretending to...
'Attempt to copy ``path`` with storage'
def copy_file(self, path, prefixed_path, source_storage):
if (prefixed_path in self.copied_files): return self.log((u"Skipping '%s' (already copied earlier)" % path)) if (not self.delete_file(path, prefixed_path, source_storage)): return source_path = source_storage.path(path) if self.dry_run: self.log((u"Pretending to ...
'Checks if the path should be handled. Ignores the path if: * the host is provided as part of the base_url * the request\'s path isn\'t under the media path (or equal)'
def _should_handle(self, path):
return (path.startswith(self.base_url[2]) and (not self.base_url[1]))
'Returns the relative path to the media file on disk for the given URL.'
def file_path(self, url):
relative_url = url[len(self.base_url[2]):] return urllib.url2pathname(relative_url)
'Actually serves the request path.'
def serve(self, request):
return serve(request, self.file_path(request.path), insecure=True)
'Returns the real URL in DEBUG mode.'
def url(self, name, force=False):
if (settings.DEBUG and (not force)): (hashed_name, fragment) = (name, '') else: (clean_name, fragment) = urldefrag(name) if urlsplit(clean_name).path.endswith('/'): hashed_name = name else: cache_key = self.cache_key(name) hashed_name = self.ca...
'Returns the custom URL converter for the given file name.'
def url_converter(self, name):
def converter(matchobj): '\n Converts the matched URL depending on the parent level (`..`)\n and returns the normalized and hashed URL using the url method\n...
'Post process the given list of files (called from collectstatic). Processing is actually two separate operations: 1. renaming files to include a hash of their content for cache-busting, and copying those files to the target storage. 2. adjusting files which contain references to other files so they refer to the cache-...
def post_process(self, paths, dry_run=False, **options):
if dry_run: return hashed_paths = {} matches = (lambda path: matches_patterns(path, self._patterns.keys())) adjustable_paths = [path for path in paths if matches(path)] path_level = (lambda name: len(name.split(os.sep))) for name in sorted(paths.keys(), key=path_level, reverse=True): ...
'Returns a static file storage if available in the given app.'
def __init__(self, app, *args, **kwargs):
mod = import_module(app) mod_path = os.path.dirname(mod.__file__) location = os.path.join(mod_path, self.source_dir) super(AppStaticStorage, self).__init__(location, *args, **kwargs)
'Given a relative file path this ought to find an absolute file path. If the ``all`` parameter is ``False`` (default) only the first found file path will be returned; if set to ``True`` a list of all found files paths is returned.'
def find(self, path, all=False):
raise NotImplementedError()
'Given an optional list of paths to ignore, this should return a two item iterable consisting of the relative path and storage instance.'
def list(self, ignore_patterns):
raise NotImplementedError()
'Looks for files in the extra locations as defined in ``STATICFILES_DIRS``.'
def find(self, path, all=False):
matches = [] for (prefix, root) in self.locations: matched_path = self.find_location(root, path, prefix) if matched_path: if (not all): return matched_path matches.append(matched_path) return matches
'Finds a requested static file in a location, returning the found absolute path (or ``None`` if no match).'
def find_location(self, root, path, prefix=None):
if prefix: prefix = ('%s%s' % (prefix, os.sep)) if (not path.startswith(prefix)): return None path = path[len(prefix):] path = safe_join(root, path) if os.path.exists(path): return path
'List all files in all locations.'
def list(self, ignore_patterns):
for (prefix, root) in self.locations: storage = self.storages[root] for path in utils.get_files(storage, ignore_patterns): (yield (path, storage))
'List all files in all app storages.'
def list(self, ignore_patterns):
for storage in self.storages.itervalues(): if storage.exists(''): for path in utils.get_files(storage, ignore_patterns): (yield (path, storage))
'Looks for files in the app directories.'
def find(self, path, all=False):
matches = [] for app in self.apps: match = self.find_in_app(app, path) if match: if (not all): return match matches.append(match) return matches
'Find a requested static file in an app\'s static locations.'
def find_in_app(self, app, path):
storage = self.storages.get(app, None) if storage: if storage.prefix: prefix = ('%s%s' % (storage.prefix, os.sep)) if (not path.startswith(prefix)): return None path = path[len(prefix):] if storage.exists(path): matched_path = stora...
'Looks for files in the default file storage, if it\'s local.'
def find(self, path, all=False):
try: self.storage.path('') except NotImplementedError: pass else: if self.storage.exists(path): match = self.storage.path(path) if all: match = [match] return match return []
'List all files of the storage.'
def list(self, ignore_patterns):
for path in utils.get_files(self.storage, ignore_patterns): (yield (path, self.storage))
'Returns an extra keyword arguments dictionary that is used when initializing the feed generator.'
def feed_extra_kwargs(self, obj):
return {}
'Returns an extra keyword arguments dictionary that is used with the `add_item` call of the feed generator.'
def item_extra_kwargs(self, item):
return {}
'Returns a feedgenerator.DefaultFeed object, fully populated, for this feed. Raises FeedDoesNotExist for invalid parameters.'
def get_feed(self, obj, request):
current_site = get_current_site(request) link = self.__get_dynamic_attr('link', obj) link = add_domain(current_site.domain, link, request.is_secure()) feed = self.feed_type(title=self.__get_dynamic_attr('title', obj), subtitle=self.__get_dynamic_attr('subtitle', obj), link=link, description=self.__get_d...
'Class method to parse get_comment_list/count/form and return a Node.'
@classmethod def handle_token(cls, parser, token):
tokens = token.contents.split() if (tokens[1] != 'for'): raise template.TemplateSyntaxError(("Second argument in %r tag must be 'for'" % tokens[0])) if (len(tokens) == 5): if (tokens[3] != 'as'): raise template.TemplateSyntaxError(("Third argument in ...
'Subclasses should override this.'
def get_context_value_from_queryset(self, context, qs):
raise NotImplementedError
'Class method to parse render_comment_form and return a Node.'
@classmethod def handle_token(cls, parser, token):
tokens = token.contents.split() if (tokens[1] != 'for'): raise template.TemplateSyntaxError(("Second argument in %r tag must be 'for'" % tokens[0])) if (len(tokens) == 3): return cls(object_expr=parser.compile_filter(tokens[2])) elif (len(tokens) == 4): retur...
'Class method to parse render_comment_list and return a Node.'
@classmethod def handle_token(cls, parser, token):
tokens = token.contents.split() if (tokens[1] != 'for'): raise template.TemplateSyntaxError(("Second argument in %r tag must be 'for'" % tokens[0])) if (len(tokens) == 3): return cls(object_expr=parser.compile_filter(tokens[2])) elif (len(tokens) == 4): retur...
'Get a URL suitable for redirecting to the content object.'
def get_content_object_url(self):
return urlresolvers.reverse('comments-url-redirect', args=(self.content_type_id, self.object_pk))
'Get a dictionary that pulls together information about the poster safely for both authenticated and non-authenticated comments. This dict will have ``name``, ``email``, and ``url`` fields.'
def _get_userinfo(self):
if (not hasattr(self, '_userinfo')): self._userinfo = {'name': self.user_name, 'email': self.user_email, 'url': self.user_url} if self.user_id: u = self.user if u.email: self._userinfo['email'] = u.email if u.get_full_name(): self._...
'Return this comment as plain text. Useful for emails.'
def get_as_text(self):
d = {'user': (self.user or self.name), 'date': self.submit_date, 'comment': self.comment, 'domain': self.site.domain, 'url': self.get_absolute_url()} return (_('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d)
'QuerySet for all comments currently in the moderation queue.'
def in_moderation(self):
return self.get_query_set().filter(is_public=False, is_removed=False)
'QuerySet for all comments for a particular model (either an instance or a class).'
def for_model(self, model):
ct = ContentType.objects.get_for_model(model) qs = self.get_query_set().filter(content_type=ct) if isinstance(model, models.Model): qs = qs.filter(object_pk=force_unicode(model._get_pk_val())) return qs