desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn\'t examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to change the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to change *any* object of the given type.'
| def has_change_permission(self, request, obj=None):
| opts = self.opts
return request.user.has_perm(((opts.app_label + '.') + opts.get_change_permission()))
|
'Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn\'t examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to delete *any* object of the given type.'
| def has_delete_permission(self, request, obj=None):
| opts = self.opts
return request.user.has_perm(((opts.app_label + '.') + opts.get_delete_permission()))
|
'Returns a dict of all perms for this model. This dict has the keys
``add``, ``change``, and ``delete`` mapping to the True/False for each
of those actions.'
| def get_model_perms(self, request):
| return {'add': self.has_add_permission(request), 'change': self.has_change_permission(request), 'delete': self.has_delete_permission(request)}
|
'Hook for specifying fieldsets for the add form.'
| def get_fieldsets(self, request, obj=None):
| if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_form(request, obj)
fields = (list(form.base_fields) + list(self.get_readonly_fields(request, obj)))
return [(None, {'fields': fields})]
|
'Returns a Form class for use in the admin add view. This is used by
add_view and change_view.'
| def get_form(self, request, obj=None, **kwargs):
| if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if (self.exclude is None):
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
if ((self.exclude is None) and hasattr(self.form, '_meta') and self.form._meta.exclude):
exclude.extend(self.form._meta.exclude)
exclude = (exclude or None)
defaults = {'form': self.form, 'fields': fields, 'exclude': exclude, 'formfield_callback': partial(self.formfield_for_dbfield, request=request)}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
|
'Returns the ChangeList class for use on the changelist page.'
| def get_changelist(self, request, **kwargs):
| from django.contrib.admin.views.main import ChangeList
return ChangeList
|
'Returns an instance matching the primary key provided. ``None`` is
returned if no match is found (or the object_id failed validation
against the primary key field).'
| def get_object(self, request, object_id):
| queryset = self.queryset(request)
model = queryset.model
try:
object_id = model._meta.pk.to_python(object_id)
return queryset.get(pk=object_id)
except (model.DoesNotExist, ValidationError):
return None
|
'Returns a Form class for use in the Formset on the changelist page.'
| def get_changelist_form(self, request, **kwargs):
| defaults = {'formfield_callback': partial(self.formfield_for_dbfield, request=request)}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
|
'Returns a FormSet class for use on the changelist page if list_editable
is used.'
| def get_changelist_formset(self, request, **kwargs):
| defaults = {'formfield_callback': partial(self.formfield_for_dbfield, request=request)}
defaults.update(kwargs)
return modelformset_factory(self.model, self.get_changelist_form(request), extra=0, fields=self.list_editable, **defaults)
|
'Log that an object has been successfully added.
The default implementation creates an admin LogEntry object.'
| def log_addition(self, request, object):
| from django.contrib.admin.models import LogEntry, ADDITION
LogEntry.objects.log_action(user_id=request.user.pk, content_type_id=ContentType.objects.get_for_model(object).pk, object_id=object.pk, object_repr=force_text(object), action_flag=ADDITION)
|
'Log that an object has been successfully changed.
The default implementation creates an admin LogEntry object.'
| def log_change(self, request, object, message):
| from django.contrib.admin.models import LogEntry, CHANGE
LogEntry.objects.log_action(user_id=request.user.pk, content_type_id=ContentType.objects.get_for_model(object).pk, object_id=object.pk, object_repr=force_text(object), action_flag=CHANGE, change_message=message)
|
'Log that an object will be deleted. Note that this method is called
before the deletion.
The default implementation creates an admin LogEntry object.'
| def log_deletion(self, request, object, object_repr):
| from django.contrib.admin.models import LogEntry, DELETION
LogEntry.objects.log_action(user_id=request.user.pk, content_type_id=ContentType.objects.get_for_model(self.model).pk, object_id=object.pk, object_repr=object_repr, action_flag=DELETION)
|
'A list_display column containing a checkbox widget.'
| def action_checkbox(self, obj):
| return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_text(obj.pk))
|
'Return a dictionary mapping the names of all actions for this
ModelAdmin to a tuple of (callable, name, description) for each action.'
| def get_actions(self, request):
| from django.contrib.admin.views.main import IS_POPUP_VAR
if ((self.actions is None) or (IS_POPUP_VAR in request.GET)):
return SortedDict()
actions = []
for (name, func) in self.admin_site.actions:
description = getattr(func, 'short_description', name.replace('_', ' '))
actions.append((func, name, description))
for klass in self.__class__.mro()[::(-1)]:
class_actions = getattr(klass, 'actions', [])
if (not class_actions):
continue
actions.extend([self.get_action(action) for action in class_actions])
actions = filter(None, actions)
actions = SortedDict([(name, (func, name, desc)) for (func, name, desc) in actions])
return actions
|
'Return a list of choices for use in a form object. Each choice is a
tuple (name, description).'
| def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH):
| choices = ([] + default_choices)
for (func, name, description) in six.itervalues(self.get_actions(request)):
choice = (name, (description % model_format_dict(self.opts)))
choices.append(choice)
return choices
|
'Return a given action from a parameter, which can either be a callable,
or the name of a method on the ModelAdmin. Return is a tuple of
(callable, name, description).'
| def get_action(self, action):
| if callable(action):
func = action
action = action.__name__
elif hasattr(self.__class__, action):
func = getattr(self.__class__, action)
else:
try:
func = self.admin_site.get_action(action)
except KeyError:
return None
if hasattr(func, 'short_description'):
description = func.short_description
else:
description = capfirst(action.replace('_', ' '))
return (func, action, description)
|
'Return a sequence containing the fields to be displayed on the
changelist.'
| def get_list_display(self, request):
| return self.list_display
|
'Return a sequence containing the fields to be displayed as links
on the changelist. The list_display parameter is the list of fields
returned by get_list_display().'
| def get_list_display_links(self, request, list_display):
| if (self.list_display_links or (not list_display)):
return self.list_display_links
else:
return list(list_display)[:1]
|
'Returns a sequence containing the fields to be displayed as filters in
the right sidebar of the changelist page.'
| def get_list_filter(self, request):
| return self.list_filter
|
'Construct a change message from a changed object.'
| def construct_change_message(self, request, form, formsets):
| change_message = []
if form.changed_data:
change_message.append((_('Changed %s.') % get_text_list(form.changed_data, _('and'))))
if formsets:
for formset in formsets:
for added_object in formset.new_objects:
change_message.append((_('Added %(name)s "%(object)s".') % {'name': force_text(added_object._meta.verbose_name), 'object': force_text(added_object)}))
for (changed_object, changed_fields) in formset.changed_objects:
change_message.append((_('Changed %(list)s for %(name)s "%(object)s".') % {'list': get_text_list(changed_fields, _('and')), 'name': force_text(changed_object._meta.verbose_name), 'object': force_text(changed_object)}))
for deleted_object in formset.deleted_objects:
change_message.append((_('Deleted %(name)s "%(object)s".') % {'name': force_text(deleted_object._meta.verbose_name), 'object': force_text(deleted_object)}))
change_message = ' '.join(change_message)
return (change_message or _('No fields changed.'))
|
'Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.'
| def message_user(self, request, message, level=messages.INFO, extra_tags='', fail_silently=False):
| if (not isinstance(level, int)):
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join((('`%s`' % l) for l in levels))
raise ValueError(('Bad message level string: `%s`. Possible values are: %s' % (level, levels_repr)))
messages.add_message(request, level, message, extra_tags=extra_tags, fail_silently=fail_silently)
|
'Given a ModelForm return an unsaved instance. ``change`` is True if
the object is being changed, and False if it\'s being added.'
| def save_form(self, request, form, change):
| return form.save(commit=False)
|
'Given a model instance save it to the database.'
| def save_model(self, request, obj, form, change):
| obj.save()
|
'Given a model instance delete it from the database.'
| def delete_model(self, request, obj):
| obj.delete()
|
'Given an inline formset save it to the database.'
| def save_formset(self, request, form, formset, change):
| formset.save()
|
'Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
list of inline formsets and a boolean value based on whether the
parent is being added or changed, save the related objects to the
database. Note that at this point save_form() and save_model() have
already been called.'
| def save_related(self, request, form, formsets, change):
| form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=change)
|
'Determines the HttpResponse for the add_view stage.'
| def response_add(self, request, obj, post_url_continue=None):
| opts = obj._meta
pk_value = obj._get_pk_val()
msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)}
if ('_continue' in request.POST):
msg = (_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % msg_dict)
self.message_user(request, msg)
if (post_url_continue is None):
post_url_continue = reverse(('admin:%s_%s_change' % (opts.app_label, opts.module_name)), args=(pk_value,), current_app=self.admin_site.name)
else:
try:
post_url_continue = (post_url_continue % pk_value)
warnings.warn('The use of string formats for post_url_continue in ModelAdmin.response_add() is deprecated. Provide a pre-formatted url instead.', DeprecationWarning, stacklevel=2)
except TypeError:
pass
if ('_popup' in request.POST):
post_url_continue += '?_popup=1'
return HttpResponseRedirect(post_url_continue)
if ('_popup' in request.POST):
return HttpResponse(('<!DOCTYPE html><html><head><title></title></head><body><script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script></body></html>' % (escape(pk_value), escapejs(obj))))
elif ('_addanother' in request.POST):
msg = (_('The %(name)s "%(obj)s" was added successfully. You may add another %(name)s below.') % msg_dict)
self.message_user(request, msg)
return HttpResponseRedirect(request.path)
else:
msg = (_('The %(name)s "%(obj)s" was added successfully.') % msg_dict)
self.message_user(request, msg)
return self.response_post_save_add(request, obj)
|
'Determines the HttpResponse for the change_view stage.'
| def response_change(self, request, obj):
| opts = self.model._meta
pk_value = obj._get_pk_val()
msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)}
if ('_continue' in request.POST):
msg = (_('The %(name)s "%(obj)s" was changed successfully. You may edit it again below.') % msg_dict)
self.message_user(request, msg)
if ('_popup' in request.REQUEST):
return HttpResponseRedirect((request.path + '?_popup=1'))
else:
return HttpResponseRedirect(request.path)
elif ('_saveasnew' in request.POST):
msg = (_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % msg_dict)
self.message_user(request, msg)
return HttpResponseRedirect(reverse(('admin:%s_%s_change' % (opts.app_label, opts.module_name)), args=(pk_value,), current_app=self.admin_site.name))
elif ('_addanother' in request.POST):
msg = (_('The %(name)s "%(obj)s" was changed successfully. You may add another %(name)s below.') % msg_dict)
self.message_user(request, msg)
return HttpResponseRedirect(reverse(('admin:%s_%s_add' % (opts.app_label, opts.module_name)), current_app=self.admin_site.name))
else:
msg = (_('The %(name)s "%(obj)s" was changed successfully.') % msg_dict)
self.message_user(request, msg)
return self.response_post_save_change(request, obj)
|
'Figure out where to redirect after the \'Save\' button has been pressed
when adding a new object.'
| def response_post_save_add(self, request, obj):
| opts = self.model._meta
if self.has_change_permission(request, None):
post_url = reverse(('admin:%s_%s_changelist' % (opts.app_label, opts.module_name)), current_app=self.admin_site.name)
else:
post_url = reverse('admin:index', current_app=self.admin_site.name)
return HttpResponseRedirect(post_url)
|
'Figure out where to redirect after the \'Save\' button has been pressed
when editing an existing object.'
| def response_post_save_change(self, request, obj):
| opts = self.model._meta
if self.has_change_permission(request, None):
post_url = reverse(('admin:%s_%s_changelist' % (opts.app_label, opts.module_name)), current_app=self.admin_site.name)
else:
post_url = reverse('admin:index', current_app=self.admin_site.name)
return HttpResponseRedirect(post_url)
|
'Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.'
| def response_action(self, request, queryset):
| try:
action_index = int(request.POST.get('index', 0))
except ValueError:
action_index = 0
data = request.POST.copy()
data.pop(helpers.ACTION_CHECKBOX_NAME, None)
data.pop('index', None)
try:
data.update({'action': data.getlist('action')[action_index]})
except IndexError:
pass
action_form = self.action_form(data, auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
if action_form.is_valid():
action = action_form.cleaned_data['action']
select_across = action_form.cleaned_data['select_across']
(func, name, description) = self.get_actions(request)[action]
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
if ((not selected) and (not select_across)):
msg = _('Items must be selected in order to perform actions on them. No items have been changed.')
self.message_user(request, msg)
return None
if (not select_across):
queryset = queryset.filter(pk__in=selected)
response = func(self, request, queryset)
if isinstance(response, HttpResponse):
return response
else:
return HttpResponseRedirect(request.get_full_path())
else:
msg = _('No action selected.')
self.message_user(request, msg)
return None
|
'The \'add\' admin view for this model.'
| @csrf_protect_m
@transaction.commit_on_success
def add_view(self, request, form_url='', extra_context=None):
| model = self.model
opts = model._meta
if (not self.has_add_permission(request)):
raise PermissionDenied
ModelForm = self.get_form(request)
formsets = []
inline_instances = self.get_inline_instances(request, None)
if (request.method == 'POST'):
form = ModelForm(request.POST, request.FILES)
if form.is_valid():
new_object = self.save_form(request, form, change=False)
form_validated = True
else:
form_validated = False
new_object = self.model()
prefixes = {}
for (FormSet, inline) in zip(self.get_formsets(request), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = (prefixes.get(prefix, 0) + 1)
if ((prefixes[prefix] != 1) or (not prefix)):
prefix = ('%s-%s' % (prefix, prefixes[prefix]))
formset = FormSet(data=request.POST, files=request.FILES, instance=new_object, save_as_new=('_saveasnew' in request.POST), prefix=prefix, queryset=inline.queryset(request))
formsets.append(formset)
if (all_valid(formsets) and form_validated):
self.save_model(request, new_object, form, False)
self.save_related(request, form, formsets, False)
self.log_addition(request, new_object)
return self.response_add(request, new_object)
else:
initial = dict(request.GET.items())
for k in initial:
try:
f = opts.get_field(k)
except models.FieldDoesNotExist:
continue
if isinstance(f, models.ManyToManyField):
initial[k] = initial[k].split(',')
form = ModelForm(initial=initial)
prefixes = {}
for (FormSet, inline) in zip(self.get_formsets(request), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = (prefixes.get(prefix, 0) + 1)
if ((prefixes[prefix] != 1) or (not prefix)):
prefix = ('%s-%s' % (prefix, prefixes[prefix]))
formset = FormSet(instance=self.model(), prefix=prefix, queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)), self.get_prepopulated_fields(request), self.get_readonly_fields(request), model_admin=self)
media = (self.media + adminForm.media)
inline_admin_formsets = []
for (inline, formset) in zip(inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request))
readonly = list(inline.get_readonly_fields(request))
prepopulated = dict(inline.get_prepopulated_fields(request))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = (media + inline_admin_formset.media)
context = {'title': (_('Add %s') % force_text(opts.verbose_name)), 'adminform': adminForm, 'is_popup': ('_popup' in request.REQUEST), 'media': media, 'inline_admin_formsets': inline_admin_formsets, 'errors': helpers.AdminErrorList(form, formsets), 'app_label': opts.app_label}
context.update((extra_context or {}))
return self.render_change_form(request, context, form_url=form_url, add=True)
|
'The \'change\' admin view for this model.'
| @csrf_protect_m
@transaction.commit_on_success
def change_view(self, request, object_id, form_url='', extra_context=None):
| model = self.model
opts = model._meta
obj = self.get_object(request, unquote(object_id))
if (not self.has_change_permission(request, obj)):
raise PermissionDenied
if (obj is None):
raise Http404((_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)}))
if ((request.method == 'POST') and ('_saveasnew' in request.POST)):
return self.add_view(request, form_url=reverse(('admin:%s_%s_add' % (opts.app_label, opts.module_name)), current_app=self.admin_site.name))
ModelForm = self.get_form(request, obj)
formsets = []
inline_instances = self.get_inline_instances(request, obj)
if (request.method == 'POST'):
form = ModelForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
else:
form_validated = False
new_object = obj
prefixes = {}
for (FormSet, inline) in zip(self.get_formsets(request, new_object), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = (prefixes.get(prefix, 0) + 1)
if ((prefixes[prefix] != 1) or (not prefix)):
prefix = ('%s-%s' % (prefix, prefixes[prefix]))
formset = FormSet(request.POST, request.FILES, instance=new_object, prefix=prefix, queryset=inline.queryset(request))
formsets.append(formset)
if (all_valid(formsets) and form_validated):
self.save_model(request, new_object, form, True)
self.save_related(request, form, formsets, True)
change_message = self.construct_change_message(request, form, formsets)
self.log_change(request, new_object, change_message)
return self.response_change(request, new_object)
else:
form = ModelForm(instance=obj)
prefixes = {}
for (FormSet, inline) in zip(self.get_formsets(request, obj), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = (prefixes.get(prefix, 0) + 1)
if ((prefixes[prefix] != 1) or (not prefix)):
prefix = ('%s-%s' % (prefix, prefixes[prefix]))
formset = FormSet(instance=obj, prefix=prefix, queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.get_prepopulated_fields(request, obj), self.get_readonly_fields(request, obj), model_admin=self)
media = (self.media + adminForm.media)
inline_admin_formsets = []
for (inline, formset) in zip(inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
readonly = list(inline.get_readonly_fields(request, obj))
prepopulated = dict(inline.get_prepopulated_fields(request, obj))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = (media + inline_admin_formset.media)
context = {'title': (_('Change %s') % force_text(opts.verbose_name)), 'adminform': adminForm, 'object_id': object_id, 'original': obj, 'is_popup': ('_popup' in request.REQUEST), 'media': media, 'inline_admin_formsets': inline_admin_formsets, 'errors': helpers.AdminErrorList(form, formsets), 'app_label': opts.app_label}
context.update((extra_context or {}))
return self.render_change_form(request, context, change=True, obj=obj, form_url=form_url)
|
'The \'change list\' admin view for this model.'
| @csrf_protect_m
def changelist_view(self, request, extra_context=None):
| from django.contrib.admin.views.main import ERROR_FLAG
opts = self.model._meta
app_label = opts.app_label
if (not self.has_change_permission(request, None)):
raise PermissionDenied
list_display = self.get_list_display(request)
list_display_links = self.get_list_display_links(request, list_display)
list_filter = self.get_list_filter(request)
actions = self.get_actions(request)
if actions:
list_display = (['action_checkbox'] + list(list_display))
ChangeList = self.get_changelist(request)
try:
cl = ChangeList(request, self.model, list_display, list_display_links, list_filter, self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self.list_max_show_all, self.list_editable, self)
except IncorrectLookupParameters:
if (ERROR_FLAG in request.GET.keys()):
return SimpleTemplateResponse('admin/invalid_setup.html', {'title': _('Database error')})
return HttpResponseRedirect((((request.path + '?') + ERROR_FLAG) + '=1'))
action_failed = False
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
if (actions and (request.method == 'POST') and ('index' in request.POST) and ('_save' not in request.POST)):
if selected:
response = self.response_action(request, queryset=cl.get_query_set(request))
if response:
return response
else:
action_failed = True
else:
msg = _('Items must be selected in order to perform actions on them. No items have been changed.')
self.message_user(request, msg)
action_failed = True
if (actions and (request.method == 'POST') and (helpers.ACTION_CHECKBOX_NAME in request.POST) and ('index' not in request.POST) and ('_save' not in request.POST)):
if selected:
response = self.response_action(request, queryset=cl.get_query_set(request))
if response:
return response
else:
action_failed = True
formset = cl.formset = None
if ((request.method == 'POST') and cl.list_editable and ('_save' in request.POST) and (not action_failed)):
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list)
if formset.is_valid():
changecount = 0
for form in formset.forms:
if form.has_changed():
obj = self.save_form(request, form, change=True)
self.save_model(request, obj, form, change=True)
self.save_related(request, form, formsets=[], change=True)
change_msg = self.construct_change_message(request, form, None)
self.log_change(request, obj, change_msg)
changecount += 1
if changecount:
if (changecount == 1):
name = force_text(opts.verbose_name)
else:
name = force_text(opts.verbose_name_plural)
msg = (ungettext('%(count)s %(name)s was changed successfully.', '%(count)s %(name)s were changed successfully.', changecount) % {'count': changecount, 'name': name, 'obj': force_text(obj)})
self.message_user(request, msg)
return HttpResponseRedirect(request.get_full_path())
elif cl.list_editable:
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(queryset=cl.result_list)
if formset:
media = (self.media + formset.media)
else:
media = self.media
if actions:
action_form = self.action_form(auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
else:
action_form = None
selection_note_all = ungettext('%(total_count)s selected', 'All %(total_count)s selected', cl.result_count)
context = {'module_name': force_text(opts.verbose_name_plural), 'selection_note': (_('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)}), 'selection_note_all': (selection_note_all % {'total_count': cl.result_count}), 'title': cl.title, 'is_popup': cl.is_popup, 'cl': cl, 'media': media, 'has_add_permission': self.has_add_permission(request), 'app_label': app_label, 'action_form': action_form, 'actions_on_top': self.actions_on_top, 'actions_on_bottom': self.actions_on_bottom, 'actions_selection_counter': self.actions_selection_counter}
context.update((extra_context or {}))
return TemplateResponse(request, (self.change_list_template or [('admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower())), ('admin/%s/change_list.html' % app_label), 'admin/change_list.html']), context, current_app=self.admin_site.name)
|
'The \'delete\' admin view for this model.'
| @csrf_protect_m
@transaction.commit_on_success
def delete_view(self, request, object_id, extra_context=None):
| opts = self.model._meta
app_label = opts.app_label
obj = self.get_object(request, unquote(object_id))
if (not self.has_delete_permission(request, obj)):
raise PermissionDenied
if (obj is None):
raise Http404((_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)}))
using = router.db_for_write(self.model)
(deleted_objects, perms_needed, protected) = get_deleted_objects([obj], opts, request.user, self.admin_site, using)
if request.POST:
if perms_needed:
raise PermissionDenied
obj_display = force_text(obj)
self.log_deletion(request, obj, obj_display)
self.delete_model(request, obj)
self.message_user(request, (_('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_text(opts.verbose_name), 'obj': force_text(obj_display)}))
if (not self.has_change_permission(request, None)):
return HttpResponseRedirect(reverse('admin:index', current_app=self.admin_site.name))
return HttpResponseRedirect(reverse(('admin:%s_%s_changelist' % (opts.app_label, opts.module_name)), current_app=self.admin_site.name))
object_name = force_text(opts.verbose_name)
if (perms_needed or protected):
title = (_('Cannot delete %(name)s') % {'name': object_name})
else:
title = _('Are you sure?')
context = {'title': title, 'object_name': object_name, 'object': obj, 'deleted_objects': deleted_objects, 'perms_lacking': perms_needed, 'protected': protected, 'opts': opts, 'app_label': app_label}
context.update((extra_context or {}))
return TemplateResponse(request, (self.delete_confirmation_template or [('admin/%s/%s/delete_confirmation.html' % (app_label, opts.object_name.lower())), ('admin/%s/delete_confirmation.html' % app_label), 'admin/delete_confirmation.html']), context, current_app=self.admin_site.name)
|
'The \'history\' admin view for this model.'
| def history_view(self, request, object_id, extra_context=None):
| from django.contrib.admin.models import LogEntry
model = self.model
obj = get_object_or_404(model, pk=unquote(object_id))
if (not self.has_change_permission(request, obj)):
raise PermissionDenied
opts = model._meta
app_label = opts.app_label
action_list = LogEntry.objects.filter(object_id=unquote(object_id), content_type__id__exact=ContentType.objects.get_for_model(model).id).select_related().order_by('action_time')
context = {'title': (_('Change history: %s') % force_text(obj)), 'action_list': action_list, 'module_name': capfirst(force_text(opts.verbose_name_plural)), 'object': obj, 'app_label': app_label, 'opts': opts}
context.update((extra_context or {}))
return TemplateResponse(request, (self.object_history_template or [('admin/%s/%s/object_history.html' % (app_label, opts.object_name.lower())), ('admin/%s/object_history.html' % app_label), 'admin/object_history.html']), context, current_app=self.admin_site.name)
|
'Returns a BaseInlineFormSet class for use in admin add/change views.'
| def get_formset(self, request, obj=None, **kwargs):
| if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if (self.exclude is None):
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
if ((self.exclude is None) and hasattr(self.form, '_meta') and self.form._meta.exclude):
exclude.extend(self.form._meta.exclude)
exclude = (exclude or None)
can_delete = (self.can_delete and self.has_delete_permission(request, obj))
defaults = {'form': self.form, 'formset': self.formset, 'fk_name': self.fk_name, 'fields': fields, 'exclude': exclude, 'formfield_callback': partial(self.formfield_for_dbfield, request=request), 'extra': self.extra, 'max_num': self.max_num, 'can_delete': can_delete}
defaults.update(kwargs)
return inlineformset_factory(self.parent_model, self.model, **defaults)
|
'Returns True if some choices would be output for this filter.'
| def has_output(self):
| raise NotImplementedError
|
'Returns choices ready to be output in the template.'
| def choices(self, cl):
| raise NotImplementedError
|
'Returns the filtered queryset.'
| def queryset(self, request, queryset):
| raise NotImplementedError
|
'Returns the list of parameter names that are expected from the
request\'s query string and that will be used by this filter.'
| def expected_parameters(self):
| raise NotImplementedError
|
'Returns the value (in string format) provided in the request\'s
query string for this filter, if any. If the value wasn\'t provided then
returns None.'
| def value(self):
| return self.used_parameters.get(self.parameter_name, None)
|
'Must be overriden to return a list of tuples (value, verbose value)'
| def lookups(self, request, model_admin):
| raise NotImplementedError
|
'Validates the input and returns a string that contains only numbers.
Returns an empty string for empty values.'
| def clean(self, value):
| v = super(CZPostalCodeField, self).clean(value)
return v.replace(u' ', u'')
|
'Validates the input and returns a string that contains only numbers.
Returns an empty string for empty values.'
| def clean(self, value):
| v = super(SKPostalCodeField, self).clean(value)
return v.replace(u' ', u'')
|
'Value can be a string either in the [X]X.XXX.XXX or [X]XXXXXXX formats.'
| def clean(self, value):
| value = super(ARDNIField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
if (not value.isdigit()):
value = value.replace(u'.', u'')
if (not value.isdigit()):
raise ValidationError(self.error_messages[u'invalid'])
if (len(value) not in (7, 8)):
raise ValidationError(self.error_messages[u'max_digits'])
return value
|
'Value can be either a string in the format XX-XXXXXXXX-X or an
11-digit number.'
| def clean(self, value):
| value = super(ARCUITField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
(value, cd) = self._canon(value)
if (not (value[:2] in [u'27', u'20', u'23', u'30'])):
raise ValidationError(self.error_messages[u'legal_type'])
if (self._calc_cd(value) != cd):
raise ValidationError(self.error_messages[u'checksum'])
return self._format(value, cd)
|
'Validates the input and returns a string that contains only numbers.
Returns an empty string for empty values.'
| def clean(self, value):
| v = super(JPPostalCodeField, self).clean(value)
return v.replace('-', '')
|
'Validate a phone number.'
| def clean(self, value):
| super(CAPhoneNumberField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
value = re.sub(u'(\\(|\\)|\\s+)', u'', smart_text(value))
m = phone_digits_re.search(value)
if m:
return (u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)))
raise ValidationError(self.error_messages[u'invalid'])
|
'Checks to make sure that the SIN passes a luhn mod-10 checksum
See: http://en.wikipedia.org/wiki/Luhn_algorithm'
| def luhn_checksum_is_valid(self, number):
| sum = 0
num_digits = len(number)
oddeven = (num_digits & 1)
for count in range(0, num_digits):
digit = int(number[count])
if (not ((count & 1) ^ oddeven)):
digit = (digit * 2)
if (digit > 9):
digit = (digit - 9)
sum = (sum + digit)
return ((sum % 10) == 0)
|
'Value must be a string in the XXXXXXXX formats.'
| def clean(self, value):
| value = super(PEDNIField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
if (not value.isdigit()):
raise ValidationError(self.error_messages[u'invalid'])
if (len(value) != 8):
raise ValidationError(self.error_messages[u'max_digits'])
return value
|
'Value must be an 11-digit number.'
| def clean(self, value):
| value = super(PERUCField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
if (not value.isdigit()):
raise ValidationError(self.error_messages[u'invalid'])
if (len(value) != 11):
raise ValidationError(self.error_messages[u'max_digits'])
return value
|
'Value can be either a string in the format XXX.XXX.XXX-XX or an
11-digit number.'
| def clean(self, value):
| value = super(BRCPFField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
orig_value = value[:]
if (not value.isdigit()):
value = re.sub(u'[-\\.]', u'', value)
try:
int(value)
except ValueError:
raise ValidationError(self.error_messages[u'digits_only'])
if (len(value) != 11):
raise ValidationError(self.error_messages[u'max_digits'])
orig_dv = value[(-2):]
new_1dv = sum([(i * int(value[idx])) for (idx, i) in enumerate(range(10, 1, (-1)))])
new_1dv = DV_maker((new_1dv % 11))
value = ((value[:(-2)] + str(new_1dv)) + value[(-1)])
new_2dv = sum([(i * int(value[idx])) for (idx, i) in enumerate(range(11, 1, (-1)))])
new_2dv = DV_maker((new_2dv % 11))
value = (value[:(-1)] + str(new_2dv))
if (value[(-2):] != orig_dv):
raise ValidationError(self.error_messages[u'invalid'])
return orig_value
|
'Value can be either a string in the format XX.XXX.XXX/XXXX-XX or a
group of 14 characters.'
| def clean(self, value):
| value = super(BRCNPJField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
orig_value = value[:]
if (not value.isdigit()):
value = re.sub(u'[-/\\.]', u'', value)
try:
int(value)
except ValueError:
raise ValidationError(self.error_messages[u'digits_only'])
if (len(value) != 14):
raise ValidationError(self.error_messages[u'max_digits'])
orig_dv = value[(-2):]
new_1dv = sum([(i * int(value[idx])) for (idx, i) in enumerate((list(range(5, 1, (-1))) + list(range(9, 1, (-1)))))])
new_1dv = DV_maker((new_1dv % 11))
value = ((value[:(-2)] + str(new_1dv)) + value[(-1)])
new_2dv = sum([(i * int(value[idx])) for (idx, i) in enumerate((list(range(6, 1, (-1))) + list(range(9, 1, (-1)))))])
new_2dv = DV_maker((new_2dv % 11))
value = (value[:(-1)] + str(new_2dv))
if (value[(-2):] != orig_dv):
raise ValidationError(self.error_messages[u'invalid'])
return orig_value
|
'CIF validation'
| def clean(self, value):
| value = super(ROCIFField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
if (value[0:2] == u'RO'):
value = value[2:]
key = u'753217532'[::(-1)]
value = value[::(-1)]
key_iter = iter(key)
checksum = 0
for digit in value[1:]:
checksum += (int(digit) * int(next(key_iter)))
checksum = ((checksum * 10) % 11)
if (checksum == 10):
checksum = 0
if (checksum != int(value[0])):
raise ValidationError(self.error_messages[u'invalid'])
return value[::(-1)]
|
'CNP validations'
| def clean(self, value):
| value = super(ROCNPField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
try:
datetime.date(int(value[1:3]), int(value[3:5]), int(value[5:7]))
except ValueError:
raise ValidationError(self.error_messages[u'invalid'])
key = u'279146358279'
checksum = 0
value_iter = iter(value)
for digit in key:
checksum += (int(digit) * int(next(value_iter)))
checksum %= 11
if (checksum == 10):
checksum = 1
if (checksum != int(value[12])):
raise ValidationError(self.error_messages[u'invalid'])
return value
|
'Strips - and spaces, performs country code and checksum validation'
| def clean(self, value):
| value = super(ROIBANField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
value = value.replace(u'-', u'')
value = value.replace(u' ', u'')
value = value.upper()
if (value[0:2] != u'RO'):
raise ValidationError(self.error_messages[u'invalid'])
numeric_format = u''
for char in (value[4:] + value[0:4]):
if char.isalpha():
numeric_format += str((ord(char) - 55))
else:
numeric_format += char
if ((int(numeric_format) % 97) != 1):
raise ValidationError(self.error_messages[u'invalid'])
return value
|
'Strips -, (, ) and spaces. Checks the final length.'
| def clean(self, value):
| value = super(ROPhoneNumberField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
value = value.replace(u'-', u'')
value = value.replace(u'(', u'')
value = value.replace(u')', u'')
value = value.replace(u' ', u'')
if (len(value) != 10):
raise ValidationError(self.error_messages[u'invalid'])
return value
|
'Validates format and validation digit.
The official format is [X.]XXX.XXX-X but usually dots and/or slash are
omitted so, when validating, those characters are ignored if found in
the correct place. The three typically used formats are supported:
[X]XXXXXXX, [X]XXXXXX-X and [X.]XXX.XXX-X.'
| def clean(self, value):
| value = super(UYCIField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
match = self.regex.match(value)
if (not match):
raise ValidationError(self.error_messages[u'invalid'])
number = int(match.group(u'num').replace(u'.', u''))
validation_digit = int(match.group(u'val'))
if (not (validation_digit == get_validation_digit(number))):
raise ValidationError(self.error_messages[u'invalid_validation_digit'])
return value
|
'Returns the value as only digits.'
| def _canonify(self, value):
| return value.replace(u'-', u'').replace(u' ', u'')
|
'Takes in the value in canonical form and checks the verifier digit. The
method is modulo 11.'
| def _validate(self, value):
| check = [3, 2, 7, 6, 5, 4, 3, 2, 1, 0]
return ((sum([(int(value[i]) * check[i]) for i in range(10)]) % 11) == 0)
|
'Takes in the value in canonical form and returns it in the common
display format.'
| def _format(self, value):
| return smart_text(((value[:6] + u'-') + value[6:]))
|
'This check is done due to the existance of RFCs without a *homoclave*
since the current algorithm to calculate it had not been created for
the first RFCs ever in Mexico.'
| def _has_homoclave(self, rfc):
| rfc_without_homoclave_re = re.compile((u'^[A-Z&\xd1\xf1]{3,4}%s$' % DATE_RE), re.IGNORECASE)
return (not rfc_without_homoclave_re.match(rfc))
|
'More info about this procedure:
www.sisi.org.mx/jspsi/documentos/2005/seguimiento/06101/0610100162005_065.doc'
| def _checksum(self, rfc):
| chars = u'0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ-\xd1'
if (len(rfc) == 11):
rfc = (u'-' + rfc)
sum_ = sum(((i * chars.index(c)) for (i, c) in zip(reversed(range(14)), rfc)))
checksum = (11 - (sum_ % 11))
if (checksum == 10):
return u'A'
elif (checksum == 11):
return u'0'
return six.text_type(checksum)
|
'Check and clean the Chilean RUT.'
| def clean(self, value):
| super(CLRutField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
(rut, verificador) = self._canonify(value)
if (self._algorithm(rut) == verificador):
return self._format(rut, verificador)
else:
raise ValidationError(self.error_messages[u'checksum'])
|
'Takes RUT in pure canonical form, calculates the verifier digit.'
| def _algorithm(self, rut):
| suma = 0
multi = 2
for r in rut[::(-1)]:
suma += (int(r) * multi)
multi += 1
if (multi == 8):
multi = 2
return u'0123456789K0'[(11 - (suma % 11))]
|
'Turns the RUT into one normalized format. Returns a (rut, verifier)
tuple.'
| def _canonify(self, rut):
| rut = smart_text(rut).replace(u' ', u'').replace(u'.', u'').replace(u'-', u'')
return (rut[:(-1)], rut[(-1)].upper())
|
'Formats the RUT from canonical form to the common string representation.
If verifier=None, then the last digit in \'code\' is the verifier.'
| def _format(self, code, verifier=None):
| if (verifier is None):
verifier = code[(-1)]
code = code[:(-1)]
while ((len(code) > 3) and (u'.' not in code[:3])):
pos = code.find(u'.')
if (pos == (-1)):
new_dot = (-3)
else:
new_dot = (pos - 3)
code = ((code[:new_dot] + u'.') + code[new_dot:])
return (u'%s-%s' % (code, verifier))
|
'Calculates a checksum with the provided algorithm.'
| def has_valid_checksum(self, number):
| multiple_table = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1)
result = 0
for i in range(len(number)):
result += (int(number[i]) * multiple_table[i])
return ((result % 10) == 0)
|
'Calculates a checksum with the provided algorithm.'
| def has_valid_checksum(self, number):
| letter_dict = {u'A': 10, u'B': 11, u'C': 12, u'D': 13, u'E': 14, u'F': 15, u'G': 16, u'H': 17, u'I': 18, u'J': 19, u'K': 20, u'L': 21, u'M': 22, u'N': 23, u'O': 24, u'P': 25, u'Q': 26, u'R': 27, u'S': 28, u'T': 29, u'U': 30, u'V': 31, u'W': 32, u'X': 33, u'Y': 34, u'Z': 35}
int_table = [(((not c.isdigit()) and letter_dict[c]) or int(c)) for c in number]
multiple_table = (7, 3, 1, (-1), 7, 3, 1, 7, 3)
result = 0
for i in range(len(int_table)):
result += (int_table[i] * multiple_table[i])
return ((result % 10) == 0)
|
'Calculates a checksum with the provided algorithm.'
| def has_valid_checksum(self, number):
| multiple_table = (6, 5, 7, 2, 3, 4, 5, 6, 7)
result = 0
for i in range((len(number) - 1)):
result += (int(number[i]) * multiple_table[i])
result %= 11
if (result == int(number[(-1)])):
return True
else:
return False
|
'Calculates a checksum with the provided algorithm.'
| def has_valid_checksum(self, number):
| weights = ((8, 9, 2, 3, 4, 5, 6, 7, (-1)), (2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8, (-1)), (8, 9, 2, 3, 4, 5, 6, 7, (-1), 0, 0, 0, 0, 0))
weights = [table for table in weights if (len(table) == len(number))]
for table in weights:
checksum = sum([(int(n) * w) for (n, w) in zip(number, table)])
if ((checksum % 11) % 10):
return False
return bool(weights)
|
'Validate a phone number. Strips parentheses, whitespace and hyphens.'
| def clean(self, value):
| super(AUPhoneNumberField, self).clean(value)
if (value in EMPTY_VALUES):
return u''
value = re.sub(u'(\\(|\\)|\\s+|-)', u'', smart_text(value))
phone_match = PHONE_DIGITS_RE.search(value)
if phone_match:
return (u'%s' % phone_match.group(1))
raise ValidationError(self.error_messages[u'invalid'])
|
'Check whether the input is a valid ID Card Number.'
| def clean(self, value):
| super(CNIDCardField, self).clean(value)
if (not value):
return u''
if (not re.match(ID_CARD_RE, value)):
raise ValidationError(self.error_messages[u'invalid'])
if (not self.has_valid_birthday(value)):
raise ValidationError(self.error_messages[u'birthday'])
if (not self.has_valid_location(value)):
raise ValidationError(self.error_messages[u'location'])
value = value.upper()
if (not self.has_valid_checksum(value)):
raise ValidationError(self.error_messages[u'checksum'])
return (u'%s' % value)
|
'This function would grab the birthdate from the ID card number and test
whether it is a valid date.'
| def has_valid_birthday(self, value):
| from datetime import datetime
if (len(value) == 15):
time_string = value[6:12]
format_string = u'%y%m%d'
else:
time_string = value[6:14]
format_string = u'%Y%m%d'
try:
datetime.strptime(time_string, format_string)
return True
except ValueError:
return False
|
'This method checks if the first two digits in the ID Card are valid.'
| def has_valid_location(self, value):
| return (int(value[:2]) in CN_LOCATION_CODES)
|
'This method checks if the last letter/digit in value is valid
according to the algorithm the ID Card follows.'
| def has_valid_checksum(self, value):
| if (len(value) != 18):
return True
checksum_index = (sum(map((lambda a, b: (a * (ord(b) - ord(u'0')))), (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2), value[:17])) % 11)
return (u'10X98765432'[checksum_index] == value[(-1)])
|
'A secure sitemap index can be rendered'
| def test_secure_sitemap_index(self):
| response = self.client.get(u'/secure/index.xml')
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<sitemap><loc>%s/secure/sitemap-simple.xml</loc></sitemap>\n</sitemapindex>\n' % self.base_url)
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'A secure sitemap section can be rendered'
| def test_secure_sitemap_section(self):
| response = self.client.get(u'/secure/sitemap-simple.xml')
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>\n</urlset>\n' % (self.base_url, date.today()))
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'A sitemap index requested in HTTPS is rendered with HTTPS links'
| def test_sitemap_index_with_https_request(self):
| response = self.client.get(u'/simple/index.xml', **self.extra)
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>\n</sitemapindex>\n' % self.base_url.replace(u'http://', u'https://'))
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'A sitemap section requested in HTTPS is rendered with HTTPS links'
| def test_sitemap_section_with_https_request(self):
| response = self.client.get(u'/simple/sitemap-simple.xml', **self.extra)
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>\n</urlset>\n' % (self.base_url.replace(u'http://', u'https://'), date.today()))
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'Basic FlatPage sitemap test'
| @skipUnless((u'django.contrib.flatpages' in settings.INSTALLED_APPS), u'django.contrib.flatpages app not installed.')
def test_flatpage_sitemap(self):
| from django.contrib.flatpages.models import FlatPage
public = FlatPage.objects.create(url=u'/public/', title=u'Public Page', enable_comments=True, registration_required=False)
public.sites.add(settings.SITE_ID)
private = FlatPage.objects.create(url=u'/private/', title=u'Private Page', enable_comments=True, registration_required=True)
private.sites.add(settings.SITE_ID)
response = self.client.get(u'/flatpages/sitemap.xml')
self.assertContains(response, (u'<loc>%s%s</loc>' % (self.base_url, public.url)))
self.assertNotContains(response, (u'<loc>%s%s</loc>' % (self.base_url, private.url)))
|
'A minimal generic sitemap can be rendered'
| def test_generic_sitemap(self):
| response = self.client.get(u'/generic/sitemap.xml')
expected = u''
for username in User.objects.values_list(u'username', flat=True):
expected += (u'<url><loc>%s/users/%s/</loc></url>' % (self.base_url, username))
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n%s\n</urlset>\n' % expected)
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'A simple sitemap index can be rendered'
| def test_simple_sitemap_index(self):
| response = self.client.get(u'/simple/index.xml')
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>\n</sitemapindex>\n' % self.base_url)
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'A simple sitemap index can be rendered with a custom template'
| @override_settings(TEMPLATE_DIRS=(os.path.join(os.path.dirname(upath(__file__)), u'templates'),))
def test_simple_sitemap_custom_index(self):
| response = self.client.get(u'/simple/custom-index.xml')
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<!-- This is a customised template -->\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>\n</sitemapindex>\n' % self.base_url)
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'A simple sitemap section can be rendered'
| def test_simple_sitemap_section(self):
| response = self.client.get(u'/simple/sitemap-simple.xml')
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>\n</urlset>\n' % (self.base_url, date.today()))
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'A simple sitemap can be rendered'
| def test_simple_sitemap(self):
| response = self.client.get(u'/simple/sitemap.xml')
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>\n</urlset>\n' % (self.base_url, date.today()))
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'A simple sitemap can be rendered with a custom template'
| @override_settings(TEMPLATE_DIRS=(os.path.join(os.path.dirname(upath(__file__)), u'templates'),))
def test_simple_custom_sitemap(self):
| response = self.client.get(u'/simple/custom-sitemap.xml')
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<!-- This is a customised template -->\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>\n</urlset>\n' % (self.base_url, date.today()))
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'The priority value should not be localized (Refs #14164)'
| @skipUnless(settings.USE_I18N, u'Internationalization is not enabled')
@override_settings(USE_L10N=True)
def test_localized_priority(self):
| activate(u'fr')
self.assertEqual(u'0,3', localize(0.3))
response = self.client.get(u'/simple/sitemap.xml')
self.assertContains(response, u'<priority>0.5</priority>')
self.assertContains(response, (u'<lastmod>%s</lastmod>' % date.today()))
deactivate()
|
'Check we get ImproperlyConfigured if we don\'t pass a site object to
Sitemap.get_urls and no Site objects exist'
| @skipUnless((u'django.contrib.sites' in settings.INSTALLED_APPS), u'django.contrib.sites app not installed.')
def test_sitemap_get_urls_no_site_1(self):
| Site.objects.all().delete()
self.assertRaises(ImproperlyConfigured, Sitemap().get_urls)
|
'Check we get ImproperlyConfigured when we don\'t pass a site object to
Sitemap.get_urls if Site objects exists, but the sites framework is not
actually installed.'
| def test_sitemap_get_urls_no_site_2(self):
| Site._meta.installed = False
self.assertRaises(ImproperlyConfigured, Sitemap().get_urls)
|
'Check to make sure that the raw item is included with each
Sitemap.get_url() url result.'
| def test_sitemap_item(self):
| user_sitemap = GenericSitemap({u'queryset': User.objects.all()})
def is_user(url):
return isinstance(url[u'item'], User)
item_in_url_info = all(map(is_user, user_sitemap.get_urls()))
self.assertTrue(item_in_url_info)
|
'Check that a cached sitemap index can be rendered (#2713).'
| def test_cached_sitemap_index(self):
| response = self.client.get(u'/cached/index.xml')
expected_content = (u'<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<sitemap><loc>%s/cached/sitemap-simple.xml</loc></sitemap>\n</sitemapindex>\n' % self.base_url)
self.assertXMLEqual(response.content.decode(u'utf-8'), expected_content)
|
'Saves the current session data to the database. If \'must_create\' is
True, a database error will be raised if the saving operation doesn\'t
create a *new* entry (as opposed to possibly updating an existing
entry).'
| def save(self, must_create=False):
| obj = Session(session_key=self._get_or_create_session_key(), session_data=self.encode(self._get_session(no_load=must_create)), expire_date=self.get_expiry_date())
using = router.db_for_write(Session, instance=obj)
sid = transaction.savepoint(using=using)
try:
obj.save(force_insert=must_create, using=using)
except IntegrityError:
if must_create:
transaction.savepoint_rollback(sid, using=using)
raise CreateError
raise
|
'We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_session_key(),
raises BadSignature if signature fails.'
| def load(self):
| try:
return signing.loads(self.session_key, serializer=PickleSerializer, max_age=settings.SESSION_COOKIE_AGE, salt='django.contrib.sessions.backends.signed_cookies')
except (signing.BadSignature, ValueError):
self.create()
return {}
|
'To create a new key, we simply make sure that the modified flag is set
so that the cookie is set on the client for the current request.'
| def create(self):
| self.modified = True
|
'To save, we get the session key as a securely signed string and then
set the modified flag so that the cookie is set on the client for the
current request.'
| def save(self, must_create=False):
| self._session_key = self._get_session_key()
self.modified = True
|
'This method makes sense when you\'re talking to a shared resource, but
it doesn\'t matter when you\'re storing the information in the client\'s
cookie.'
| def exists(self, session_key=None):
| return False
|
'To delete, we clear the session key and the underlying data structure
and set the modified flag so that the cookie is set on the client for
the current request.'
| def delete(self, session_key=None):
| self._session_key = ''
self._session_cache = {}
self.modified = True
|
'Keeps the same data but with a new key. To do this, we just have to
call ``save()`` and it will automatically save a cookie with a new key
at the end of the request.'
| def cycle_key(self):
| self.save()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.