Started attackign the next flake8 violation

This commit is contained in:
Alex Gaynor 2013-10-31 08:42:28 -07:00
parent a023a84c06
commit 726ded5708
38 changed files with 128 additions and 4 deletions

View File

@ -1,5 +1,6 @@
VERSION = (1, 7, 0, 'alpha', 0) VERSION = (1, 7, 0, 'alpha', 0)
def get_version(*args, **kwargs): def get_version(*args, **kwargs):
# Don't litter django/__init__.py with all the get_version stuff. # Don't litter django/__init__.py with all the get_version stuff.
# Only import if it's actually called. # Only import if it's actually called.

View File

@ -12,6 +12,7 @@ import os
import pstats import pstats
import sys import sys
def gather_stats(p): def gather_stats(p):
profiles = {} profiles = {}
for f in os.listdir(p): for f in os.listdir(p):

View File

@ -3,6 +3,7 @@
import os import os
import sys import sys
def unique_messages(): def unique_messages():
basedir = None basedir = None

View File

@ -13,6 +13,7 @@ handler403 = 'django.views.defaults.permission_denied'
handler404 = 'django.views.defaults.page_not_found' handler404 = 'django.views.defaults.page_not_found'
handler500 = 'django.views.defaults.server_error' handler500 = 'django.views.defaults.server_error'
def include(arg, namespace=None, app_name=None): def include(arg, namespace=None, app_name=None):
if isinstance(arg, tuple): if isinstance(arg, tuple):
# callable returning a namespace hint # callable returning a namespace hint
@ -39,6 +40,7 @@ def include(arg, namespace=None, app_name=None):
return (urlconf_module, app_name, namespace) return (urlconf_module, app_name, namespace)
def patterns(prefix, *args): def patterns(prefix, *args):
pattern_list = [] pattern_list = []
for t in args: for t in args:
@ -49,6 +51,7 @@ def patterns(prefix, *args):
pattern_list.append(t) pattern_list.append(t)
return pattern_list return pattern_list
def url(regex, view, kwargs=None, name=None, prefix=''): def url(regex, view, kwargs=None, name=None, prefix=''):
if isinstance(view, (list, tuple)): if isinstance(view, (list, tuple)):
# For include(...) processing. # For include(...) processing.

View File

@ -2,6 +2,7 @@ from django.conf import settings
from django.conf.urls import patterns, url from django.conf.urls import patterns, url
from django.core.urlresolvers import LocaleRegexURLResolver from django.core.urlresolvers import LocaleRegexURLResolver
def i18n_patterns(prefix, *args): def i18n_patterns(prefix, *args):
""" """
Adds the language code prefix to every URL pattern within this Adds the language code prefix to every URL pattern within this

View File

@ -1,8 +1,10 @@
import re import re
from django.conf import settings from django.conf import settings
from django.conf.urls import patterns, url from django.conf.urls import patterns, url
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
def static(prefix, view='django.views.static.serve', **kwargs): def static(prefix, view='django.views.static.serve', **kwargs):
""" """
Helper function to return a URL pattern for serving files in debug mode. Helper function to return a URL pattern for serving files in debug mode.

View File

@ -11,6 +11,7 @@ from django.template.response import TemplateResponse
from django.utils.encoding import force_text from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy, ugettext as _ from django.utils.translation import ugettext_lazy, ugettext as _
def delete_selected(modeladmin, request, queryset): def delete_selected(modeladmin, request, queryset):
""" """
Default action which deletes the selected objects. Default action which deletes the selected objects.

View File

@ -6,6 +6,7 @@ import sys
js_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'admin', 'js') js_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'admin', 'js')
def main(): def main():
usage = "usage: %prog [file1..fileN]" usage = "usage: %prog [file1..fileN]"
description = """With no file paths given this script will automatically description = """With no file paths given this script will automatically

View File

@ -16,6 +16,7 @@ from django.contrib.admin.utils import (get_model_from_relation,
reverse_field_path, get_limit_choices_to_from_path, prepare_lookup_value) reverse_field_path, get_limit_choices_to_from_path, prepare_lookup_value)
from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.options import IncorrectLookupParameters
class ListFilter(object): class ListFilter(object):
title = None # Human-readable title to appear in the right sidebar. title = None # Human-readable title to appear in the right sidebar.
template = 'admin/filter.html' template = 'admin/filter.html'

View File

