desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Check that a password reset token is correct for a given user.'
def check_token(self, user, token):
try: (ts_b36, hash) = token.split('-') except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False if (not constant_time_compare(self._make_token_with_timestamp(user, ts), token)): return False if ((self._num_days(self._...
'Allows the backend to clean the username, if the backend defines a clean_username method.'
def clean_username(self, username, request):
backend_str = request.session[auth.BACKEND_SESSION_KEY] backend = auth.load_backend(backend_str) try: username = backend.clean_username(username) except AttributeError: pass return username
'Start a new wizard with a list of forms. form_list should be a list of Form classes (not instances).'
def __init__(self, form_list, initial=None):
self.form_list = form_list[:] self.initial = (initial or {}) self.extra_context = {} self.step = 0 import warnings warnings.warn('Old-style form wizards have been deprecated; use the class-based views in django.contrib.formtools.wizard.views instead.', Pending...
'Helper method that returns the Form instance for the given step.'
def get_form(self, step, data=None):
if (step >= self.num_steps()): raise Http404(('Step %s does not exist' % step)) return self.form_list[step](data, prefix=self.prefix_for_step(step), initial=self.initial.get(step, None))
'Helper method that returns the number of steps.'
def num_steps(self):
return len(self.form_list)
'Main method that does all the hard work, conforming to the Django view interface.'
@method_decorator(csrf_protect) def __call__(self, request, *args, **kwargs):
if ('extra_context' in kwargs): self.extra_context.update(kwargs['extra_context']) current_step = self.get_current_or_first_step(request, *args, **kwargs) self.parse_params(request, *args, **kwargs) previous_form_list = [] for i in range(current_step): f = self.get_form(i, request.PO...
'Renders the given Form object, returning an HttpResponse.'
def render(self, form, request, step, context=None):
old_data = request.POST prev_fields = [] if old_data: hidden = HiddenInput() for i in range(step): old_form = self.get_form(i, old_data) hash_name = ('hash_%s' % i) prev_fields.extend([bf.as_hidden() for bf in old_form]) prev_fields.append(hidd...
'Given the step, returns a Form prefix to use.'
def prefix_for_step(self, step):
return str(step)
'Hook for rendering a template if a hash check failed. step is the step that failed. Any previous step is guaranteed to be valid. This default implementation simply renders the form for the given step, but subclasses may want to display an error message, etc.'
def render_hash_failure(self, request, step):
return self.render(self.get_form(step), request, step, context={'wizard_error': _('We apologize, but your form has expired. Please continue filling out the form from this page.')})
'Hook for rendering a template if final revalidation failed. It is highly unlikely that this point would ever be reached, but See the comment in __call__() for an explanation.'
def render_revalidation_failure(self, request, step, form):
return self.render(form, request, step)
'Calculates the security hash for the given HttpRequest and Form instances. Subclasses may want to take into account request-specific information, such as the IP address.'
def security_hash(self, request, form):
return form_hmac(form)
'Given the request object and whatever *args and **kwargs were passed to __call__(), returns the current step (which is zero-based). Note that the result should not be trusted. It may even be a completely invalid number. It\'s not the job of this method to validate it.'
def get_current_or_first_step(self, request, *args, **kwargs):
if (not request.POST): return 0 try: step = int(request.POST.get(self.step_field_name, 0)) except ValueError: return 0 return step
'Hook for setting some state, given the request object and whatever *args and **kwargs were passed to __call__(), sets some state. This is called at the beginning of __call__().'
def parse_params(self, request, *args, **kwargs):
pass
'Hook for specifying the name of the template to use for a given step. Note that this can return a tuple of template names if you\'d like to use the template system\'s select_template() hook.'
def get_template(self, step):
return 'forms/wizard.html'
'Renders the template for the given step, returning an HttpResponse object. Override this method if you want to add a custom context, return a different MIME type, etc. If you only need to override the template name, use get_template() instead. The template will be rendered with the following context: step_field -- The...
def render_template(self, request, form, previous_fields, step, context=None):
context = (context or {}) context.update(self.extra_context) return render_to_response(self.get_template(step), dict(context, step_field=self.step_field_name, step0=step, step=(step + 1), step_count=self.num_steps(), form=form, previous_fields=previous_fields), context_instance=RequestContext(request))
'Hook for modifying the FormWizard\'s internal state, given a fully validated Form object. The Form is guaranteed to have clean, valid data. This method should *not* modify any of that data. Rather, it might want to set self.extra_context or dynamically alter self.form_list, based on previously submitted forms. Note th...
def process_step(self, request, form, step):
pass
'Hook for doing something with the validated data. This is responsible for the final processing. form_list is a list of Form instances, each containing clean, valid data.'
def done(self, request, form_list):
raise NotImplementedError(('Your %s class has not defined a done() method, which is required.' % self.__class__.__name__))
'Returns the names of all steps/forms.'
@property def all(self):
return self._wizard.get_form_list().keys()
'Returns the total number of steps/forms in this the wizard.'
@property def count(self):
return len(self.all)
'Returns the current step. If no current step is stored in the storage backend, the first step will be returned.'
@property def current(self):
return (self._wizard.storage.current_step or self.first)
'Returns the name of the first step.'
@property def first(self):
return self.all[0]
'Returns the name of the last step.'
@property def last(self):
return self.all[(-1)]
'Returns the next step.'
@property def next(self):
return self._wizard.get_next_step()
'Returns the previous step.'
@property def prev(self):
return self._wizard.get_prev_step()
'Returns the index for the current step.'
@property def index(self):
return self._wizard.get_step_index()
'This method is used within urls.py to create unique wizardview instances for every request. We need to override this method because we add some kwargs which are needed to make the wizardview usable.'
@classonlymethod def as_view(cls, *args, **kwargs):
initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs)
'Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the wizardview will convert the class list to (`zero_based_counter`, `form_class`). This is nee...
@classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs):
kwargs.update({'initial_dict': (initial_dict or {}), 'instance_dict': (instance_dict or {}), 'condition_dict': (condition_dict or {})}) init_form_list = SortedDict() assert (len(form_list) > 0), 'at least one form is needed' for (i, form) in enumerate(form_list): if isinstance(for...
'This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on...
def get_form_list(self):
form_list = SortedDict() for (form_key, form_class) in self.form_list.iteritems(): condition = self.condition_dict.get(form_key, True) if callable(condition): condition = condition(self) if condition: form_list[form_key] = form_class return form_list
'This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the sto...
def dispatch(self, request, *args, **kwargs):
self.prefix = self.get_prefix(*args, **kwargs) self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) self.storage.update_response(response) retu...
'This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step.'
def get(self, request, *args, **kwargs):
self.storage.reset() self.storage.current_step = self.steps.first return self.render(self.get_form())
'This method handles POST requests. The wizard will render either the current step (if form validation wasn\'t successful), the next step (if the current step was stored successful) or the done view (if no more steps are available)'
def post(self, *args, **kwargs):
wizard_goto_step = self.request.POST.get('wizard_goto_step', None) if (wizard_goto_step and (wizard_goto_step in self.get_form_list())): self.storage.current_step = wizard_goto_step form = self.get_form(data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.s...
'This method gets called when the next step/form should be rendered. `form` contains the last/current form.'
def render_next_step(self, form, **kwargs):
next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) self.storage.current_step = next_step return self.render(new_form, **kwargs)
'This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don\'t validate, `render_revalidation_failure` should get called. If everything is fine call `done`.'
def render_done(self, form, **kwargs):
final_form_list = [] for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if (not form_obj.is_valid()): return self.render_revalidation_failure(form_key, form_obj, **kwarg...
'Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically.'
def get_form_prefix(self, step=None, form=None):
if (step is None): step = self.steps.current return str(step)
'Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned.'
def get_form_initial(self, step):
return self.initial_dict.get(step, {})
'Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None will be returned.'
def get_form_instance(self, step):
return self.instance_dict.get(step, None)
'Returns the keyword arguments for instantiating the form (or formset) on the given step.'
def get_form_kwargs(self, step=None):
return {}
'Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too.'
def get_form(self, step=None, data=None, files=None):
if (step is None): step = self.steps.current kwargs = self.get_form_kwargs(step) kwargs.update({'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step)}) if issubclass(self.form_list[step], forms.ModelForm): kwargs....
'This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary.'
def process_step(self, form):
return self.get_form_step_data(form)
'This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary.'
def process_step_files(self, form):
return self.get_form_step_files(form)
'Gets called when a form doesn\'t validate when rendering the done view. By default, it changes the current step to failing forms step and renders the form.'
def render_revalidation_failure(self, step, form, **kwargs):
self.storage.current_step = step return self.render(form, **kwargs)
'Is used to return the raw form data. You may use this method to manipulate the data.'
def get_form_step_data(self, form):
return form.data
'Is used to return the raw form files. You may use this method to manipulate the data.'
def get_form_step_files(self, form):
return form.files
'Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset cleaned_data dictionaries.'
def get_all_cleaned_data(self):
cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned...
'Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn\'t validate, None will be returned.'
def get_cleaned_data_for_step(self, step):
if (step in self.form_list): form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None
'Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically.'
def get_next_step(self, step=None):
if (step is None): step = self.steps.current form_list = self.get_form_list() key = (form_list.keyOrder.index(step) + 1) if (len(form_list.keyOrder) > key): return form_list.keyOrder[key] return None
'Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically.'
def get_prev_step(self, step=None):
if (step is None): step = self.steps.current form_list = self.get_form_list() key = (form_list.keyOrder.index(step) - 1) if (key >= 0): return form_list.keyOrder[key] return None
'Returns the index for the given `step` name. If no step is given, the current step will be used to get the index.'
def get_step_index(self, step=None):
if (step is None): step = self.steps.current return self.get_form_list().keyOrder.index(step)
'Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wiz...
def get_context_data(self, form, **kwargs):
context = super(WizardView, self).get_context_data(**kwargs) context.update(self.storage.extra_data) context['wizard'] = {'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={'current_step': self.steps.current})} return context
'Returns a ``HttpResponse`` containing all needed context data.'
def render(self, form=None, **kwargs):
form = (form or self.get_form()) context = self.get_context_data(form=form, **kwargs) return self.render_to_response(context)
'This method must be overridden by a subclass to process to form data after processing all steps.'
def done(self, form_list, **kwargs):
raise NotImplementedError(('Your %s class has not defined a done() method, which is required.' % self.__class__.__name__))
'We require a url_name to reverse URLs later. Additionally users can pass a done_step_name to change the URL name of the "done" view.'
@classmethod def get_initkwargs(cls, *args, **kwargs):
assert ('url_name' in kwargs), 'URL name is needed to resolve correct wizard URLs' extra_kwargs = {'done_step_name': kwargs.pop('done_step_name', 'done'), 'url_name': kwargs.pop('url_name')} initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs) initkwargs.up...
'This renders the form or, if needed, does the http redirects.'
def get(self, *args, **kwargs):
step_url = kwargs.get('step', None) if (step_url is None): if ('reset' in self.request.GET): self.storage.reset() self.storage.current_step = self.steps.first if self.request.GET: query_string = ('?%s' % self.request.GET.urlencode()) else: ...
'Do a redirect if user presses the prev. step button. The rest of this is super\'d from WizardView.'
def post(self, *args, **kwargs):
wizard_goto_step = self.request.POST.get('wizard_goto_step', None) if (wizard_goto_step and (wizard_goto_step in self.get_form_list())): self.storage.current_step = wizard_goto_step return redirect(self.get_step_url(wizard_goto_step)) return super(NamedUrlWizardView, self).post(*args, **kwar...
'NamedUrlWizardView provides the url_name of this wizard in the context dict `wizard`.'
def get_context_data(self, form, **kwargs):
context = super(NamedUrlWizardView, self).get_context_data(form=form, **kwargs) context['wizard']['url_name'] = self.url_name return context
'When using the NamedUrlWizardView, we have to redirect to update the browser\'s URL to match the shown step.'
def render_next_step(self, form, **kwargs):
next_step = self.get_next_step() self.storage.current_step = next_step return redirect(self.get_step_url(next_step))
'When a step fails, we have to redirect the user to the first failing step.'
def render_revalidation_failure(self, failed_step, form, **kwargs):
self.storage.current_step = failed_step return redirect(self.get_step_url(failed_step))
'When rendering the done view, we have to redirect first (if the URL name doesn\'t fit).'
def render_done(self, form, **kwargs):
if (kwargs.get('step', None) != self.done_step_name): return redirect(self.get_step_url(self.done_step_name)) return super(NamedUrlWizardView, self).render_done(form, **kwargs)
'Given a first-choice name, adds an underscore to the name until it reaches a name that isn\'t claimed by any field in the form. This is calculated rather than being hard-coded so that no field names are off-limits for use in the form.'
def unused_name(self, name):
while 1: try: f = self.form.base_fields[name] except KeyError: break name += '_' return name
'Displays the form'
def preview_get(self, request):
f = self.form(auto_id=self.get_auto_id(), initial=self.get_initial(request)) return render_to_response(self.form_template, self.get_context(request, f), context_instance=RequestContext(request))
'Validates the POST data. If valid, displays the preview page. Else, redisplays form.'
def preview_post(self, request):
f = self.form(request.POST, auto_id=self.get_auto_id()) context = self.get_context(request, f) if f.is_valid(): self.process_preview(request, f, context) context['hash_field'] = self.unused_name('hash') context['hash_value'] = self.security_hash(request, f) return render_to_r...
'Validates the POST data. If valid, calls done(). Else, redisplays form.'
def post_post(self, request):
f = self.form(request.POST, auto_id=self.get_auto_id()) if f.is_valid(): if (not self._check_security_hash(request.POST.get(self.unused_name('hash'), ''), request, f)): return self.failed_hash(request) return self.done(request, f.cleaned_data) else: return render_to_respo...
'Hook to override the ``auto_id`` kwarg for the form. Needed when rendering two form previews in the same template.'
def get_auto_id(self):
return AUTO_ID
'Takes a request argument and returns a dictionary to pass to the form\'s ``initial`` kwarg when the form is being created from an HTTP get.'
def get_initial(self, request):
return {}
'Context for template rendering.'
def get_context(self, request, form):
return {'form': form, 'stage_field': self.unused_name('stage'), 'state': self.state}
'Given captured args and kwargs from the URLconf, saves something in self.state and/or raises Http404 if necessary. For example, this URLconf captures a user_id variable: (r\'^contact/(?P<user_id>\d{1,6})/$\', MyFormPreview(MyForm)), In this case, the kwargs variable in parse_params would be {\'user_id\': 32} for a req...
def parse_params(self, *args, **kwargs):
pass
'Given a validated form, performs any extra processing before displaying the preview page, and saves any extra data in context.'
def process_preview(self, request, form, context):
pass
'Calculates the security hash for the given HttpRequest and Form instances. Subclasses may want to take into account request-specific information, such as the IP address.'
def security_hash(self, request, form):
return form_hmac(form)
'Returns an HttpResponse in the case of an invalid security hash.'
def failed_hash(self, request):
return self.preview_post(request)
'Does something with the cleaned_data and returns an HttpResponseRedirect.'
def done(self, request, cleaned_data):
raise NotImplementedError(('You must define a done() method on your %s subclass.' % self.__class__.__name__))
'Verifies name mangling to get uniue field name.'
def test_unused_name(self):
self.assertEqual(self.preview.unused_name('field1'), 'field1__')
'Test contrib.formtools.preview form retrieval. Use the client library to see if we can sucessfully retrieve the form (mostly testing the setup ROOT_URLCONF process). Verify that an additional hidden input field is created to manage the stage.'
def test_form_get(self):
response = self.client.get('/preview/') stage = (self.input % 1) self.assertContains(response, stage, 1) self.assertEqual(response.context['custom_context'], True) self.assertEqual(response.context['form'].initial, {'field1': 'Works!'})
'Test contrib.formtools.preview form preview rendering. Use the client library to POST to the form to see if a preview is returned. If we do get a form back check that the hidden value is correctly managing the state of the form.'
def test_form_preview(self):
self.test_data.update({'stage': 1}) response = self.client.post('/preview/', self.test_data) stage = (self.input % 2) self.assertContains(response, stage, 1)
'Test contrib.formtools.preview form submittal. Use the client library to POST to the form with stage set to 3 to see if our forms done() method is called. Check first without the security hash, verify failure, retry with security hash and verify sucess.'
def test_form_submit(self):
self.test_data.update({'stage': 2}) response = self.client.post('/preview/', self.test_data) self.assertNotEqual(response.content, success_string) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/preview/', self...
'Test contrib.formtools.preview form submittal when form contains: BooleanField(required=False) Ticket: #6209 - When an unchecked BooleanField is previewed, the preview form\'s hash would be computed with no value for ``bool1``. However, when the preview form is rendered, the unchecked hidden BooleanField would be rend...
def test_bool_submit(self):
self.test_data.update({'stage': 2}) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash, 'bool1': u'False'}) response = self.client.post('/preview/', self.test_data) self.assertEqual(response.content, success_string)
'Test contrib.formtools.preview form submittal, using a correct hash'
def test_form_submit_good_hash(self):
self.test_data.update({'stage': 2}) response = self.client.post('/preview/', self.test_data) self.assertNotEqual(response.content, success_string) hash = utils.form_hmac(TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/preview/', self.test_data) s...
'Test contrib.formtools.preview form submittal does not proceed if the hash is incorrect.'
def test_form_submit_bad_hash(self):
self.test_data.update({'stage': 2}) response = self.client.post('/preview/', self.test_data) self.assertEqual(response.status_code, 200) self.assertNotEqual(response.content, success_string) hash = (utils.form_hmac(TestForm(self.test_data)) + 'bad') self.test_data.update({'hash': hash}) resp...
'Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas).'
def test_textfield_hash(self):
f1 = HashTestForm({'name': 'joe', 'bio': 'Nothing notable.'}) f2 = HashTestForm({'name': ' joe', 'bio': 'Nothing notable. '}) hash1 = utils.security_hash(None, f1) hash2 = utils.security_hash(None, f2) self.assertEqual(hash1, hash2)
'Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed.'
def test_empty_permitted(self):
f1 = HashTestBlankForm({}) f2 = HashTestForm({}, empty_permitted=True) hash1 = utils.security_hash(None, f1) hash2 = utils.security_hash(None, f2) self.assertEqual(hash1, hash2)
'Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas).'
def test_textfield_hash(self):
f1 = HashTestForm({'name': 'joe', 'bio': 'Nothing notable.'}) f2 = HashTestForm({'name': ' joe', 'bio': 'Nothing notable. '}) hash1 = utils.form_hmac(f1) hash2 = utils.form_hmac(f2) self.assertEqual(hash1, hash2)
'Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed.'
def test_empty_permitted(self):
f1 = HashTestBlankForm({}) f2 = HashTestForm({}, empty_permitted=True) hash1 = utils.form_hmac(f1) hash2 = utils.form_hmac(f2) self.assertEqual(hash1, hash2)
'step should be zero for the first form'
def test_step_starts_at_zero(self):
response = self.client.get('/wizard1/') self.assertEqual(0, response.context['step0'])
'step should be incremented when we go to the next page'
def test_step_increments(self):
response = self.client.post('/wizard1/', {'0-field': 'test', 'wizard_step': '0'}) self.assertEqual(1, response.context['step0'])
'Form should not advance if the hash is missing or bad'
def test_bad_hash(self):
response = self.client.post('/wizard1/', {'0-field': 'test', '1-field': 'test2', 'wizard_step': '1'}) self.assertEqual(0, response.context['step0'])
'Form should advance if the hash is present and good, as calculated using current method.'
def test_good_hash(self):
data = {'0-field': 'test', '1-field': 'test2', 'hash_0': '7e9cea465f6a10a6fb47fcea65cb9a76350c9a5c', 'wizard_step': '1'} response = self.client.post('/wizard1/', data) self.assertEqual(2, response.context['step0'])
'Regression test for ticket #11726. Wizard should not raise Http404 when steps are added dynamically.'
def test_11726(self):
reached = [False] that = self class WizardWithProcessStep(TestWizardClass, ): def process_step(self, request, form, step): if (step == 0): if (self.num_steps() < 2): self.form_list.append(WizardPageTwoForm) if (step == 1): t...
'Regression test for ticket #14498. All previous steps\' forms should be validated.'
def test_14498(self):
reached = [False] that = self class WizardWithProcessStep(TestWizardClass, ): def process_step(self, request, form, step): that.assertTrue(hasattr(form, 'cleaned_data')) reached[0] = True wizard = WizardWithProcessStep([WizardPageOneForm, WizardPageTwoForm, WizardPageThre...
'Regression test for ticket #14576. The form of the last step is not passed to the done method.'
def test_14576(self):
reached = [False] that = self class Wizard(TestWizardClass, ): def done(self, request, form_list): reached[0] = True that.assertTrue((len(form_list) == 2)) wizard = Wizard([WizardPageOneForm, WizardPageTwoForm]) data = {'0-field': 'test', '1-field': 'test2', 'hash_0':...
'Regression test for ticket #15075. Allow modifying wizard\'s form_list in process_step.'
def test_15075(self):
reached = [False] that = self class WizardWithProcessStep(TestWizardClass, ): def process_step(self, request, form, step): if (step == 0): self.form_list[1] = WizardPageTwoAlternativeForm if (step == 1): that.assertTrue(isinstance(form, WizardP...
'Pull the appropriate field data from the context to pass to the next wizard step'
def grab_field_data(self, response):
previous_fields = response.context['previous_fields'] fields = {'wizard_step': response.context['step0']} def grab(m): fields[m.group(1)] = m.group(2) return '' self.input_re.sub(grab, previous_fields) return fields
'Helper function to test each step of the wizard - Make sure the call succeeded - Make sure response is the proper step number - return the result from the post for the next step'
def check_wizard_step(self, response, step_no):
step_count = len(self.wizard_step_data) self.assertEqual(response.status_code, 200) self.assertContains(response, ('Step %d of %d' % (step_no, step_count))) data = self.grab_field_data(response) data.update(self.wizard_step_data[(step_no - 1)]) return self.client.post('/wizard2/', data)...
'Returns the ContentType object for a given model, creating the ContentType if necessary. Lookups are cached so that subsequent lookups for the same model don\'t hit the database.'
def get_for_model(self, model):
opts = self._get_opts(model) try: ct = self._get_from_cache(opts) except KeyError: (ct, created) = self.get_or_create(app_label=opts.app_label, model=opts.object_name.lower(), defaults={'name': smart_unicode(opts.verbose_name_raw)}) self._add_to_cache(self.db, ct) return ct
'Given *models, returns a dictionary mapping {model: content_type}.'
def get_for_models(self, *models):
results = {} needed_app_labels = set() needed_models = set() needed_opts = set() for model in models: opts = self._get_opts(model) try: ct = self._get_from_cache(opts) except KeyError: needed_app_labels.add(opts.app_label) needed_models.add...
'Lookup a ContentType by ID. Uses the same shared cache as get_for_model (though ContentTypes are obviously not created on-the-fly by get_by_id).'
def get_for_id(self, id):
try: ct = self.__class__._cache[self.db][id] except KeyError: ct = self.get(pk=id) self._add_to_cache(self.db, ct) return ct
'Clear out the content-type cache. This needs to happen during database flushes to prevent caching of "stale" content type IDs (see django.contrib.contenttypes.management.update_contenttypes for where this gets called).'
def clear_cache(self):
self.__class__._cache.clear()
'Insert a ContentType into the cache.'
def _add_to_cache(self, using, ct):
model = ct.model_class() key = (model._meta.app_label, model._meta.object_name.lower()) self.__class__._cache.setdefault(using, {})[key] = ct self.__class__._cache.setdefault(using, {})[ct.id] = ct
'Returns the Python model class for this type of content.'
def model_class(self):
from django.db import models return models.get_model(self.app_label, self.model, only_installed=False)
'Returns an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type\'s get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it.'
def get_object_for_this_type(self, **kwargs):
return self.model_class()._base_manager.using(self._state.db).get(**kwargs)
'Returns all objects of this type for the keyword arguments given.'
def get_all_objects_for_this_type(self, **kwargs):
return self.model_class()._base_manager.using(self._state.db).filter(**kwargs)
'Handles initializing an object with the generic FK instaed of content-type/object-id fields.'
def instance_pre_init(self, signal, sender, args, kwargs, **_kwargs):
if (self.name in kwargs): value = kwargs.pop(self.name) kwargs[self.ct_field] = self.get_content_type(obj=value) kwargs[self.fk_field] = value._get_pk_val()