desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Displays the login form for the given HttpRequest.'
@never_cache def login(self, request, extra_context=None):
from django.contrib.auth.views import login context = {'title': _('Log in'), 'root_path': self.root_path, 'app_path': request.get_full_path(), REDIRECT_FIELD_NAME: request.get_full_path()} context.update((extra_context or {})) defaults = {'extra_context': context, 'current_app': self.name, 'authentic...
'Displays the main admin index page, which lists all of the installed apps that have been registered in this site.'
@never_cache def index(self, request, extra_context=None):
app_dict = {} user = request.user for (model, model_admin) in self._registry.items(): app_label = model._meta.app_label has_module_perms = user.has_module_perms(app_label) if has_module_perms: perms = model_admin.get_model_perms(request) if (True in perms.valu...
'Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they\'re passed to the form Field\'s constructor.'
def formfield_for_dbfield(self, db_field, **kwargs):
request = kwargs.pop('request', None) if db_field.choices: return self.formfield_for_choice_field(db_field, request, **kwargs) if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)): if (db_field.__class__ in self.formfield_overrides): kwargs = dict(self.formfield_o...
'Get a form Field for a database Field that has declared choices.'
def formfield_for_choice_field(self, db_field, request=None, **kwargs):
if (db_field.name in self.radio_fields): if ('widget' not in kwargs): kwargs['widget'] = widgets.AdminRadioSelect(attrs={'class': get_ul_class(self.radio_fields[db_field.name])}) if ('choices' not in kwargs): kwargs['choices'] = db_field.get_choices(include_blank=db_field.bla...
'Get a form Field for a ForeignKey.'
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
db = kwargs.get('using') if (db_field.name in self.raw_id_fields): kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel, using=db) elif (db_field.name in self.radio_fields): kwargs['widget'] = widgets.AdminRadioSelect(attrs={'class': get_ul_class(self.radio_fields[db_field.name])}) ...
'Get a form Field for a ManyToManyField.'
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if (not db_field.rel.through._meta.auto_created): return None db = kwargs.get('using') if (db_field.name in self.raw_id_fields): kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db) kwargs['help_text'] = '' elif (db_field.name in (list(self.filter_vertical) + ...
'Returns a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view.'
def queryset(self, request):
qs = self.model._default_manager.get_query_set() ordering = (self.ordering or ()) if ordering: qs = qs.order_by(*ordering) return qs
'Returns True if the given request has permission to add an object. Can be overriden by the user in subclasses.'
def has_add_permission(self, request):
opts = self.opts return request.user.has_perm(((opts.app_label + '.') + opts.get_add_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 change the `obj` model instance. If `obj` is...
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...
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 = (form.base_fields.keys() + 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(kwargs.get('exclude', [])) exclude.extend(self.get_readonly_fields(request...
'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': curry(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': curry(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_unicode(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_unicode(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.id, 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_unicode(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...
'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 self.get_actions(request).itervalues(): 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, 'sho...
'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 "%(obj...
'Send a message to the user. The default implementation posts a message using the django.contrib.messages backend.'
def message_user(self, request, message):
messages.info(request, message)
'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()
'Determines the HttpResponse for the add_view stage.'
def response_add(self, request, obj, post_url_continue='../%s/'):
opts = obj._meta pk_value = obj._get_pk_val() msg = (_('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}) if ('_continue' in request.POST): self.message_user(request, ((msg + ' ') + _('You may edit ...
'Determines the HttpResponse for the change_view stage.'
def response_change(self, request, obj):
opts = obj._meta verbose_name = opts.verbose_name if obj._deferred: opts_ = opts.proxy_for_model._meta verbose_name = opts_.verbose_name pk_value = obj._get_pk_val() msg = (_('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(verbose_name), 'o...
'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 IndexErr...
'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 = [] if (request.method == 'POST'): form = ModelForm(request.POST, request.FILES) if form.is_valid(): new_object...
'The \'change\' admin view for this model.'
@csrf_protect_m @transaction.commit_on_success def change_view(self, request, object_id, 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.') % ...
'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 actions = self.get_actions(request) list_display = list(self.list_display) if (not actions): tr...
'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 ...
'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 opts = model._meta app_label = opts.app_label action_list = LogEntry.objects.filter(object_id=object_id, content_type__id__exact=ContentType.objects.get_for_model(model).id).select_related().order_by('action_time') obj = get_obj...
'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(kwargs.get('exclude', [])) exclude.extend(self.get_readonly_fields(request...
'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(' ', '')
'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(' ', '')
'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('.', '') if (not value.isdigit()): raise ValidationError(self.error_messages['invalid']) if (len(value) not in (7, 8)): raise Validation...
'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 (self._calc_cd(value) != cd): raise ValidationError(self.error_messages['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('(\\(|\\)|\\s+)', '', smart_unicode(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_mess...
'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...
'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['invalid']) if (len(value) != 8): raise ValidationError(self.error_messages['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['invalid']) if (len(value) != 11): raise ValidationError(self.error_messages['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('[-\\.]', '', value) try: int(value) except ValueError: raise ValidationError(self.error_messages['digits_only']) ...
'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('[-/\\.]', '', value) try: int(value) except ValueError: raise ValidationError(self.error_messages['digits_only']) ...
'CIF validation'
def clean(self, value):
value = super(ROCIFField, self).clean(value) if (value in EMPTY_VALUES): return u'' if (value[0:2] == 'RO'): value = value[2:] key = '753217532'[::(-1)] value = value[::(-1)] key_iter = iter(key) checksum = 0 for digit in value[1:]: checksum += (int(digit) * int(k...
'CNP validations'
def clean(self, value):
value = super(ROCNPField, self).clean(value) if (value in EMPTY_VALUES): return u'' import datetime try: datetime.date(int(value[1:3]), int(value[3:5]), int(value[5:7])) except: raise ValidationError(self.error_messages['invalid']) key = '279146358279' checksum = 0 ...
'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('-', '') value = value.replace(' ', '') value = value.upper() if (value[0:2] != 'RO'): raise ValidationError(self.error_messages['invalid']) numeric_format = '' f...
'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('-', '') value = value.replace('(', '') value = value.replace(')', '') value = value.replace(' ', '') if (len(value) != 10): raise ValidationError(self.error_m...
'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['invalid']) number = int(match.group('num').replace('.', '')) validation_digit = int(match.group('val')) ...
'Returns the value as only digits.'
def _canonify(self, value):
return value.replace('-', '').replace(' ', '')
'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_unicode(((value[:6] + '-') + value[6:]))
'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['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_unicode(rut).replace(' ', '').replace('.', '').replace('-', '') 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 ('.' not in code[:3])): pos = code.find('.') if (pos == (-1)): new_dot = (-3) else: new_dot = (pos - 3) code = ((code[:new_dot] + '.') + code[new_dot...
'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):
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)]) ...
'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('(\\(|\\)|\\s+|-)', '', smart_unicode(value)) phone_match = PHONE_DIGITS_RE.search(value) if phone_match: return (u'%s' % phone_match.group(1)) raise ValidationError(self.error_mess...
'A simple sitemap index can be rendered'
def test_simple_sitemap_index(self):
response = self.client.get('/simple/index.xml') self.assertEqual(response.content, ('<?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))
'A simple sitemap index can be rendered with a custom template'
def test_simple_sitemap_custom_index(self):
response = self.client.get('/simple/custom-index.xml') self.assertEqual(response.content, ('<?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</l...
'A simple sitemap can be rendered'
def test_simple_sitemap(self):
response = self.client.get('/simple/sitemap.xml') self.assertEqual(response.content, ('<?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</u...
'A simple sitemap can be rendered with a custom template'
def test_simple_custom_sitemap(self):
response = self.client.get('/simple/custom-sitemap.xml') self.assertEqual(response.content, ('<?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>...
'The priority value should not be localized (Refs #14164)'
@skipUnless(settings.USE_I18N, 'Internationalization is not enabled') def test_localized_priority(self):
settings.USE_L10N = True activate('fr') self.assertEqual(u'0,3', localize(0.3)) response = self.client.get('/simple/sitemap.xml') self.assertContains(response, '<priority>0.5</priority>') self.assertContains(response, ('<lastmod>%s</lastmod>' % date.today().strftime('%Y-%m-%d'))) deactivate(...
'A minimal generic sitemap can be rendered'
def test_generic_sitemap(self):
response = self.client.get('/generic/sitemap.xml') expected = '' for username in User.objects.values_list('username', flat=True): expected += ('<url><loc>%s/users/%s/</loc></url>' % (self.base_url, username)) self.assertEqual(response.content, ('<?xml version="1.0" encoding="UTF-8"?>\n<url...
'Basic FlatPage sitemap test'
@skipUnless(('django.contrib.flatpages' in settings.INSTALLED_APPS), '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_comme...
'Check we get ImproperlyConfigured if we don\'t pass a site object to Sitemap.get_urls and no Site objects exist'
@skipUnless(('django.contrib.sites' in settings.INSTALLED_APPS), '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)
'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.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) e...
'Returns the given session dictionary pickled and encoded as a string.'
def encode(self, session_dict):
pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) hash = self._hash(pickled) return base64.encodestring(((hash + ':') + pickled))
'Returns session key that isn\'t being used.'
def _get_new_session_key(self):
try: pid = os.getpid() except AttributeError: pid = 1 while 1: session_key = md5_constructor(('%s%s%s%s' % (randrange(0, MAX_SESSION_KEY), pid, time.time(), settings.SECRET_KEY))).hexdigest() if (not self.exists(session_key)): break return session_key
'Lazily loads session from storage (unless "no_load" is True, when only an empty dict is stored) and stores it in the current instance.'
def _get_session(self, no_load=False):
self.accessed = True try: return self._session_cache except AttributeError: if ((self._session_key is None) or no_load): self._session_cache = {} else: self._session_cache = self.load() return self._session_cache
'Get the number of seconds until the session expires.'
def get_expiry_age(self):
expiry = self.get('_session_expiry') if (not expiry): return settings.SESSION_COOKIE_AGE if (not isinstance(expiry, datetime)): return expiry delta = (expiry - datetime.now()) return ((delta.days * 86400) + delta.seconds)
'Get session the expiry date (as a datetime object).'
def get_expiry_date(self):
expiry = self.get('_session_expiry') if isinstance(expiry, datetime): return expiry if (not expiry): expiry = settings.SESSION_COOKIE_AGE return (datetime.now() + timedelta(seconds=expiry))
'Sets a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser close. If ``value`` is a ``datetime`` or `...
def set_expiry(self, value):
if (value is None): try: del self['_session_expiry'] except KeyError: pass return if isinstance(value, timedelta): value = (datetime.now() + value) self['_session_expiry'] = value
'Returns ``True`` if the session is set to expire when the browser closes, and ``False`` if there\'s an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one.'
def get_expire_at_browser_close(self):
if (self.get('_session_expiry') is None): return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE return (self.get('_session_expiry') == 0)
'Removes the current session data from the database and regenerates the key.'
def flush(self):
self.clear() self.delete() self.create()
'Creates a new session key, whilst retaining the current session data.'
def cycle_key(self):
data = self._session_cache key = self.session_key self.create() self._session_cache = data self.delete(key)
'Returns True if the given session_key already exists.'
def exists(self, session_key):
raise NotImplementedError
'Creates a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns.'
def create(self):
raise NotImplementedError
'Saves the session data. If \'must_create\' is True, a new session object is created (otherwise a CreateError exception is raised). Otherwise, save() can update an existing object with the same key.'
def save(self, must_create=False):
raise NotImplementedError
'Deletes the session data under this key. If the key is None, the current session key value is used.'
def delete(self, session_key=None):
raise NotImplementedError
'Loads the session data and returns a dictionary.'
def load(self):
raise NotImplementedError
'Get the file associated with this session key.'
def _key_to_file(self, session_key=None):
if (session_key is None): session_key = self.session_key if (not set(session_key).issubset(self.VALID_KEY_CHARS)): raise SuspiciousOperation('Invalid characters in session key') return os.path.join(self.storage_path, (self.file_prefix + session_key))
'Removes the current session data from the database and regenerates the key.'
def flush(self):
self.clear() self.delete(self.session_key) self.create()
'Returns the given session dictionary pickled and encoded as a string.'
def encode(self, session_dict):
return SessionStore().encode(session_dict)
'Test we can use Session.get_decoded to retrieve data stored in normal way'
def test_session_get_decoded(self):
self.session['x'] = 1 self.session.save() s = Session.objects.get(session_key=self.session.session_key) self.assertEqual(s.get_decoded(), {'x': 1})
'Test SessionManager.save method'
def test_sessionmanager_save(self):
self.session['y'] = 1 self.session.save() s = Session.objects.get(session_key=self.session.session_key) Session.objects.save(s.session_key, {'y': 2}, s.expire_date) del self.session._session_cache self.assertEqual(self.session['y'], 2)
'If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie.'
def process_response(self, request, response):
try: accessed = request.session.accessed modified = request.session.modified except AttributeError: pass else: if accessed: patch_vary_headers(response, ('Cookie',)) if (modified or settings.SESSION_SAVE_EVERY_REQUEST): if request.session.get_e...
'Returns the current ``Site`` based on the SITE_ID in the project\'s settings. The ``Site`` object is cached the first time it\'s retrieved from the database.'
def get_current(self):
from django.conf import settings try: sid = settings.SITE_ID except AttributeError: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured('You\'re using the Django "sites framework" without having set the SITE_ID setting. ...
'Clears the ``Site`` object cache.'
def clear_cache(self):
global SITE_CACHE SITE_CACHE = {}
'Regressiontest for #12462'
def test_has_no_object_perm(self):
user = User.objects.get(username='test') content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) user.save() self.assertEqual(user.has_perm('auth.test', 'object'), False) ...
'A superuser has all permissions. Refs #14795'
def test_get_all_superuser_permissions(self):
user = User.objects.get(username='test2') self.assertEqual(len(user.get_all_permissions()), len(Permission.objects.all()))