@ -19,6 +19,7 @@ from django.conf import settings
ACTION_CHECKBOX_NAME = '_selected_action' ACTION_CHECKBOX_NAME = '_selected_action'
class ActionForm(forms.Form): class ActionForm(forms.Form):
action = forms.ChoiceField(label=_('Action:')) action = forms.ChoiceField(label=_('Action:'))
select_across = forms.BooleanField(label='', required=False, initial=0, select_across = forms.BooleanField(label='', required=False, initial=0,
@ -26,6 +27,7 @@ class ActionForm(forms.Form):
checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False) checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False)
class AdminForm(object): class AdminForm(object):
def __init__(self, form, fieldsets, prepopulated_fields, readonly_fields=None, model_admin=None): def __init__(self, form, fieldsets, prepopulated_fields, readonly_fields=None, model_admin=None):
self.form, self.fieldsets = form, normalize_fieldsets(fieldsets) self.form, self.fieldsets = form, normalize_fieldsets(fieldsets)
@ -53,6 +55,7 @@ class AdminForm(object):
return media return media
media = property(_media) media = property(_media)
class Fieldset(object): class Fieldset(object):
def __init__(self, form, name=None, readonly_fields=(), fields=(), classes=(), def __init__(self, form, name=None, readonly_fields=(), fields=(), classes=(),
description=None, model_admin=None): description=None, model_admin=None):
@ -77,6 +80,7 @@ class Fieldset(object):
for field in self.fields: for field in self.fields:
yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin) yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin)
class Fieldline(object): class Fieldline(object):
def __init__(self, form, field, readonly_fields=None, model_admin=None): def __init__(self, form, field, readonly_fields=None, model_admin=None):
self.form = form # A django.forms.Form instance self.form = form # A django.forms.Form instance
@ -103,6 +107,7 @@ class Fieldline(object):
def errors(self): def errors(self):
return mark_safe('\n'.join(self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields).strip('\n')) return mark_safe('\n'.join(self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields).strip('\n'))
class AdminField(object): class AdminField(object):
def __init__(self, form, field, is_first): def __init__(self, form, field, is_first):
self.field = form[field] # A django.forms.BoundField instance self.field = form[field] # A django.forms.BoundField instance
@ -128,6 +133,7 @@ class AdminField(object):
def errors(self): def errors(self):
return mark_safe(self.field.errors.as_ul()) return mark_safe(self.field.errors.as_ul())
class AdminReadonlyField(object): class AdminReadonlyField(object):
def __init__(self, form, field, is_first, model_admin=None): def __init__(self, form, field, is_first, model_admin=None):
label = label_for_field(field, form._meta.model, model_admin) label = label_for_field(field, form._meta.model, model_admin)
@ -183,6 +189,7 @@ class AdminReadonlyField(object):
result_repr = display_for_field(value, f) result_repr = display_for_field(value, f)
return conditional_escape(result_repr) return conditional_escape(result_repr)
class InlineAdminFormSet(object): class InlineAdminFormSet(object):
""" """
A wrapper around an inline formset for use in the admin system. A wrapper around an inline formset for use in the admin system.
@ -238,6 +245,7 @@ class InlineAdminFormSet(object):
return media return media
media = property(_media) media = property(_media)
class InlineAdminForm(AdminForm): class InlineAdminForm(AdminForm):
""" """
A wrapper around an inline form for use in the admin system. A wrapper around an inline form for use in the admin system.
@ -300,6 +308,7 @@ class InlineAdminForm(AdminForm):
from django.forms.formsets import ORDERING_FIELD_NAME from django.forms.formsets import ORDERING_FIELD_NAME
return AdminField(self.form, ORDERING_FIELD_NAME, False) return AdminField(self.form, ORDERING_FIELD_NAME, False)
class InlineFieldset(Fieldset): class InlineFieldset(Fieldset):
def __init__(self, formset, *args, **kwargs): def __init__(self, formset, *args, **kwargs):
self.formset = formset self.formset = formset
@ -313,6 +322,7 @@ class InlineFieldset(Fieldset):
yield Fieldline(self.form, field, self.readonly_fields, yield Fieldline(self.form, field, self.readonly_fields,
model_admin=self.model_admin) model_admin=self.model_admin)
class AdminErrorList(forms.utils.ErrorList): class AdminErrorList(forms.utils.ErrorList):
""" """
Stores all errors for the form/formsets in an add/change stage view. Stores all errors for the form/formsets in an add/change stage view.
@ -325,6 +335,7 @@ class AdminErrorList(forms.utils.ErrorList):
for errors_in_inline_form in inline_formset.errors: for errors_in_inline_form in inline_formset.errors:
self.extend(list(six.itervalues(errors_in_inline_form))) self.extend(list(six.itervalues(errors_in_inline_form)))
def normalize_fieldsets(fieldsets): def normalize_fieldsets(fieldsets):
""" """
Make sure the keys in fieldset dictionaries are strings. Returns the Make sure the keys in fieldset dictionaries are strings. Returns the
@ -335,6 +346,7 @@ def normalize_fieldsets(fieldsets):
result.append((name, normalize_dictionary(options))) result.append((name, normalize_dictionary(options)))
return result return result
def normalize_dictionary(data_dict): def normalize_dictionary(data_dict):
""" """
Converts all the keys in "data_dict" to strings. The keys must be Converts all the keys in "data_dict" to strings. The keys must be

View File

@ -25,6 +25,7 @@ register = Library()
DOT = '.' DOT = '.'
@register.simple_tag @register.simple_tag
def paginator_number(cl, i): def paginator_number(cl, i):
""" """
@ -40,6 +41,7 @@ def paginator_number(cl, i):
mark_safe(' class="end"' if i == cl.paginator.num_pages-1 else ''), mark_safe(' class="end"' if i == cl.paginator.num_pages-1 else ''),
i+1) i+1)
@register.inclusion_tag('admin/pagination.html') @register.inclusion_tag('admin/pagination.html')
def pagination(cl): def pagination(cl):
""" """
@ -86,6 +88,7 @@ def pagination(cl):
'1': 1, '1': 1,
} }
def result_headers(cl): def result_headers(cl):
""" """
Generates the list column headers. Generates the list column headers.
@ -167,11 +170,13 @@ def result_headers(cl):
"class_attrib": format_html(' class="{0}"', ' '.join(th_classes)) if th_classes else '', "class_attrib": format_html(' class="{0}"', ' '.join(th_classes)) if th_classes else '',
} }
def _boolean_icon(field_val): def _boolean_icon(field_val):
icon_url = static('admin/img/icon-%s.gif' % icon_url = static('admin/img/icon-%s.gif' %
{True: 'yes', False: 'no', None: 'unknown'}[field_val]) {True: 'yes', False: 'no', None: 'unknown'}[field_val])
return format_html('<img src="{0}" alt="{1}" />', icon_url, field_val) return format_html('<img src="{0}" alt="{1}" />', icon_url, field_val)
def items_for_result(cl, result, form): def items_for_result(cl, result, form):
""" """
Generates the actual list of data. Generates the actual list of data.
@ -266,6 +271,7 @@ def items_for_result(cl, result, form):
if form and not form[cl.model._meta.pk.name].is_hidden: if form and not form[cl.model._meta.pk.name].is_hidden:
yield format_html('<td>{0}</td>', force_text(form[cl.model._meta.pk.name])) yield format_html('<td>{0}</td>', force_text(form[cl.model._meta.pk.name]))
class ResultList(list): class ResultList(list):
# Wrapper class used to return items in a list_editable # Wrapper class used to return items in a list_editable
# changelist, annotated with the form object for error # changelist, annotated with the form object for error
@ -275,6 +281,7 @@ class ResultList(list):
self.form = form self.form = form
super(ResultList, self).__init__(*items) super(ResultList, self).__init__(*items)
def results(cl): def results(cl):
if cl.formset: if cl.formset:
for res, form in zip(cl.result_list, cl.formset.forms): for res, form in zip(cl.result_list, cl.formset.forms):
@ -283,12 +290,14 @@ def results(cl):
for res in cl.result_list: for res in cl.result_list:
yield ResultList(None, items_for_result(cl, res, None)) yield ResultList(None, items_for_result(cl, res, None))
def result_hidden_fields(cl): def result_hidden_fields(cl):
if cl.formset: if cl.formset:
for res, form in zip(cl.result_list, cl.formset.forms): for res, form in zip(cl.result_list, cl.formset.forms):
if form[cl.model._meta.pk.name].is_hidden: if form[cl.model._meta.pk.name].is_hidden:
yield mark_safe(force_text(form[cl.model._meta.pk.name])) yield mark_safe(force_text(form[cl.model._meta.pk.name]))
@register.inclusion_tag("admin/change_list_results.html") @register.inclusion_tag("admin/change_list_results.html")
def result_list(cl): def result_list(cl):
""" """
@ -305,6 +314,7 @@ def result_list(cl):
'num_sorted_fields': num_sorted_fields, 'num_sorted_fields': num_sorted_fields,
'results': list(results(cl))} 'results': list(results(cl))}
@register.inclusion_tag('admin/date_hierarchy.html') @register.inclusion_tag('admin/date_hierarchy.html')
def date_hierarchy(cl): def date_hierarchy(cl):
""" """
@ -382,6 +392,7 @@ def date_hierarchy(cl):
} for year in years] } for year in years]
} }
@register.inclusion_tag('admin/search_form.html') @register.inclusion_tag('admin/search_form.html')
def search_form(cl): def search_form(cl):
""" """
@ -393,6 +404,7 @@ def search_form(cl):
'search_var': SEARCH_VAR 'search_var': SEARCH_VAR
} }
@register.simple_tag @register.simple_tag
def admin_list_filter(cl, spec): def admin_list_filter(cl, spec):
tpl = get_template(spec.template) tpl = get_template(spec.template)
@ -402,6 +414,7 @@ def admin_list_filter(cl, spec):
'spec': spec, 'spec': spec,
})) }))
@register.inclusion_tag('admin/actions.html', takes_context=True) @register.inclusion_tag('admin/actions.html', takes_context=True)
def admin_actions(context): def admin_actions(context):
""" """

