desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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.get_ordering(request) 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(self.get_readonly_fields(request, obj)) if ((self.exclude is None) and has...
'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_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...
'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]
'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()
'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='../%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 module_name = opts.module_name if obj._deferred: opts_ = opts.proxy_for_model._meta verbose_name = opts_.verbose_name module_name = opts_.module_name pk_value = obj._get_pk_val() msg = (_('The %(name)s "%(obj)s" w...
'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 = [] inline_instances = self.get_inline_instances(request) if (request.method == 'POST'): form = ModelForm(request.POST, request...
'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.') % ...
'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, lis...
'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(self.get_readonly_fields(request, obj)) if ((self.exclude is None) and has...
'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(' ', '')
'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:]))
'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 = ('-' + rfc) sum_ = sum(((i * chars.index(c)) for (i, c) in zip(reversed(xrange(14)), rfc))) checksum = (11 - (sum_ % 11)) if (checksum == 10): return u'A' elif (checksum == 11): return u'0' ...
'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):
letter_dict = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, 'G': 16, 'H': 17, 'I': 18, 'J': 19, 'K': 20, 'L': 21, 'M': 22, 'N': 23, 'O': 24, 'P': 25, 'Q': 26, 'R': 27, 'S': 28, 'T': 29, 'U': 30, 'V': 31, 'W': 32, 'X': 33, 'Y': 34, 'Z': 35} int_table = [(((not c.isdigit()) and letter_dict[c]) or int(c))...
'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...
'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['invalid']) if (not self.has_valid_birthday(value)): raise ValidationError(self.error_messages['birthday']) if (not self.has_vali...
'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 = '%y%m%d' else: time_string = value[6:14] format_string = '%Y%m%d' try: datetime.strptime(time_string, format_string) return True except ValueError: r...
'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('0')))), (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2), value[:17])) % 11) return ('10X98765432'[checksum_index] == value[(-1)])
'A secure sitemap index can be rendered'
def test_secure_sitemap_index(self):
response = self.client.get('/secure/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/secure/sitemap-simple.xml</loc></sitemap>\n</sitemapindex>\n' % self.base_url))
'A secure sitemap section can be rendered'
def test_secure_sitemap_section(self):
response = self.client.get('/secure/sitemap-simple.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></ur...
'A sitemap index requested in HTTPS is rendered with HTTPS links'
def test_sitemap_index_with_https_request(self):
response = self.client.get('/simple/index.xml', **self.extra) 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.r...
'A sitemap section requested in HTTPS is rendered with HTTPS links'
def test_sitemap_section_with_https_request(self):
response = self.client.get('/simple/sitemap-simple.xml', **self.extra) 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<...
'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...
'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...
'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 section can be rendered'
def test_simple_sitemap_section(self):
response = self.client.get('/simple/sitemap-simple.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></ur...
'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())) deactivate()
'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)
'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({'queryset': User.objects.all()}) def is_user(url): return isinstance(url['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('/cached/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/cached/sitemap-simple.xml</loc></sitemap>\n</sitemapindex>\n' % self.base_url))
'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, u...
'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()
'Most session backends don\'t need to override this method, but we do, because instead of generating a random string, we want to actually generate a secure url-safe Base64-encoded string of data as our session key.'
def _get_session_key(self):
session_cache = getattr(self, '_session_cache', {}) return signing.dumps(session_cache, compress=True, salt='django.contrib.sessions.backends.signed_cookies', serializer=PickleSerializer)