desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns a dictonary with with the country code and name when given an
IP address or a Fully Qualified Domain Name (FQDN). For example, both
\'24.124.1.80\' and \'djangoproject.com\' are valid parameters.'
| def country(self, query):
| return {'country_code': self.country_code(query), 'country_name': self.country_name(query)}
|
'Returns a tuple of the (longitude, latitude) for the given query.'
| def lon_lat(self, query):
| return self.coords(query)
|
'Returns a tuple of the (latitude, longitude) for the given query.'
| def lat_lon(self, query):
| return self.coords(query, ('latitude', 'longitude'))
|
'Returns a GEOS Point object for the given query.'
| def geos(self, query):
| ll = self.lon_lat(query)
if ll:
from django.contrib.gis.geos import Point
return Point(ll, srid=4326)
else:
return None
|
'Returns information about the GeoIP country database.'
| def country_info(self):
| if (self._country is None):
ci = ('No GeoIP Country data in "%s"' % self._country_file)
else:
ci = geoip_dbinfo(self._country)
return ci
|
'Retuns information about the GeoIP city database.'
| def city_info(self):
| if (self._city is None):
ci = ('No GeoIP City data in "%s"' % self._city_file)
else:
ci = geoip_dbinfo(self._city)
return ci
|
'Returns information about all GeoIP databases in use.'
| def info(self):
| return ('Country:\n DCTB %s\nCity:\n DCTB %s' % (self.country_info, self.city_info))
|
'A LayerMapping object is initialized using the given Model (not an instance),
a DataSource (or string path to an OGR-supported data file), and a mapping
dictionary. See the module level docstring for more details and keyword
argument usage.'
| def __init__(self, model, data, mapping, layer=0, source_srs=None, encoding=None, transaction_mode='commit_on_success', transform=True, unique=None, using=DEFAULT_DB_ALIAS):
| if isinstance(data, basestring):
self.ds = DataSource(data)
else:
self.ds = data
self.layer = self.ds[layer]
self.using = using
self.spatial_backend = connections[using].ops
self.mapping = mapping
self.model = model
self.check_layer()
if self.spatial_backend.mysql:
... |
'This checks the `fid_range` keyword.'
| def check_fid_range(self, fid_range):
| if fid_range:
if isinstance(fid_range, (tuple, list)):
return slice(*fid_range)
elif isinstance(fid_range, slice):
return fid_range
else:
raise TypeError
else:
return None
|
'This checks the Layer metadata, and ensures that it is compatible
with the mapping information and model. Unlike previous revisions,
there is no need to increment through each feature in the Layer.'
| def check_layer(self):
| self.geom_field = False
self.fields = {}
ogr_fields = self.layer.fields
ogr_field_types = self.layer.field_types
def check_ogr_fld(ogr_map_fld):
try:
idx = ogr_fields.index(ogr_map_fld)
except ValueError:
raise LayerMapError(('Given mapping OGR field ... |
'Checks the compatibility of the given spatial reference object.'
| def check_srs(self, source_srs):
| if isinstance(source_srs, SpatialReference):
sr = source_srs
elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()):
sr = source_srs.srs
elif isinstance(source_srs, (int, basestring)):
sr = SpatialReference(source_srs)
else:
sr = self.layer.srs
if (not sr... |
'Checks the `unique` keyword parameter -- may be a sequence or string.'
| def check_unique(self, unique):
| if isinstance(unique, (list, tuple)):
for attr in unique:
if (not (attr in self.mapping)):
raise ValueError
elif isinstance(unique, basestring):
if (unique not in self.mapping):
raise ValueError
else:
raise TypeError('Unique keyword argum... |
'Given an OGR Feature, this will return a dictionary of keyword arguments
for constructing the mapped model.'
| def feature_kwargs(self, feat):
| kwargs = {}
for (field_name, ogr_name) in self.mapping.items():
model_field = self.fields[field_name]
if isinstance(model_field, GeometryField):
val = self.verify_geom(feat.geom, model_field)
elif isinstance(model_field, models.base.ModelBase):
val = self.verify_f... |
'Given the feature keyword arguments (from `feature_kwargs`) this routine
will construct and return the uniqueness keyword arguments -- a subset
of the feature kwargs.'
| def unique_kwargs(self, kwargs):
| if isinstance(self.unique, basestring):
return {self.unique: kwargs[self.unique]}
else:
return dict(((fld, kwargs[fld]) for fld in self.unique))
|
'Verifies if the OGR Field contents are acceptable to the Django
model field. If they are, the verified value is returned,
otherwise the proper exception is raised.'
| def verify_ogr_field(self, ogr_field, model_field):
| if (isinstance(ogr_field, OFTString) and isinstance(model_field, (models.CharField, models.TextField))):
if self.encoding:
val = unicode(ogr_field.value, self.encoding)
else:
val = ogr_field.value
if (len(val) > model_field.max_length):
raise Inval... |
'Given an OGR Feature, the related model and its dictionary mapping,
this routine will retrieve the related model for the ForeignKey
mapping.'
| def verify_fk(self, feat, rel_model, rel_mapping):
| fk_kwargs = {}
for (field_name, ogr_name) in rel_mapping.items():
fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))
try:
return rel_model.objects.get(**fk_kwargs)
except ObjectDoesNotExist:
raise MissingForeignKey(('No Foreign... |
'Verifies the geometry -- will construct and return a GeometryCollection
if necessary (for example if the model field is MultiPolygonField while
the mapped shapefile only contains Polygons).'
| def verify_geom(self, geom, model_field):
| if (self.coord_dim != geom.coord_dim):
geom.coord_dim = self.coord_dim
if self.make_multi(geom.geom_type, model_field):
multi_type = self.MULTI_TYPES[geom.geom_type.num]
g = OGRGeometry(multi_type)
g.add(geom)
else:
g = geom
if self.transform:
g.transform(... |
'Returns the coordinate transformation object.'
| def coord_transform(self):
| SpatialRefSys = self.spatial_backend.spatial_ref_sys()
try:
target_srs = SpatialRefSys.objects.get(srid=self.geo_field.srid).srs
return CoordTransform(self.source_srs, target_srs)
except Exception as msg:
raise LayerMapError(('Could not translate between the data so... |
'Returns the GeometryField instance associated with the geographic column.'
| def geometry_field(self):
| opts = self.model._meta
(fld, model, direct, m2m) = opts.get_field_by_name(self.geom_field)
return fld
|
'Given the OGRGeomType for a geometry and its associated GeometryField,
determine whether the geometry should be turned into a GeometryCollection.'
| def make_multi(self, geom_type, model_field):
| return ((geom_type.num in self.MULTI_TYPES) and (model_field.__class__.__name__ == ('Multi%s' % geom_type.django)))
|
'Saves the contents from the OGR DataSource Layer into the database
according to the mapping dictionary given at initialization.
Keyword Parameters:
verbose:
If set, information will be printed subsequent to each model save
executed on the database.
fid_range:
May be set with a slice or tuple of (begin, end) feature ID... | def save(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False):
| default_range = self.check_fid_range(fid_range)
if progress:
if ((progress is True) or (not isinstance(progress, int))):
progress_interval = 1000
else:
progress_interval = progress
@self.transaction_decorator
def _save(feat_range=default_range, num_feat=0, num_sav... |
'Add item ``obj`` to the graph. Returns True (and does nothing)
if the item has been seen already.
The ``parent_obj`` argument must already exist in the graph; if
not, it\'s ignored (but ``obj`` is still added with no
parent). In any case, Model._collect_sub_objects (for whom
this API exists) will never pass a parent t... | def add(self, model, pk, obj, parent_model=None, parent_obj=None, nullable=False):
| (model, pk) = (type(obj), obj._get_pk_val())
if model._meta.auto_created:
return True
key = (model, pk)
if (key in self.seen):
return True
self.seen.setdefault(key, obj)
if (parent_obj is not None):
(parent_model, parent_pk) = (type(parent_obj), parent_obj._get_pk_val())
... |
'Return the graph as a nested list.
Passes **kwargs back to the format_callback as kwargs.'
| def nested(self, format_callback=None, **kwargs):
| roots = []
for key in self.seen.keys():
if (key not in self.parents):
roots.extend(self._nested(key, format_callback, **kwargs))
return roots
|
'Returns the edited object represented by this log entry'
| def get_edited_object(self):
| return self.content_type.get_object_for_this_type(pk=self.object_id)
|
'Returns the admin URL to edit the object represented by this log entry.
This is relative to the Django admin index page.'
| def get_admin_url(self):
| return mark_safe((u'%s/%s/%s/' % (self.content_type.app_label, self.content_type.model, quote(self.object_id))))
|
'Outputs a <ul> for this set of radio fields.'
| def render(self):
| return mark_safe((u'<ul%s>\n%s\n</ul>' % (flatatt(self.attrs), u'\n'.join([(u'<li>%s</li>' % force_unicode(w)) for w in self]))))
|
'Helper function for building an attribute dictionary.'
| def build_attrs(self, extra_attrs=None, **kwargs):
| self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs)
return self.attrs
|
'Registers the given model(s) with the given admin class.
The model(s) should be Model classes, not instances.
If an admin class isn\'t given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they\'ll be applied as options to the admin class.
If a model is alre... | def register(self, model_or_iterable, admin_class=None, **options):
| if (not admin_class):
admin_class = ModelAdmin
if (admin_class and settings.DEBUG):
from django.contrib.admin.validation import validate
else:
validate = (lambda model, adminclass: None)
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
... |
'Unregisters the given model(s).
If a model isn\'t already registered, this will raise NotRegistered.'
| def unregister(self, model_or_iterable):
| if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if (model not in self._registry):
raise NotRegistered(('The model %s is not registered' % model.__name__))
del self._registry[model]
|
'Register an action to be available globally.'
| def add_action(self, action, name=None):
| name = (name or action.__name__)
self._actions[name] = action
self._global_actions[name] = action
|
'Disable a globally-registered action. Raises KeyError for invalid names.'
| def disable_action(self, name):
| del self._actions[name]
|
'Explicitally get a registered global action wheather it\'s enabled or
not. Raises KeyError for invalid names.'
| def get_action(self, name):
| return self._global_actions[name]
|
'Get all the enabled actions as an iterable of (name, func).'
| def actions(self):
| return self._actions.iteritems()
|
'Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.'
| def has_permission(self, request):
| return (request.user.is_active and request.user.is_staff)
|
'Check that all things needed to run the admin have been correctly installed.
The default implementation checks that LogEntry, ContentType and the
auth context processor are installed.'
| def check_dependencies(self):
| from django.contrib.admin.models import LogEntry
from django.contrib.contenttypes.models import ContentType
if (not LogEntry._meta.installed):
raise ImproperlyConfigured("Put 'django.contrib.admin' in your INSTALLED_APPS setting in order to use the admin applicati... |
'Decorator to create an admin view attached to this ``AdminSite``. This
wraps the view and provides permission checking by calling
``self.has_permission``.
You\'ll want to use this from within ``AdminSite.get_urls()``:
class MyAdminSite(AdminSite):
def get_urls(self):
from django.conf.urls.defaults import patterns, url... | def admin_view(self, view, cacheable=False):
| def inner(request, *args, **kwargs):
if (not self.has_permission(request)):
return self.login(request)
return view(request, *args, **kwargs)
if (not cacheable):
inner = never_cache(inner)
if (not getattr(view, 'csrf_exempt', False)):
inner = csrf_protect(inner)
... |
'Handles the "change password" task -- both form display and validation.'
| def password_change(self, request):
| from django.contrib.auth.views import password_change
if (self.root_path is not None):
url = ('%spassword_change/done/' % self.root_path)
else:
url = reverse('admin:password_change_done', current_app=self.name)
defaults = {'post_change_redirect': url}
if (self.password_change_templat... |
'Displays the "success" page after a password change.'
| def password_change_done(self, request):
| from django.contrib.auth.views import password_change_done
defaults = {}
if (self.password_change_done_template is not None):
defaults['template_name'] = self.password_change_done_template
return password_change_done(request, **defaults)
|
'Displays the i18n JavaScript that the Django admin requires.
This takes into account the USE_I18N setting. If it\'s set to False, the
generated JavaScript will be leaner and faster.'
| def i18n_javascript(self, request):
| if settings.USE_I18N:
from django.views.i18n import javascript_catalog
else:
from django.views.i18n import null_javascript_catalog as javascript_catalog
return javascript_catalog(request, packages='django.conf')
|
'Logs out the user for the given HttpRequest.
This should *not* assume the user is already logged in.'
| def logout(self, request):
| from django.contrib.auth.views import logout
defaults = {}
if (self.logout_template is not None):
defaults['template_name'] = self.logout_template
return logout(request, **defaults)
|
'Displays the login form for the given HttpRequest.'
| def login(self, request):
| from django.contrib.auth.models import User
if (not request.POST.has_key(LOGIN_FORM_KEY)):
if request.POST:
message = _('Please log in again, because your session has expired.')
else:
message = ''
return self.display_login_form(request, mes... |
'Displays the main admin index page, which lists all of the installed
apps that have been registered in this site.'
| 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... |
'DEPRECATED. This function is the old way of handling URL resolution, and
is deprecated in favor of real URL resolution -- see ``get_urls()``.
This function still exists for backwards-compatibility; it will be
removed in Django 1.3.'
| def root(self, request, url):
| import warnings
warnings.warn('AdminSite.root() is deprecated; use include(admin.site.urls) instead.', DeprecationWarning)
if ((request.method == 'GET') and (not request.path.endswith('/'))):
return http.HttpResponseRedirect((request.path + '/'))
if settings.DEBUG:
self.ch... |
'DEPRECATED. This is the old way of handling a model view on the admin
site; the new views should use get_urls(), above.'
| def model_page(self, request, app_label, model_name, rest_of_url=None):
| from django.db import models
model = models.get_model(app_label, model_name)
if (model is None):
raise http.Http404(('App %r, model %r, not found.' % (app_label, model_name)))
try:
admin_obj = self._registry[model]
except KeyError:
raise http.Http404('This m... |
'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 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)}
|
'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
|
'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 has been successfully deleted. Note that since the
object is deleted, it might no longer be safe to call *any* methods
on the object, hence this method getting object_repr.
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):
| if (self.actions is None):
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_... |
'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 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 request.POST.has_key('_continue'):
self.message_user(request, ((msg + ' ') + _('You may edi... |
'Determines the HttpResponse for the change_view stage.'
| def response_change(self, request, obj):
| opts = obj._meta
pk_value = obj._get_pk_val()
msg = (_('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)})
if request.POST.has_key('_continue'):
self.message_user(request, ((msg + ' ') + _('You may e... |
'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
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... |
'DEPRECATED: this is the old way of URL resolution, replaced by
``get_urls()``. This only called by AdminSite.root(), which is also
deprecated.
Again, remember that the following code only exists for
backwards-compatibility. Any new URLs, changes to existing URLs, or
whatever need to be done up in get_urls(), above!
Th... | def __call__(self, request, url):
| if (url is None):
return self.changelist_view(request)
elif (url == 'add'):
return self.add_view(request)
elif url.endswith('/history'):
return self.history_view(request, unquote(url[:(-8)]))
elif url.endswith('/delete'):
return self.delete_view(request, unquote(url[:(-7)... |
'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:]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.