View File

@ -2,6 +2,7 @@ from django import template
register = template.Library() register = template.Library()
@register.inclusion_tag('admin/prepopulated_fields_js.html', takes_context=True) @register.inclusion_tag('admin/prepopulated_fields_js.html', takes_context=True)
def prepopulated_fields_js(context): def prepopulated_fields_js(context):
""" """
@ -19,6 +20,7 @@ def prepopulated_fields_js(context):
context.update({'prepopulated_fields': prepopulated_fields}) context.update({'prepopulated_fields': prepopulated_fields})
return context return context
@register.inclusion_tag('admin/submit_line.html', takes_context=True) @register.inclusion_tag('admin/submit_line.html', takes_context=True)
def submit_row(context): def submit_row(context):
""" """
@ -43,6 +45,7 @@ def submit_row(context):
ctx['original'] = context['original'] ctx['original'] = context['original']
return ctx return ctx
@register.filter @register.filter
def cell_count(inline_admin_form): def cell_count(inline_admin_form):
"""Returns the number of cells used in a tabular inline""" """Returns the number of cells used in a tabular inline"""

View File

@ -3,6 +3,7 @@ from django.contrib.admin.models import LogEntry
register = template.Library() register = template.Library()
class AdminLogNode(template.Node): class AdminLogNode(template.Node):
def __init__(self, limit, varname, user): def __init__(self, limit, varname, user):
self.limit, self.varname, self.user = limit, varname, user self.limit, self.varname, self.user = limit, varname, user
@ -20,6 +21,7 @@ class AdminLogNode(template.Node):
context[self.varname] = LogEntry.objects.filter(user__pk__exact=user_id).select_related('content_type', 'user')[:int(self.limit)] context[self.varname] = LogEntry.objects.filter(user__pk__exact=user_id).select_related('content_type', 'user')[:int(self.limit)]
return '' return ''
@register.tag @register.tag
def get_admin_log(parser, token): def get_admin_log(parser, token):
""" """

View File

@ -18,6 +18,7 @@ from django.utils import six
from django.utils.translation import ungettext from django.utils.translation import ungettext
from django.core.urlresolvers import reverse, NoReverseMatch from django.core.urlresolvers import reverse, NoReverseMatch
def lookup_needs_distinct(opts, lookup_path): def lookup_needs_distinct(opts, lookup_path):
""" """
Returns True if 'distinct()' should be used to query the given lookup path. Returns True if 'distinct()' should be used to query the given lookup path.
@ -31,6 +32,7 @@ def lookup_needs_distinct(opts, lookup_path):
return True return True
return False return False
def prepare_lookup_value(key, value): def prepare_lookup_value(key, value):
""" """
Returns a lookup value prepared to be used in queryset filtering. Returns a lookup value prepared to be used in queryset filtering.
@ -46,6 +48,7 @@ def prepare_lookup_value(key, value):
value = True value = True
return value return value
def quote(s): def quote(s):
""" """
Ensure that primary key values do not confuse the admin URLs by escaping Ensure that primary key values do not confuse the admin URLs by escaping

View File

@ -410,14 +410,17 @@ def check_type(cls, attr, type_):
raise ImproperlyConfigured("'%s.%s' should be a %s." raise ImproperlyConfigured("'%s.%s' should be a %s."
% (cls.__name__, attr, type_.__name__)) % (cls.__name__, attr, type_.__name__))
def check_isseq(cls, label, obj): def check_isseq(cls, label, obj):
if not isinstance(obj, (list, tuple)): if not isinstance(obj, (list, tuple)):
raise ImproperlyConfigured("'%s.%s' must be a list or tuple." % (cls.__name__, label)) raise ImproperlyConfigured("'%s.%s' must be a list or tuple." % (cls.__name__, label))
def check_isdict(cls, label, obj): def check_isdict(cls, label, obj):
if not isinstance(obj, dict): if not isinstance(obj, dict):
raise ImproperlyConfigured("'%s.%s' must be a dictionary." % (cls.__name__, label)) raise ImproperlyConfigured("'%s.%s' must be a dictionary." % (cls.__name__, label))
def get_field(cls, model, label, field): def get_field(cls, model, label, field):
try: try:
return model._meta.get_field(field) return model._meta.get_field(field)
@ -425,6 +428,7 @@ def get_field(cls, model, label, field):
raise ImproperlyConfigured("'%s.%s' refers to field '%s' that is missing from model '%s.%s'." raise ImproperlyConfigured("'%s.%s' refers to field '%s' that is missing from model '%s.%s'."
% (cls.__name__, label, field, model._meta.app_label, model.__name__)) % (cls.__name__, label, field, model._meta.app_label, model.__name__))
def fetch_attr(cls, model, label, field): def fetch_attr(cls, model, label, field):
try: try:
return model._meta.get_field(field) return model._meta.get_field(field)

