desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Returns a list of permission strings that this user has through his/her
groups. This method queries all available auth backends. If an object
is passed in, only permissions matching this object are returned.'
| def get_group_permissions(self, obj=None):
| permissions = set()
for backend in auth.get_backends():
if hasattr(backend, u'get_group_permissions'):
if (obj is not None):
permissions.update(backend.get_group_permissions(self, obj))
else:
permissions.update(backend.get_group_permissions(self))
return permissions
|
'Returns True if the user has the specified permission. This method
queries all available auth backends, but returns immediately if any
backend returns True. Thus, a user who has permission from a single
auth backend is assumed to have permission in general. If an object is
provided, permissions for this specific object are checked.'
| def has_perm(self, perm, obj=None):
| if (self.is_active and self.is_superuser):
return True
return _user_has_perm(self, perm, obj)
|
'Returns True if the user has each of the specified permissions. If
object is passed, it checks if the user has all required perms for this
object.'
| def has_perms(self, perm_list, obj=None):
| for perm in perm_list:
if (not self.has_perm(perm, obj)):
return False
return True
|
'Returns True if the user has any permissions in the given app label.
Uses pretty much the same logic as has_perm, above.'
| def has_module_perms(self, app_label):
| if (self.is_active and self.is_superuser):
return True
return _user_has_module_perms(self, app_label)
|
'Returns the first_name plus the last_name, with a space in between.'
| def get_full_name(self):
| full_name = (u'%s %s' % (self.first_name, self.last_name))
return full_name.strip()
|
'Returns the short name for the user.'
| def get_short_name(self):
| return self.first_name
|
'Sends an email to this User.'
| def email_user(self, subject, message, from_email=None):
| send_mail(subject, message, from_email, [self.email])
|
'Returns site-specific profile for this user. Raises
SiteProfileNotAvailable if this site does not allow profiles.'
| def get_profile(self):
| warnings.warn(u'The use of AUTH_PROFILE_MODULE to define user profiles has been deprecated.', PendingDeprecationWarning)
if (not hasattr(self, u'_profile_cache')):
from django.conf import settings
if (not getattr(settings, u'AUTH_PROFILE_MODULE', False)):
raise SiteProfileNotAvailable(u'You need to set AUTH_PROFILE_MODULE in your project settings')
try:
(app_label, model_name) = settings.AUTH_PROFILE_MODULE.split(u'.')
except ValueError:
raise SiteProfileNotAvailable(u'app_label and model_name should be separated by a dot in the AUTH_PROFILE_MODULE setting')
try:
model = models.get_model(app_label, model_name)
if (model is None):
raise SiteProfileNotAvailable(u'Unable to load the profile model, check AUTH_PROFILE_MODULE in your project settings')
self._profile_cache = model._default_manager.using(self._state.db).get(user__id__exact=self.id)
self._profile_cache.user = self
except (ImportError, ImproperlyConfigured):
raise SiteProfileNotAvailable
return self._profile_cache
|
'Lookup by "someapp" or "someapp.someperm" in perms.'
| def __contains__(self, perm_name):
| if ('.' not in perm_name):
return bool(self[perm_name])
(module_name, perm_name) = perm_name.split('.', 1)
return self[module_name][perm_name]
|
'Returns a set of permission strings that this user has through his/her
groups.'
| def get_group_permissions(self, user_obj, obj=None):
| if (user_obj.is_anonymous() or (obj is not None)):
return set()
if (not hasattr(user_obj, u'_group_perm_cache')):
if user_obj.is_superuser:
perms = Permission.objects.all()
else:
user_groups_field = get_user_model()._meta.get_field(u'groups')
user_groups_query = (u'group__%s' % user_groups_field.related_query_name())
perms = Permission.objects.filter(**{user_groups_query: user_obj})
perms = perms.values_list(u'content_type__app_label', u'codename').order_by()
user_obj._group_perm_cache = set([(u'%s.%s' % (ct, name)) for (ct, name) in perms])
return user_obj._group_perm_cache
|
'Returns True if user_obj has any permissions in the given app_label.'
| def has_module_perms(self, user_obj, app_label):
| if (not user_obj.is_active):
return False
for perm in self.get_all_permissions(user_obj):
if (perm[:perm.index(u'.')] == app_label):
return True
return False
|
'The username passed as ``remote_user`` is considered trusted. This
method simply returns the ``User`` object with the given username,
creating a new ``User`` object if ``create_unknown_user`` is ``True``.
Returns None if ``create_unknown_user`` is ``False`` and a ``User``
object with the given username is not found in the database.'
| def authenticate(self, remote_user):
| if (not remote_user):
return
user = None
username = self.clean_username(remote_user)
UserModel = get_user_model()
if self.create_unknown_user:
(user, created) = UserModel.objects.get_or_create(**{UserModel.USERNAME_FIELD: username})
if created:
user = self.configure_user(user)
else:
try:
user = UserModel.objects.get_by_natural_key(username)
except UserModel.DoesNotExist:
pass
return user
|
'Performs any cleaning on the "username" prior to using it to get or
create the user object. Returns the cleaned username.
By default, returns the username unchanged.'
| def clean_username(self, username):
| return username
|
'Configures a user after creation and returns the updated user.
By default, returns the user unmodified.'
| def configure_user(self, user):
| return user
|
'Use special form during user creation'
| def get_form(self, request, obj=None, **kwargs):
| defaults = {}
if (obj is None):
defaults.update({'form': self.add_form, 'fields': admin.util.flatten_fieldsets(self.add_fieldsets)})
defaults.update(kwargs)
return super(UserAdmin, self).get_form(request, obj, **defaults)
|
'Determines the HttpResponse for the add_view stage. It mostly defers to
its superclass implementation but is customized because the User model
has a slightly different workflow.'
| def response_add(self, request, obj, post_url_continue=None):
| if (('_addanother' not in request.POST) and ('_popup' not in request.POST)):
request.POST['_continue'] = 1
return super(UserAdmin, self).response_add(request, obj, post_url_continue)
|
'Generates a cryptographically secure nonce salt in ascii'
| def salt(self):
| return get_random_string()
|
'Checks if the given password is correct'
| def verify(self, password, encoded):
| raise NotImplementedError()
|
'Creates an encoded database value
The result is normally formatted as "algorithm$salt$hash" and
must be fewer than 128 characters.'
| def encode(self, password, salt):
| raise NotImplementedError()
|
'Returns a summary of safe values
The result is a dictionary and will be used where the password field
must be displayed to construct a safe representation of the password.'
| def safe_summary(self, encoded):
| raise NotImplementedError()
|
'If request is passed in, the form will validate that cookies are
enabled. Note that the request (a HttpRequest object) must have set a
cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
running this validation.'
| def __init__(self, request=None, *args, **kwargs):
| self.request = request
self.user_cache = None
super(AuthenticationForm, self).__init__(*args, **kwargs)
UserModel = get_user_model()
self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
if (not self.fields[u'username'].label):
self.fields[u'username'].label = capfirst(self.username_field.verbose_name)
|
'Validates that an active user exists with the given email address.'
| def clean_email(self):
| UserModel = get_user_model()
email = self.cleaned_data[u'email']
self.users_cache = UserModel._default_manager.filter(email__iexact=email)
if (not len(self.users_cache)):
raise forms.ValidationError(self.error_messages[u'unknown'])
if (not any((user.is_active for user in self.users_cache))):
raise forms.ValidationError(self.error_messages[u'unknown'])
if any(((user.password == UNUSABLE_PASSWORD) for user in self.users_cache)):
raise forms.ValidationError(self.error_messages[u'unusable'])
return email
|
'Generates a one-use only link for resetting password and sends to the
user.'
| def save(self, domain_override=None, subject_template_name=u'registration/password_reset_subject.txt', email_template_name=u'registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None):
| from django.core.mail import send_mail
for user in self.users_cache:
if (not domain_override):
current_site = get_current_site(request)
site_name = current_site.name
domain = current_site.domain
else:
site_name = domain = domain_override
c = {u'email': user.email, u'domain': domain, u'site_name': site_name, u'uid': int_to_base36(user.pk), u'user': user, u'token': token_generator.make_token(user), u'protocol': ((use_https and u'https') or u'http')}
subject = loader.render_to_string(subject_template_name, c)
subject = u''.join(subject.splitlines())
email = loader.render_to_string(email_template_name, c)
send_mail(subject, email, from_email, [user.email])
|
'Validates that the old_password field is correct.'
| def clean_old_password(self):
| old_password = self.cleaned_data[u'old_password']
if (not self.user.check_password(old_password)):
raise forms.ValidationError(self.error_messages[u'password_incorrect'])
return old_password
|
'Saves the new password.'
| def save(self, commit=True):
| self.user.set_password(self.cleaned_data[u'password1'])
if commit:
self.user.save()
return self.user
|
'Returns a token that can be used once to do a password reset
for the given user.'
| def make_token(self, user):
| return self._make_token_with_timestamp(user, self._num_days(self._today()))
|
'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._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS):
return False
return True
|
'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.', DeprecationWarning)
|
'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.POST)
if (not self._check_security_hash(request.POST.get(('hash_%d' % i), ''), request, f)):
return self.render_hash_failure(request, i)
if (not f.is_valid()):
return self.render_revalidation_failure(request, i, f)
else:
self.process_step(request, f, i)
previous_form_list.append(f)
if (request.method == 'POST'):
form = self.get_form(current_step, request.POST)
else:
form = self.get_form(current_step)
if form.is_valid():
self.process_step(request, form, current_step)
next_step = (current_step + 1)
if (next_step == self.num_steps()):
return self.done(request, (previous_form_list + [form]))
else:
form = self.get_form(next_step)
self.step = current_step = next_step
return self.render(form, request, current_step)
|
'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(hidden.render(hash_name, old_data.get(hash_name, self.security_hash(request, old_form))))
return self.render_template(request, form, ''.join(prev_fields), step, context)
|
'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 name of the hidden field containing the step.
step0 -- The current step (zero-based).
step -- The current step (one-based).
step_count -- The total number of steps.
form -- The Form instance for the current step (either empty
or with errors).
previous_fields -- A string representing every previous data field,
plus hashes for completed forms, all in the form of
hidden fields. Note that you\'ll need to run this
through the "safe" template filter, to prevent
auto-escaping, because it\'s raw HTML.'
| 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 that this method is called every time a page is rendered for *all*
submitted steps.'
| 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 list(self._wizard.get_form_list())
|
'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 needed to access the
form for a specific step.
* `initial_dict` - contains a dictionary of initial data dictionaries.
The key should be equal to the `step_name` in the `form_list` (or
the str of the zero based counter - if no step_names added in the
`form_list`)
* `instance_dict` - contains a dictionary whose values are model
instances if the step is based on a ``ModelForm`` and querysets if
the step is based on a ``ModelFormSet``. The key should be equal to
the `step_name` in the `form_list`. Same rules as for `initial_dict`
apply.
* `condition_dict` - contains a dictionary of boolean values or
callables. If the value of for a specific `step_name` is callable it
will be called with the wizardview instance as the only argument.
If the return value is true, the step\'s form will be used.'
| @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(form, (list, tuple)):
init_form_list[six.text_type(form[0])] = form[1]
else:
init_form_list[six.text_type(i)] = form
for form in six.itervalues(init_form_list):
if issubclass(form, formsets.BaseFormSet):
form = form.form
for field in six.itervalues(form.base_fields):
if (isinstance(field, forms.FileField) and (not hasattr(cls, 'file_storage'))):
raise NoFileStorageConfigured("You need to define 'file_storage' in your wizard view in order to handle file uploads.")
kwargs['form_list'] = init_form_list
return kwargs
|
'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 the fly because condition methods
could use data from other (maybe previous forms).'
| def get_form_list(self):
| form_list = SortedDict()
for (form_key, form_class) in six.iteritems(self.form_list):
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 storage engine (for example add cookies).'
| 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)
return response
|
'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.steps.current))
return self.render(form)
management_form = ManagementForm(self.request.POST, prefix=self.prefix)
if (not management_form.is_valid()):
raise ValidationError('ManagementForm data is missing or has been tampered.')
form_current_step = management_form.cleaned_data['current_step']
if ((form_current_step != self.steps.current) and (self.storage.current_step is not None)):
self.storage.current_step = form_current_step
form = self.get_form(data=self.request.POST, files=self.request.FILES)
if form.is_valid():
self.storage.set_step_data(self.steps.current, self.process_step(form))
self.storage.set_step_files(self.steps.current, self.process_step_files(form))
if (self.steps.current == self.steps.last):
return self.render_done(form, **kwargs)
else:
return self.render_next_step(form)
return self.render(form)
|
'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, **kwargs)
final_form_list.append(form_obj)
done_response = self.done(final_form_list, **kwargs)
self.storage.reset()
return done_response
|
'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.setdefault('instance', self.get_form_instance(step))
elif issubclass(self.form_list[step], forms.models.BaseModelFormSet):
kwargs.setdefault('queryset', self.get_form_instance(step))
return self.form_list[step](**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_data.update({('formset-%s' % form_key): form_obj.cleaned_data})
else:
cleaned_data.update(form_obj.cleaned_data)
return cleaned_data
|
'Returns the cleaned data for a given `step`. Before returning the
cleaned data, the stored values are 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
* `wizard` - the wizard instance itself
Example:
.. code-block:: python
class MyWizard(WizardView):
def get_context_data(self, form, **kwargs):
context = super(MyWizard, self).get_context_data(form=form, **kwargs)
if self.steps.current == \'my_step_name\':
context.update({\'another_var\': True})
return context'
| def get_context_data(self, form, **kwargs):
| context = super(WizardView, self).get_context_data(form=form, **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.update(extra_kwargs)
assert (initkwargs['done_step_name'] not in initkwargs['form_list']), ('step name "%s" is reserved for "done" view' % initkwargs['done_step_name'])
return initkwargs
|
'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:
query_string = ''
return redirect((self.get_step_url(self.steps.current) + query_string))
elif (step_url == self.done_step_name):
last_step = self.steps.last
return self.render_done(self.get_form(step=last_step, data=self.storage.get_step_data(last_step), files=self.storage.get_step_files(last_step)), **kwargs)
elif (step_url == self.steps.current):
return self.render(self.get_form(data=self.storage.current_step_data, files=self.storage.current_step_files), **kwargs)
elif (step_url in self.get_form_list()):
self.storage.current_step = step_url
return self.render(self.get_form(data=self.storage.current_step_data, files=self.storage.current_step_files), **kwargs)
else:
self.storage.current_step = self.steps.first
return redirect(self.get_step_url(self.steps.first))
|
'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, **kwargs)
|
'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_response(self.preview_template, context, context_instance=RequestContext(request))
else:
return render_to_response(self.form_template, context, context_instance=RequestContext(request))
|
'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_response(self.form_template, self.get_context(request, f), context_instance=RequestContext(request))
|
'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 request to \'/contact/32/\'. You can use that
user_id to make sure it\'s a valid user and/or save it for later, for
use in done().'
| 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(u'field1'), u'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(u'/preview/')
stage = (self.input % 1)
self.assertContains(response, stage, 1)
self.assertEqual(response.context[u'custom_context'], True)
self.assertEqual(response.context[u'form'].initial, {u'field1': u'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({u'stage': 1, u'date1': datetime.date(2006, 10, 25)})
response = self.client.post(u'/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({u'stage': 2, u'date1': datetime.date(2006, 10, 25)})
response = self.client.post(u'/preview/', self.test_data)
self.assertNotEqual(response.content, success_string_encoded)
hash = self.preview.security_hash(None, TestForm(self.test_data))
self.test_data.update({u'hash': hash})
response = self.client.post(u'/preview/', self.test_data)
self.assertEqual(response.content, success_string_encoded)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.