View File

@ -49,8 +49,8 @@ class FilteredSelectMultiple(forms.SelectMultiple):
% (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), static('admin/'))) % (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), static('admin/')))
return mark_safe(''.join(output)) return mark_safe(''.join(output))
class AdminDateWidget(forms.DateInput):
class AdminDateWidget(forms.DateInput):
@property @property
def media(self): def media(self):
js = ["calendar.js", "admin/DateTimeShortcuts.js"] js = ["calendar.js", "admin/DateTimeShortcuts.js"]
@ -62,8 +62,8 @@ class AdminDateWidget(forms.DateInput):
final_attrs.update(attrs) final_attrs.update(attrs)
super(AdminDateWidget, self).__init__(attrs=final_attrs, format=format) super(AdminDateWidget, self).__init__(attrs=final_attrs, format=format)
class AdminTimeWidget(forms.TimeInput):
class AdminTimeWidget(forms.TimeInput):
@property @property
def media(self): def media(self):
js = ["calendar.js", "admin/DateTimeShortcuts.js"] js = ["calendar.js", "admin/DateTimeShortcuts.js"]
@ -75,6 +75,7 @@ class AdminTimeWidget(forms.TimeInput):
final_attrs.update(attrs) final_attrs.update(attrs)
super(AdminTimeWidget, self).__init__(attrs=final_attrs, format=format) super(AdminTimeWidget, self).__init__(attrs=final_attrs, format=format)
class AdminSplitDateTime(forms.SplitDateTimeWidget): class AdminSplitDateTime(forms.SplitDateTimeWidget):
""" """
A SplitDateTime Widget that has some admin-specific styling. A SplitDateTime Widget that has some admin-specific styling.
@ -90,6 +91,7 @@ class AdminSplitDateTime(forms.SplitDateTimeWidget):
_('Date:'), rendered_widgets[0], _('Date:'), rendered_widgets[0],
_('Time:'), rendered_widgets[1]) _('Time:'), rendered_widgets[1])
class AdminRadioFieldRenderer(RadioFieldRenderer): class AdminRadioFieldRenderer(RadioFieldRenderer):
def render(self): def render(self):
"""Outputs a <ul> for this set of radio fields.""" """Outputs a <ul> for this set of radio fields."""
@ -98,15 +100,18 @@ class AdminRadioFieldRenderer(RadioFieldRenderer):
format_html_join('\n', '<li>{0}</li>', format_html_join('\n', '<li>{0}</li>',
((force_text(w),) for w in self))) ((force_text(w),) for w in self)))
class AdminRadioSelect(forms.RadioSelect): class AdminRadioSelect(forms.RadioSelect):
renderer = AdminRadioFieldRenderer renderer = AdminRadioFieldRenderer
class AdminFileWidget(forms.ClearableFileInput): class AdminFileWidget(forms.ClearableFileInput):
template_with_initial = ('<p class="file-upload">%s</p>' template_with_initial = ('<p class="file-upload">%s</p>'
% forms.ClearableFileInput.template_with_initial) % forms.ClearableFileInput.template_with_initial)
template_with_clear = ('<span class="clearable-file-input">%s</span>' template_with_clear = ('<span class="clearable-file-input">%s</span>'
% forms.ClearableFileInput.template_with_clear) % forms.ClearableFileInput.template_with_clear)
def url_params_from_lookup_dict(lookups): def url_params_from_lookup_dict(lookups):
""" """
Converts the type of lookups specified in a ForeignKey limit_choices_to Converts the type of lookups specified in a ForeignKey limit_choices_to
@ -129,6 +134,7 @@ def url_params_from_lookup_dict(lookups):
params.update(dict(items)) params.update(dict(items))
return params return params
class ForeignKeyRawIdWidget(forms.TextInput): class ForeignKeyRawIdWidget(forms.TextInput):
""" """
A Widget for displaying ForeignKeys in the "raw_id" interface rather than A Widget for displaying ForeignKeys in the "raw_id" interface rather than
@ -187,6 +193,7 @@ class ForeignKeyRawIdWidget(forms.TextInput):
except (ValueError, self.rel.to.DoesNotExist): except (ValueError, self.rel.to.DoesNotExist):
return '' return ''
class ManyToManyRawIdWidget(ForeignKeyRawIdWidget): class ManyToManyRawIdWidget(ForeignKeyRawIdWidget):
""" """
A Widget for displaying ManyToMany ids in the "raw_id" interface rather than A Widget for displaying ManyToMany ids in the "raw_id" interface rather than
@ -275,6 +282,7 @@ class RelatedFieldWidgetWrapper(forms.Widget):
def id_for_label(self, id_): def id_for_label(self, id_):
return self.widget.id_for_label(id_) return self.widget.id_for_label(id_)
class AdminTextareaWidget(forms.Textarea): class AdminTextareaWidget(forms.Textarea):
def __init__(self, attrs=None): def __init__(self, attrs=None):
final_attrs = {'class': 'vLargeTextField'} final_attrs = {'class': 'vLargeTextField'}
@ -282,6 +290,7 @@ class AdminTextareaWidget(forms.Textarea):
final_attrs.update(attrs) final_attrs.update(attrs)
super(AdminTextareaWidget, self).__init__(attrs=final_attrs) super(AdminTextareaWidget, self).__init__(attrs=final_attrs)
class AdminTextInputWidget(forms.TextInput): class AdminTextInputWidget(forms.TextInput):
def __init__(self, attrs=None): def __init__(self, attrs=None):
final_attrs = {'class': 'vTextField'} final_attrs = {'class': 'vTextField'}
@ -289,6 +298,7 @@ class AdminTextInputWidget(forms.TextInput):
final_attrs.update(attrs) final_attrs.update(attrs)
super(AdminTextInputWidget, self).__init__(attrs=final_attrs) super(AdminTextInputWidget, self).__init__(attrs=final_attrs)
class AdminEmailInputWidget(forms.EmailInput): class AdminEmailInputWidget(forms.EmailInput):
def __init__(self, attrs=None): def __init__(self, attrs=None):
final_attrs = {'class': 'vTextField'} final_attrs = {'class': 'vTextField'}
@ -296,6 +306,7 @@ class AdminEmailInputWidget(forms.EmailInput):
final_attrs.update(attrs) final_attrs.update(attrs)
super(AdminEmailInputWidget, self).__init__(attrs=final_attrs) super(AdminEmailInputWidget, self).__init__(attrs=final_attrs)
class AdminURLFieldWidget(forms.URLInput): class AdminURLFieldWidget(forms.URLInput):
def __init__(self, attrs=None): def __init__(self, attrs=None):
final_attrs = {'class': 'vURLField'} final_attrs = {'class': 'vURLField'}
@ -325,9 +336,11 @@ class AdminIntegerFieldWidget(forms.TextInput):
final_attrs.update(attrs) final_attrs.update(attrs)
super(AdminIntegerFieldWidget, self).__init__(attrs=final_attrs) super(AdminIntegerFieldWidget, self).__init__(attrs=final_attrs)
class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget): class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget):
class_name = 'vBigIntegerField' class_name = 'vBigIntegerField'
class AdminCommaSeparatedIntegerFieldWidget(forms.TextInput): class AdminCommaSeparatedIntegerFieldWidget(forms.TextInput):
def __init__(self, attrs=None): def __init__(self, attrs=None):
final_attrs = {'class': 'vCommaSeparatedIntegerField'} final_attrs = {'class': 'vCommaSeparatedIntegerField'}

View File

@ -1,6 +1,7 @@
from django.conf import settings from django.conf import settings
from django import http from django import http
class XViewMiddleware(object): class XViewMiddleware(object):
""" """
Adds an X-View header to internal HEAD requests -- used by the documentation system. Adds an X-View header to internal HEAD requests -- used by the documentation system.

View File

@ -11,6 +11,7 @@ from django.utils.translation import ugettext as _
class CustomField(models.Field): class CustomField(models.Field):
description = "A custom field type" description = "A custom field type"
class DescriptionLackingField(models.Field): class DescriptionLackingField(models.Field):
pass pass

View File

@ -16,6 +16,7 @@ except ImportError:
else: else:
docutils_is_available = True docutils_is_available = True
def trim_docstring(docstring): def trim_docstring(docstring):
""" """
Uniformly trims leading/trailing whitespace from docstrings. Uniformly trims leading/trailing whitespace from docstrings.
@ -30,6 +31,7 @@ def trim_docstring(docstring):
trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]] trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]]
return "\n".join(trimmed).strip() return "\n".join(trimmed).strip()
def parse_docstring(docstring): def parse_docstring(docstring):
""" """
Parse out the parts of a docstring. Returns (title, body, metadata). Parse out the parts of a docstring. Returns (title, body, metadata).
@ -55,6 +57,7 @@ def parse_docstring(docstring):
body = "\n\n".join(parts[1:]) body = "\n\n".join(parts[1:])
return title, body, metadata return title, body, metadata
def parse_rst(text, default_reference_context, thing_being_parsed=None): def parse_rst(text, default_reference_context, thing_being_parsed=None):
""" """
Convert the string from reST to an XHTML fragment. Convert the string from reST to an XHTML fragment.
@ -92,6 +95,7 @@ ROLES = {
'tag': '%s/tags/#%s', 'tag': '%s/tags/#%s',
} }
def create_reference_role(rolename, urlbase): def create_reference_role(rolename, urlbase):
def _role(name, rawtext, text, lineno, inliner, options=None, content=None): def _role(name, rawtext, text, lineno, inliner, options=None, content=None):
if options is None: if options is None:
@ -102,6 +106,7 @@ def create_reference_role(rolename, urlbase):
return [node], [] return [node], []
docutils.parsers.rst.roles.register_canonical_role(rolename, _role) docutils.parsers.rst.roles.register_canonical_role(rolename, _role)
def default_reference_role(name, rawtext, text, lineno, inliner, options=None, content=None): def default_reference_role(name, rawtext, text, lineno, inliner, options=None, content=None):
if options is None: if options is None:
options = {} options = {}

View File

@ -21,10 +21,12 @@ from django.utils.translation import ugettext as _
# Exclude methods starting with these strings from documentation # Exclude methods starting with these strings from documentation
MODEL_METHODS_EXCLUDE = ('_', 'add_', 'delete', 'save', 'set_') MODEL_METHODS_EXCLUDE = ('_', 'add_', 'delete', 'save', 'set_')
class GenericSite(object): class GenericSite(object):
domain = 'example.com' domain = 'example.com'
name = 'my site' name = 'my site'
@staff_member_required @staff_member_required
def doc_index(request): def doc_index(request):
if not utils.docutils_is_available: if not utils.docutils_is_available:
@ -33,6 +35,7 @@ def doc_index(request):
'root_path': urlresolvers.reverse('admin:index'), 'root_path': urlresolvers.reverse('admin:index'),
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
@staff_member_required @staff_member_required
def bookmarklets(request): def bookmarklets(request):
admin_root = urlresolvers.reverse('admin:index') admin_root = urlresolvers.reverse('admin:index')
@ -41,6 +44,7 @@ def bookmarklets(request):
'admin_url': "%s://%s%s" % (request.scheme, request.get_host(), admin_root), 'admin_url': "%s://%s%s" % (request.scheme, request.get_host(), admin_root),
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
@staff_member_required @staff_member_required
def template_tag_index(request): def template_tag_index(request):
if not utils.docutils_is_available: if not utils.docutils_is_available:
@ -76,6 +80,7 @@ def template_tag_index(request):
'tags': tags 'tags': tags
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
@staff_member_required @staff_member_required
def template_filter_index(request): def template_filter_index(request):
if not utils.docutils_is_available: if not utils.docutils_is_available:
@ -111,6 +116,7 @@ def template_filter_index(request):
'filters': filters 'filters': filters
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
@staff_member_required @staff_member_required
def view_index(request): def view_index(request):
if not utils.docutils_is_available: if not utils.docutils_is_available:
@ -141,6 +147,7 @@ def view_index(request):
'views': views 'views': views
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
@staff_member_required @staff_member_required
def view_detail(request, view): def view_detail(request, view):
if not utils.docutils_is_available: if not utils.docutils_is_available:
@ -166,6 +173,7 @@ def view_detail(request, view):
'meta': metadata, 'meta': metadata,
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
@staff_member_required @staff_member_required
def model_index(request): def model_index(request):
if not utils.docutils_is_available: if not utils.docutils_is_available:
@ -176,6 +184,7 @@ def model_index(request):
'models': m_list 'models': m_list
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
@staff_member_required @staff_member_required
def model_detail(request, app_label, model_name): def model_detail(request, app_label, model_name):
if not utils.docutils_is_available: if not utils.docutils_is_available:
@ -278,6 +287,7 @@ def model_detail(request, app_label, model_name):
'fields': fields, 'fields': fields,
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
@staff_member_required @staff_member_required
def template_detail(request, template): def template_detail(request, template):
templates = [] templates = []
@ -307,10 +317,12 @@ def template_detail(request, template):
# Helper functions # # Helper functions #
#################### ####################
def missing_docutils_page(request): def missing_docutils_page(request):
"""Display an error message for people without docutils""" """Display an error message for people without docutils"""
return render_to_response('admin_doc/missing_docutils.html') return render_to_response('admin_doc/missing_docutils.html')
def load_all_installed_template_libraries(): def load_all_installed_template_libraries():
# Load/register all template tag libraries from installed apps. # Load/register all template tag libraries from installed apps.
for module_name in template.get_templatetags_modules(): for module_name in template.get_templatetags_modules():
@ -329,6 +341,7 @@ def load_all_installed_template_libraries():
except template.InvalidTemplateLibrary: except template.InvalidTemplateLibrary:
pass pass
def get_return_data_type(func_name): def get_return_data_type(func_name):
"""Return a somewhat-helpful data type given a function name""" """Return a somewhat-helpful data type given a function name"""
if func_name.startswith('get_'): if func_name.startswith('get_'):
@ -338,6 +351,7 @@ def get_return_data_type(func_name):
return 'Integer' return 'Integer'
return '' return ''
def get_readable_field_data_type(field): def get_readable_field_data_type(field):
"""Returns the description for a given field type, if it exists, """Returns the description for a given field type, if it exists,
Fields' descriptions can contain format strings, which will be interpolated Fields' descriptions can contain format strings, which will be interpolated
@ -345,6 +359,7 @@ def get_readable_field_data_type(field):
return field.description % field.__dict__ return field.description % field.__dict__
def extract_views_from_urlpatterns(urlpatterns, base=''): def extract_views_from_urlpatterns(urlpatterns, base=''):
""" """
Return a list of views from a list of urlpatterns. Return a list of views from a list of urlpatterns.
@ -371,6 +386,7 @@ def extract_views_from_urlpatterns(urlpatterns, base=''):
named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)') named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)')
non_named_group_matcher = re.compile(r'\(.*?\)') non_named_group_matcher = re.compile(r'\(.*?\)')
def simplify_regex(pattern): def simplify_regex(pattern):
""" """
Clean up urlpattern regexes into something somewhat readable by Mere Humans: Clean up urlpattern regexes into something somewhat readable by Mere Humans:

View File

@ -1,6 +1,7 @@
# PermWrapper and PermLookupDict proxy the permissions system into objects that # PermWrapper and PermLookupDict proxy the permissions system into objects that
# the template system can understand. # the template system can understand.
class PermLookupDict(object): class PermLookupDict(object):
def __init__(self, user, app_label): def __init__(self, user, app_label):
self.user, self.app_label = user, app_label self.user, self.app_label = user, app_label

View File

@ -27,6 +27,7 @@ def check_password(environ, username, password):
finally: finally:
db.close_old_connections() db.close_old_connections()
def groups_for_user(environ, username): def groups_for_user(environ, username):
""" """
Authorizes a user based on groups Authorizes a user based on groups

View File

@ -711,6 +711,7 @@ class LogoutTest(AuthViewsTestCase):
"%s should be allowed" % good_url) "%s should be allowed" % good_url)
self.confirm_logged_out() self.confirm_logged_out()
@skipIfCustomUser @skipIfCustomUser
@override_settings( @override_settings(
PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),

View File

@ -10,11 +10,13 @@ from django.shortcuts import render_to_response
from django.template import Template, RequestContext from django.template import Template, RequestContext
from django.views.decorators.cache import never_cache from django.views.decorators.cache import never_cache
class CustomRequestAuthenticationForm(AuthenticationForm): class CustomRequestAuthenticationForm(AuthenticationForm):
def __init__(self, request, *args, **kwargs): def __init__(self, request, *args, **kwargs):
assert isinstance(request, HttpRequest) assert isinstance(request, HttpRequest)
super(CustomRequestAuthenticationForm, self).__init__(request, *args, **kwargs) super(CustomRequestAuthenticationForm, self).__init__(request, *args, **kwargs)
@never_cache @never_cache
def remote_user_auth_view(request): def remote_user_auth_view(request):
"Dummy view for remote user tests" "Dummy view for remote user tests"
@ -22,6 +24,7 @@ def remote_user_auth_view(request):
c = RequestContext(request, {}) c = RequestContext(request, {})
return HttpResponse(t.render(c)) return HttpResponse(t.render(c))
def auth_processor_no_attr_access(request): def auth_processor_no_attr_access(request):
render_to_response('context_processors/auth_attrs_no_access.html', render_to_response('context_processors/auth_attrs_no_access.html',
RequestContext(request, {}, processors=[context_processors.auth])) RequestContext(request, {}, processors=[context_processors.auth]))
@ -29,32 +32,39 @@ def auth_processor_no_attr_access(request):
return render_to_response('context_processors/auth_attrs_test_access.html', return render_to_response('context_processors/auth_attrs_test_access.html',
{'session_accessed': request.session.accessed}) {'session_accessed': request.session.accessed})
def auth_processor_attr_access(request): def auth_processor_attr_access(request):
render_to_response('context_processors/auth_attrs_access.html', render_to_response('context_processors/auth_attrs_access.html',
RequestContext(request, {}, processors=[context_processors.auth])) RequestContext(request, {}, processors=[context_processors.auth]))
return render_to_response('context_processors/auth_attrs_test_access.html', return render_to_response('context_processors/auth_attrs_test_access.html',
{'session_accessed': request.session.accessed}) {'session_accessed': request.session.accessed})
def auth_processor_user(request): def auth_processor_user(request):
return render_to_response('context_processors/auth_attrs_user.html', return render_to_response('context_processors/auth_attrs_user.html',
RequestContext(request, {}, processors=[context_processors.auth])) RequestContext(request, {}, processors=[context_processors.auth]))
def auth_processor_perms(request): def auth_processor_perms(request):
return render_to_response('context_processors/auth_attrs_perms.html', return render_to_response('context_processors/auth_attrs_perms.html',
RequestContext(request, {}, processors=[context_processors.auth])) RequestContext(request, {}, processors=[context_processors.auth]))
def auth_processor_perm_in_perms(request): def auth_processor_perm_in_perms(request):
return render_to_response('context_processors/auth_attrs_perm_in_perms.html', return render_to_response('context_processors/auth_attrs_perm_in_perms.html',
RequestContext(request, {}, processors=[context_processors.auth])) RequestContext(request, {}, processors=[context_processors.auth]))
def auth_processor_messages(request): def auth_processor_messages(request):
info(request, "Message 1") info(request, "Message 1")
return render_to_response('context_processors/auth_attrs_messages.html', return render_to_response('context_processors/auth_attrs_messages.html',
RequestContext(request, {}, processors=[context_processors.auth])) RequestContext(request, {}, processors=[context_processors.auth]))
def userpage(request): def userpage(request):
pass pass
def custom_request_auth_login(request): def custom_request_auth_login(request):
return login(request, authentication_form=CustomRequestAuthenticationForm) return login(request, authentication_form=CustomRequestAuthenticationForm)

View File

@ -234,6 +234,7 @@ def password_reset_confirm(request, uidb64=None, token=None,
return TemplateResponse(request, template_name, context, return TemplateResponse(request, template_name, context,
current_app=current_app) current_app=current_app)
def password_reset_complete(request, def password_reset_complete(request,
template_name='registration/password_reset_complete.html', template_name='registration/password_reset_complete.html',
current_app=None, extra_context=None): current_app=None, extra_context=None):

View File

@ -154,6 +154,7 @@ class GenericForeignKey(six.with_metaclass(RenameGenericForeignKeyMethods)):
setattr(instance, self.fk_field, fk) setattr(instance, self.fk_field, fk)
setattr(instance, self.cache_attr, value) setattr(instance, self.cache_attr, value)
class GenericRelation(ForeignObject): class GenericRelation(ForeignObject):
"""Provides an accessor to generic related objects (e.g. comments)""" """Provides an accessor to generic related objects (e.g. comments)"""
@ -293,6 +294,7 @@ class ReverseGenericRelatedObjectsDescriptor(object):
for obj in value: for obj in value:
manager.add(obj) manager.add(obj)
def create_generic_related_manager(superclass): def create_generic_related_manager(superclass):
""" """
Factory function for a manager that subclasses 'superclass' (which is a Factory function for a manager that subclasses 'superclass' (which is a
@ -390,11 +392,12 @@ def create_generic_related_manager(superclass):
return GenericRelatedObjectManager return GenericRelatedObjectManager
class GenericRel(ForeignObjectRel):
class GenericRel(ForeignObjectRel):
def __init__(self, field, to, related_name=None, limit_choices_to=None): def __init__(self, field, to, related_name=None, limit_choices_to=None):
super(GenericRel, self).__init__(field, to, related_name, limit_choices_to) super(GenericRel, self).__init__(field, to, related_name, limit_choices_to)
class BaseGenericInlineFormSet(BaseModelFormSet): class BaseGenericInlineFormSet(BaseModelFormSet):
""" """
A formset for generic inline objects to a parent. A formset for generic inline objects to a parent.
@ -475,6 +478,7 @@ def generic_inlineformset_factory(model, form=ModelForm,
FormSet.for_concrete_model = for_concrete_model FormSet.for_concrete_model = for_concrete_model
return FormSet return FormSet
class GenericInlineModelAdmin(InlineModelAdmin): class GenericInlineModelAdmin(InlineModelAdmin):
ct_field = "content_type" ct_field = "content_type"
ct_fk_field = "object_id" ct_fk_field = "object_id"
@ -516,8 +520,10 @@ class GenericInlineModelAdmin(InlineModelAdmin):
return generic_inlineformset_factory(self.model, **defaults) return generic_inlineformset_factory(self.model, **defaults)
class GenericStackedInline(GenericInlineModelAdmin): class GenericStackedInline(GenericInlineModelAdmin):
template = 'admin/edit_inline/stacked.html' template = 'admin/edit_inline/stacked.html'
class GenericTabularInline(GenericInlineModelAdmin): class GenericTabularInline(GenericInlineModelAdmin):
template = 'admin/edit_inline/tabular.html' template = 'admin/edit_inline/tabular.html'

View File

@ -3,6 +3,7 @@ from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_text, force_text from django.utils.encoding import smart_text, force_text
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
class ContentTypeManager(models.Manager): class ContentTypeManager(models.Manager):
# Cache to avoid re-looking up ContentType objects all over the place. # Cache to avoid re-looking up ContentType objects all over the place.

View File

@ -15,10 +15,12 @@ from django.utils.encoding import python_2_unicode_compatible
class ConcreteModel(models.Model): class ConcreteModel(models.Model):
name = models.CharField(max_length=10) name = models.CharField(max_length=10)
class ProxyModel(ConcreteModel): class ProxyModel(ConcreteModel):
class Meta: class Meta:
proxy = True proxy = True
@python_2_unicode_compatible @python_2_unicode_compatible
class FooWithoutUrl(models.Model): class FooWithoutUrl(models.Model):
""" """
@ -39,6 +41,7 @@ class FooWithUrl(FooWithoutUrl):
def get_absolute_url(self): def get_absolute_url(self):
return "/users/%s/" % urlquote(self.name) return "/users/%s/" % urlquote(self.name)
class FooWithBrokenAbsoluteUrl(FooWithoutUrl): class FooWithBrokenAbsoluteUrl(FooWithoutUrl):
""" """
Fake model defining a ``get_absolute_url`` method containing an error Fake model defining a ``get_absolute_url`` method containing an error
@ -47,8 +50,8 @@ class FooWithBrokenAbsoluteUrl(FooWithoutUrl):
def get_absolute_url(self): def get_absolute_url(self):
return "/users/%s/" % self.unknown_field return "/users/%s/" % self.unknown_field
class ContentTypesTests(TestCase):
class ContentTypesTests(TestCase):
def setUp(self): def setUp(self):
self.old_Site_meta_installed = Site._meta.installed self.old_Site_meta_installed = Site._meta.installed
ContentType.objects.clear_cache() ContentType.objects.clear_cache()

View File

@ -6,6 +6,7 @@ from django.contrib.sites.models import Site, get_current_site
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
def shortcut(request, content_type_id, object_id): def shortcut(request, content_type_id, object_id):
""" """
Redirect to an object's page based on a content-type ID and an object ID. Redirect to an object's page based on a content-type ID and an object ID.

View File

@ -3,6 +3,7 @@ from django.contrib.flatpages.models import FlatPage
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.contrib.flatpages.forms import FlatpageForm from django.contrib.flatpages.forms import FlatpageForm
class FlatPageAdmin(admin.ModelAdmin): class FlatPageAdmin(admin.ModelAdmin):
form = FlatpageForm form = FlatpageForm
fieldsets = ( fieldsets = (

View File

@ -3,6 +3,7 @@ from django.conf import settings
from django.contrib.flatpages.models import FlatPage from django.contrib.flatpages.models import FlatPage
from django.utils.translation import ugettext, ugettext_lazy as _ from django.utils.translation import ugettext, ugettext_lazy as _
class FlatpageForm(forms.ModelForm): class FlatpageForm(forms.ModelForm):
url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/\.~]+$', url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/\.~]+$',
help_text = _("Example: '/about/contact/'. Make sure to have leading" help_text = _("Example: '/about/contact/'. Make sure to have leading"

View File

@ -2,6 +2,7 @@ from django.contrib.flatpages.views import flatpage
from django.http import Http404 from django.http import Http404
from django.conf import settings from django.conf import settings
class FlatpageFallbackMiddleware(object): class FlatpageFallbackMiddleware(object):
def process_response(self, request, response): def process_response(self, request, response):
if response.status_code != 404: if response.status_code != 404:

View File

@ -6,6 +6,7 @@ from django.core.urlresolvers import get_script_prefix
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import iri_to_uri, python_2_unicode_compatible from django.utils.encoding import iri_to_uri, python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class FlatPage(models.Model): class FlatPage(models.Model):
url = models.CharField(_('URL'), max_length=100, db_index=True) url = models.CharField(_('URL'), max_length=100, db_index=True)

View File

@ -7,6 +7,7 @@ from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import translation from django.utils import translation
@override_settings(SITE_ID=1) @override_settings(SITE_ID=1)
class FlatpageAdminFormTests(TestCase): class FlatpageAdminFormTests(TestCase):
fixtures = ['example_site'] fixtures = ['example_site']

View File

@ -17,6 +17,8 @@ DEFAULT_TEMPLATE = 'flatpages/default.html'
# or a redirect is required for authentication, the 404 needs to be returned # or a redirect is required for authentication, the 404 needs to be returned
# without any CSRF checks. Therefore, we only # without any CSRF checks. Therefore, we only
# CSRF protect the internal implementation. # CSRF protect the internal implementation.
def flatpage(request, url): def flatpage(request, url):
""" """
Public interface to the flat page view. Public interface to the flat page view.
@ -44,6 +46,7 @@ def flatpage(request, url):
raise raise
return render_flatpage(request, f) return render_flatpage(request, f)
@csrf_protect @csrf_protect
def render_flatpage(request, f): def render_flatpage(request, f):
""" """

View File

@ -10,6 +10,7 @@ from django.contrib.formtools.utils import form_hmac
AUTO_ID = 'formtools_%s' # Each form here uses this as its auto_id parameter. AUTO_ID = 'formtools_%s' # Each form here uses this as its auto_id parameter.
class FormPreview(object): class FormPreview(object):
preview_template = 'formtools/preview.html' preview_template = 'formtools/preview.html'
form_template = 'formtools/form.html' form_template = 'formtools/form.html'

View File

@ -1,15 +1,18 @@
from django import forms from django import forms
class TestForm(forms.Form): class TestForm(forms.Form):
field1 = forms.CharField() field1 = forms.CharField()
field1_ = forms.CharField() field1_ = forms.CharField()
bool1 = forms.BooleanField(required=False) bool1 = forms.BooleanField(required=False)
date1 = forms.DateField(required=False) date1 = forms.DateField(required=False)
class HashTestForm(forms.Form): class HashTestForm(forms.Form):
name = forms.CharField() name = forms.CharField()
bio = forms.CharField() bio = forms.CharField()
class HashTestBlankForm(forms.Form): class HashTestBlankForm(forms.Form):
name = forms.CharField(required=False) name = forms.CharField(required=False)
bio = forms.CharField(required=False) bio = forms.CharField(required=False)

View File

@ -19,6 +19,7 @@ from django.contrib.formtools.tests.forms import (
success_string = "Done was called!" success_string = "Done was called!"
success_string_encoded = success_string.encode() success_string_encoded = success_string.encode()
class TestFormPreview(preview.FormPreview): class TestFormPreview(preview.FormPreview):
def get_context(self, request, form): def get_context(self, request, form):
context = super(TestFormPreview, self).get_context(request, form) context = super(TestFormPreview, self).get_context(request, form)
@ -31,6 +32,7 @@ class TestFormPreview(preview.FormPreview):
def done(self, request, cleaned_data): def done(self, request, cleaned_data):
return http.HttpResponse(success_string) return http.HttpResponse(success_string)
@override_settings( @override_settings(
TEMPLATE_DIRS=( TEMPLATE_DIRS=(
os.path.join(os.path.dirname(upath(__file__)), 'templates'), os.path.join(os.path.dirname(upath(__file__)), 'templates'),