idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
33,300
def rasterToPolygon ( raster_file , polygon_file ) : log ( "Process: Raster to Polygon ..." ) time_start = datetime . utcnow ( ) temp_polygon_file = "{0}_temp.shp" . format ( os . path . splitext ( os . path . basename ( polygon_file ) ) [ 0 ] ) GDALGrid ( raster_file ) . to_polygon ( out_shapefile = temp_polygon_file ...
Converts watershed raster to polygon and then dissolves it . It dissolves features based on the LINKNO attribute .
33,301
def pitRemove ( self , elevation_grid , pit_filled_elevation_grid , input_depression_mask_grid = None , consider4way = False , ) : log ( "PROCESS: PitRemove" ) self . pit_filled_elevation_grid = pit_filled_elevation_grid cmd = [ os . path . join ( self . taudem_exe_path , 'pitremove' ) , '-z' , elevation_grid , '-fel' ...
Remove low spots from DEM .
33,302
def dinfFlowDirection ( self , flow_dir_grid , slope_grid , pit_filled_elevation_grid = None ) : log ( "PROCESS: DinfFlowDirection" ) if pit_filled_elevation_grid : self . pit_filled_elevation_grid = pit_filled_elevation_grid cmd = [ os . path . join ( self . taudem_exe_path , 'dinfflowdir' ) , '-fel' , self . pit_fill...
Calculates flow direction with Dinf method
33,303
def dinfContributingArea ( self , contributing_area_grid , flow_dir_grid , outlet_shapefile = None , weight_grid = None , edge_contamination = False , ) : log ( "PROCESS: DinfContributingArea" ) cmd = [ os . path . join ( self . taudem_exe_path , 'areadinf' ) , '-ang' , flow_dir_grid , '-sca' , contributing_area_grid ,...
Calculates contributing area with Dinf method .
33,304
def streamDefByThreshold ( self , stream_raster_grid , threshold , contributing_area_grid , mask_grid = None , ) : log ( "PROCESS: StreamDefByThreshold" ) self . stream_raster_grid = stream_raster_grid cmd = [ os . path . join ( self . taudem_exe_path , 'threshold' ) , '-ssa' , contributing_area_grid , '-src' , self . ...
Calculates the stream definition by threshold .
33,305
def streamReachAndWatershed ( self , delineate , out_stream_order_grid , out_network_connectivity_tree , out_network_coordinates , out_stream_reach_file , out_watershed_grid , pit_filled_elevation_grid = None , flow_dir_grid = None , contributing_area_grid = None , stream_raster_grid = None , outlet_shapefile = None ) ...
Creates vector network and shapefile from stream raster grid
33,306
def demToStreamNetwork ( self , output_directory , raw_elevation_dem = "" , pit_filled_elevation_grid = "" , flow_dir_grid_d8 = "" , contributing_area_grid_d8 = "" , flow_dir_grid_dinf = "" , contributing_area_grid_dinf = "" , use_dinf = False , threshold = 1000 , delineate = False ) : time_start = datetime . utcnow ( ...
This function will run all of the TauDEM processes to generate a stream network from an elevation raster .
33,307
def build_iiif_file_storage_path ( url_path , ik_image , iiif_storage ) : storage_path = url_path [ 1 : ] if storage_path . startswith ( 'iiif/' ) : storage_path = storage_path [ 5 : ] ik_image_ts = str ( calendar . timegm ( ik_image . date_modified . timetuple ( ) ) ) splits = storage_path . split ( '/' ) storage_path...
Return the file storage path for a given IIIF Image API URL path .
33,308
def get_roles ( self ) : work_ids = self . get_works ( ) . values_list ( 'id' , flat = True ) return self . works . through . objects . filter ( creator = self . get_draft ( ) , work_id__in = work_ids , ) . select_related ( 'role' )
Return the m2m relations connecting me to works
33,309
def derive_and_set_slug ( self , set_name_sort = True , set_slug = True ) : if is_empty ( self . title ) : raise ValueError ( u"%s.title cannot be empty at save" % type ( self ) . __name__ ) if set_slug and is_empty ( self . slug ) : self . slug = slugify ( self . title )
Derive slug field from title unless it is set in its own right .
33,310
def get_roles ( self ) : creator_ids = self . get_creators ( ) . values_list ( 'id' , flat = True ) return self . creators . through . objects . filter ( work = self . get_draft ( ) , creator_id__in = creator_ids , ) . select_related ( 'role' )
Return the m2m relations connecting me to creators .
33,311
def get_urls ( self ) : from django . conf . urls import patterns , url urls = super ( EventAdmin , self ) . get_urls ( ) my_urls = patterns ( '' , url ( r'^calendar/$' , self . admin_site . admin_view ( self . calendar ) , name = 'icekit_events_eventbase_calendar' ) , url ( r'^calendar_data/$' , self . admin_site . ad...
Add a calendar URL .
33,312
def calendar ( self , request ) : context = { 'is_popup' : bool ( int ( request . GET . get ( '_popup' , 0 ) ) ) , } return TemplateResponse ( request , 'admin/icekit_events/eventbase/calendar.html' , context )
Return a calendar page to be loaded in an iframe .
33,313
def calendar_data ( self , request ) : request . GET = request . GET . copy ( ) if 'timezone' in request . GET : tz = djtz . get ( request . GET . pop ( 'timezone' ) ) else : tz = get_current_timezone ( ) if 'start' in request . GET : start_dt = self . _parse_dt_from_request ( request , 'start' ) if start_dt : start = ...
Return event data in JSON format for AJAX requests or a calendar page to be loaded in an iframe .
33,314
def _calendar_json_for_occurrence ( self , occurrence ) : if occurrence . is_all_day : start = occurrence . start end = occurrence . start + timedelta ( days = 1 ) else : start = djtz . localize ( occurrence . start ) end = djtz . localize ( occurrence . end ) if occurrence . is_cancelled and occurrence . cancel_reason...
Return JSON for a single Occurrence
33,315
def _calendar_classes_for_occurrence ( self , occurrence ) : classes = [ slugify ( occurrence . event . polymorphic_ctype . name ) ] if occurrence . is_all_day : classes . append ( 'is-all-day' ) if occurrence . is_protected_from_regeneration : classes . append ( 'is-user-modified' ) if occurrence . is_cancelled : clas...
Return css classes to be used in admin calendar JSON
33,316
def get_urls ( self ) : from django . conf . urls import patterns , url urls = super ( RecurrenceRuleAdmin , self ) . get_urls ( ) my_urls = patterns ( '' , url ( r'^preview/$' , self . admin_site . admin_view ( self . preview ) , name = 'icekit_events_recurrencerule_preview' ) , ) return my_urls + urls
Add a preview URL .
33,317
def preview ( self , request ) : recurrence_rule = request . POST . get ( 'recurrence_rule' ) limit = int ( request . POST . get ( 'limit' , 10 ) ) try : rruleset = rrule . rrulestr ( recurrence_rule , dtstart = djtz . now ( ) , forceset = True ) except ValueError as e : data = { 'error' : six . text_type ( e ) , } els...
Return a occurrences in JSON format up until the configured limit .
33,318
def parse_primary_types ( self , request ) : if request . GET . getlist ( 'primary_types' ) : return EventType . objects . get ( slug__in = request . GET . getlist ( 'primary_types' ) ) return None
Return primary event types that occurrences must belong to or None if there is no constraint on primary type .
33,319
def parse_secondary_types ( self , request ) : if request . GET . getlist ( 'secondary_types' ) : return EventType . objects . filter ( slug__in = request . GET . getlist ( 'secondary_types' ) ) return None
Return secondary event types that occurrences must belong to or None if there is no constraint on secondary type .
33,320
def get_users ( self , email ) : if hasattr ( super ( PasswordResetForm , self ) , 'get_users' ) : return ( u for u in super ( PasswordResetForm , self ) . get_users ( email ) if u . is_staff and u . is_active ) active_users = get_user_model ( ) . _default_manager . filter ( email__iexact = email , is_active = True ) r...
Make sure users are staff users .
33,321
def send_email_notifications_for_workflow_state_change ( sender , instance , * args , ** kwargs ) : if not appsettings . WORKFLOW_EMAIL_NOTIFICATION_TARGETS : return obj = instance . content_object obj_ct = ContentType . objects . get_for_model ( obj ) obj_app_name = '_' . join ( obj_ct . natural_key ( ) ) admin_path =...
Send email notifications for save events on WorkflowState based on settings in this module s appsettings .
33,322
def _get_image_or_404 ( identifier , load_image = False ) : try : image_id = int ( identifier ) except ValueError : raise Http404 ( ) ik_image = get_object_or_404 ( ICEkitImage , id = image_id ) if not load_image : return ik_image , None image = Image . open ( BytesIO ( ik_image . image . read ( ) ) ) try : image . loa...
Return image matching identifier .
33,323
def iiif_image_api ( request , identifier_param , region_param , size_param , rotation_param , quality_param , format_param ) : ik_image , image = _get_image_or_404 ( identifier_param , load_image = True ) is_transparent = et_utils . is_transparent ( image ) is_grayscale = image . mode in ( 'L' , 'LA' ) format_mapping ...
Image repurposing endpoint for IIIF Image API 2 . 1
33,324
def clean_url ( self ) : url = self . cleaned_data [ 'url' ] if url : pattern = re . compile ( r'https?://(www\.)?instagr(\.am|am\.com)/p/\S+' ) if not pattern . match ( url ) : raise forms . ValidationError ( 'Please provide a valid instagram link.' ) return url
Make sure the URL provided matches the instagram URL format .
33,325
def retrieve ( self , request , * args , ** kwargs ) : try : instance = self . get_object ( ) serializer = self . get_serializer ( instance ) return Response ( serializer . data ) except Http404 : pass lookup_url_kwarg = self . lookup_url_kwarg or self . lookup_field slug = self . kwargs [ lookup_url_kwarg ] try : tmp ...
If the URL slug doesn t match an object try slugifying the URL param and searching alt_url for that . If found redirect to the canonical URL . If still not found raise 404 .
33,326
def forwards ( apps , schema_editor ) : starts = timeutils . round_datetime ( when = timezone . now ( ) , precision = timedelta ( days = 1 ) , rounding = timeutils . ROUND_DOWN ) ends = starts + appsettings . DEFAULT_ENDS_DELTA recurrence_rules = dict ( RecurrenceRule . objects . values_list ( 'description' , 'recurren...
Create sample events .
33,327
def backwards ( apps , schema_editor ) : titles = [ 'Daily Event' , 'Weekday Event' , 'Weekend Event' , 'Weekly Event' , 'Monthly Event' , 'Yearly Event' , ] samples = EventBase . objects . filter ( title__in = titles ) samples . delete ( )
Delete sample events including derivative repeat and variation events .
33,328
def dump_viewset ( viewset_class , root_folder , folder_fn = lambda i : "." , sample_size = None ) : if os . path . exists ( root_folder ) : shutil . rmtree ( root_folder ) os . makedirs ( root_folder ) vs = viewset_class ( ) vs . request = rf . get ( '' ) serializer_class = vs . get_serializer_class ( ) serializer = s...
Dump the contents of a rest - api queryset to a folder structure .
33,329
def concatenate_json ( source_folder , destination_file ) : matches = [ ] for root , dirnames , filenames in os . walk ( source_folder ) : for filename in fnmatch . filter ( filenames , '*.json' ) : matches . append ( os . path . join ( root , filename ) ) with open ( destination_file , "wb" ) as f : f . write ( "[\n" ...
Concatenate all the json files in a folder to one big JSON file .
33,330
def validate_unique_slug ( self ) : clashes_qs = type ( self ) . objects . filter ( slug = self . slug ) if self . pk : clashes_qs = clashes_qs . exclude ( pk = self . pk ) if isinstance ( self , PublishingModel ) : clashes_qs = clashes_qs . filter ( publishing_is_draft = self . publishing_is_draft ) if clashes_qs : ra...
Ensure slug is unique for this model . This check is aware of publishing but is otherwise fairly basic and will need to be customised for situations where models with slugs are not in a flat hierarchy etc .
33,331
def get_absolute_url ( self ) : if self . is_draft : visible_parent = self . parent . get_draft ( ) else : visible_parent = self . parent . get_published ( ) or self . parent . get_draft ( ) return urljoin ( visible_parent . get_absolute_url ( ) , self . slug + "/" )
The majority of the time the URL is the parent s URL plus the slug . If not override this function .
33,332
def get_response ( self , request , parent , * args , ** kwargs ) : context = { 'page' : self , } try : return TemplateResponse ( request , self . get_layout_template_name ( ) , context ) except AttributeError : raise AttributeError ( "You need to define " "`get_layout_template_name()` on your `%s` model, " "or overrid...
Render this collected content to a response .
33,333
def forwards_migration ( apps , schema_editor ) : RecurrenceRule = apps . get_model ( 'icekit_events' , 'RecurrenceRule' ) for rrule in RecurrenceRule . objects . all ( ) : if ';\n' in rrule . recurrence_rule : parts = rrule . recurrence_rule . split ( ';\n' ) rrule . recurrence_rule = '\n' . join ( parts ) rrule . sav...
0002_recurrence_rules added malformed recurrence with trailing semi - colons . While the JS parser on the front - end handles them the python parser will crash
33,334
def get_response_page ( request , return_type , template_location , response_page_type ) : try : page = models . ResponsePage . objects . get ( is_active = True , type = response_page_type , ) template = loader . get_template ( template_location ) content_type = None body = template . render ( RequestContext ( request ...
Helper function to get an appropriate response page if it exists .
33,335
def server_error ( request , template_name = '500.html' ) : try : rendered_page = get_response_page ( request , http . HttpResponseServerError , 'icekit/response_pages/500.html' , abstract_models . RESPONSE_HTTP500 ) if rendered_page is not None : return rendered_page except Exception : pass return defaults . server_er...
Custom 500 error handler .
33,336
def allowed_to_preview ( user ) : if ( user . is_authenticated and user . is_active and user . is_staff ) : return True return False
Is the user allowed to view the preview?
33,337
def get_child_type_choices ( self , request , action ) : choices = super ( ChildModelPluginPolymorphicParentModelAdmin , self ) . get_child_type_choices ( request , action ) plugins = self . child_model_plugin_class . get_plugins ( ) labels = { } sort_priorities = { } if plugins : for plugin in plugins : pk = plugin . ...
Override choice labels with verbose_name from plugins and sort .
33,338
def get_child_models ( self ) : child_models = [ ] for plugin in self . child_model_plugin_class . get_plugins ( ) : child_models . append ( ( plugin . model , plugin . model_admin ) ) if not child_models : child_models . append ( ( self . child_model_admin . base_model , self . child_model_admin , ) ) return child_mod...
Get child models from registered plugins . Fallback to the child model admin and its base model if no plugins are registered .
33,339
def _get_child_admin_site ( self , rel ) : if rel . to not in self . admin_site . _registry : for parent in rel . to . mro ( ) : if parent in self . admin_site . _registry and hasattr ( self . admin_site . _registry [ parent ] , '_child_admin_site' ) : return self . admin_site . _registry [ parent ] . _child_admin_site...
Returns the separate AdminSite instance that django - polymorphic maintains for child models .
33,340
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' ] = PolymorphicForeignKeyRawIdWidget ( db_field . rel , admin_site = self . _get_child_admin_site ( db_field . rel ) , using = db ) if 'queryset' n...
Replicates the logic in ModelAdmin . forfield_for_foreignkey replacing the widget with the patched one above initialising it with the child admin site .
33,341
def wikipedia_slugify ( value , do_unidecode = False ) : if do_unidecode : value = unidecode ( value ) value = value . strip ( ) return mark_safe ( re . sub ( '[\s/#\?:@]+' , '_' , value ) )
Converts to ASCII via unidecode . Converts spaces to underscore .
33,342
def ensure_unique ( qs , field_name , value , exclude_id = None ) : orig = value if not value : value = "None" for x in itertools . count ( 1 ) : if not qs . exclude ( id = exclude_id ) . filter ( ** { field_name : value } ) . exists ( ) : break if orig : value = '%s-%d' % ( orig , x ) else : value = '%d' % x return va...
Makes sure that value is unique on model . fieldname . And nonempty .
33,343
def fix_line_breaks ( s ) : l = s . splitlines ( ) x = [ i . strip ( ) for i in l ] x = [ i for i in x if i ] return "\n" . join ( x )
Convert \ r \ n and \ r to \ n chars . Strip any leading or trailing whitespace on each line . Remove blank lines .
33,344
def update_json_analysis ( analysis , j ) : def _analyze_list ( l , parent = "" ) : for v in l : if isinstance ( v , ( dict , CaseInsensitiveDict ) ) : _analyze_json ( v , parent = parent ) elif isinstance ( v , list ) : _analyze_list ( v , parent = parent + "[]" ) else : analysis [ parent ] . add ( v ) def _analyze_js...
Step through the items in a piece of json and update an analysis dict with the values found .
33,345
def add_missing_placeholders ( self ) : content_type = ContentType . objects . get_for_model ( self ) result = False if self . layout : for data in self . layout . get_placeholder_data ( ) : placeholder , created = Placeholder . objects . update_or_create ( parent_type = content_type , parent_id = self . pk , slot = da...
Add missing placeholders from templates . Return True if any missing placeholders were created .
33,346
def get_og_title ( self ) : if hasattr ( self , 'meta_title' ) and self . meta_title : return self . meta_title return self . get_title ( )
return meta_title if exists otherwise fall back to title
33,347
def get_map_data ( self ) : return { 'containerSelector' : '#' + self . get_map_element_id ( ) , 'center' : self . map_center_description , 'marker' : self . map_marker_description or self . map_center_description , 'zoom' : self . map_zoom , 'href' : self . get_map_href ( ) , 'key' : getattr ( settings , 'GOOGLE_MAPS_...
Returns a serializable data set describing the map location
33,348
def get_map_href ( self ) : if self . map_center_lat and self . map_center_long : params = { 'll' : '%s,%s' % ( self . map_center_lat , self . map_center_long ) } else : params = { 'q' : self . map_center_description } return self . GOOGLE_MAPS_HREF_ROOT + urllib . urlencode ( params )
Returns a link to an external view of the map
33,349
def round_datetime ( when = None , precision = 60 , rounding = ROUND_NEAREST ) : when = when or djtz . now ( ) weekday = WEEKDAYS . get ( precision , WEEKDAYS [ 'MON' ] ) if precision in WEEKDAYS : precision = int ( timedelta ( days = 7 ) . total_seconds ( ) ) elif isinstance ( precision , timedelta ) : precision = int...
Round a datetime object to a time that matches the given precision .
33,350
def coerce_dt_awareness ( date_or_datetime , tz = None , t = None ) : if isinstance ( date_or_datetime , datetime ) : dt = date_or_datetime else : dt = datetime . combine ( date_or_datetime , t or time . min ) is_project_tz_aware = settings . USE_TZ if is_project_tz_aware : return coerce_aware ( dt , tz ) elif not is_p...
Coerce the given datetime or date object into a timezone - aware or timezone - naive datetime result depending on which is appropriate for the project s settings .
33,351
def get_draft_secret_key ( ) : draft_secret_key , created = Text . objects . get_or_create ( name = 'DRAFT_SECRET_KEY' , defaults = dict ( value = get_random_string ( 50 ) , ) ) return draft_secret_key . value
Return the secret key used to generate draft mode HMACs . It will be randomly generated on first access . Existing draft URLs can be invalidated by deleting or updating the DRAFT_SECRET_KEY setting .
33,352
def get_draft_url ( url ) : if verify_draft_url ( url ) : return url url = urlparse . urlparse ( url ) salt = get_random_string ( 5 ) query = QueryDict ( force_bytes ( url . query ) , mutable = True ) query [ 'preview' ] = '%s:%s' % ( salt , get_draft_hmac ( salt , url . path ) ) parts = list ( url ) parts [ 4 ] = quer...
Return the given URL with a draft mode HMAC in its querystring .
33,353
def verify_draft_url ( url ) : url = urlparse . urlparse ( url ) query = QueryDict ( force_bytes ( url . query ) ) preview_hmac = query . get ( 'preview' ) or query . get ( 'edit' ) if preview_hmac : salt , hmac = preview_hmac . split ( ':' ) return hmac == get_draft_hmac ( salt , url . path ) return False
Return True if the given URL has a valid draft mode HMAC in its querystring .
33,354
def contribute_to_class ( model_class , name = 'slots' , descriptor = None ) : rel_obj = descriptor or PlaceholderDescriptor ( ) rel_obj . contribute_to_class ( model_class , name ) setattr ( model_class , name , rel_obj ) return True
Function that adds a description to a model Class .
33,355
def create_placeholder_access_object ( self , instance ) : related_model = self . related_model def get_related_model_objects ( name ) : return related_model . objects . get ( parent_type = ContentType . objects . get_for_model ( type ( instance ) ) , parent_id = instance . id , slot = name , ) . get_content_items ( ) ...
Created objects with placeholder slots as properties .
33,356
def get_users_for_assigned_to ( ) : User = get_user_model ( ) return User . objects . filter ( is_active = True , is_staff = True )
Return a list of users who can be assigned to workflow states
33,357
def _get_obj_ct ( self , obj ) : if not hasattr ( obj , '_wfct' ) : if hasattr ( obj , 'polymorphic_ctype' ) : obj . _wfct = obj . polymorphic_ctype else : obj . _wfct = ContentType . objects . get_for_model ( obj ) return obj . _wfct
Look up and return object s content type and cache for reuse
33,358
def workflow_states_column ( self , obj ) : workflow_states = models . WorkflowState . objects . filter ( content_type = self . _get_obj_ct ( obj ) , object_id = obj . pk , ) return ', ' . join ( [ unicode ( wfs ) for wfs in workflow_states ] )
Return text description of workflow states assigned to object
33,359
def created_by_column ( self , obj ) : try : first_addition_logentry = admin . models . LogEntry . objects . filter ( object_id = obj . pk , content_type_id = self . _get_obj_ct ( obj ) . pk , action_flag = admin . models . ADDITION , ) . get ( ) return first_addition_logentry . user except admin . models . LogEntry . ...
Return user who first created an item in Django admin
33,360
def create_content_instance ( content_plugin_class , page , placeholder_name = 'main' , ** kwargs ) : placeholders = page . get_placeholder_by_slot ( placeholder_name ) if placeholders . exists ( ) : placeholder = placeholders [ 0 ] else : placeholder = page . create_placeholder ( placeholder_name ) ct = ContentType . ...
Creates a content instance from a content plugin class .
33,361
def expand_python_version ( version ) : if not re . match ( r"^\d\.\d$" , version ) : return [ version ] major , minor = version . split ( "." ) patterns = [ "{major}.{minor}" , "cp{major}{minor}" , "py{major}" , "py{major}.{minor}" , "py{major}{minor}" , "source" , "py2.py3" , ] return set ( pattern . format ( major =...
Expand Python versions to all identifiers used on PyPI .
33,362
def get_package_hashes ( package , version = None , algorithm = DEFAULT_ALGORITHM , python_versions = ( ) , verbose = False , include_prereleases = False , lookup_memory = None , index_url = DEFAULT_INDEX_URL , ) : if lookup_memory is not None and package in lookup_memory : data = lookup_memory [ package ] else : data ...
Gets the hashes for the given package .
33,363
def formfield ( self , ** kwargs ) : if self . plugin_class : self . _choices = self . plugin_class . get_all_choices ( field = self ) return super ( TemplateNameField , self ) . formfield ( ** kwargs )
Get choices from plugins if necessary .
33,364
def register_model_once ( cls , ModelClass , ** kwargs ) : if cls . _static_registry . get_for_model ( ModelClass ) is None : logger . warn ( "Model is already registered with {0}: '{1}'" . format ( cls , ModelClass ) ) else : cls . register_model . register ( ModelClass , ** kwargs )
Tweaked version of AnyUrlField . register_model that only registers the given model after checking that it is not already registered .
33,365
def filter_featured_apps ( admin_apps , request ) : featured_apps = [ ] for orig_app_spec in appsettings . DASHBOARD_FEATURED_APPS : app_spec = orig_app_spec . copy ( ) if "verbose_name" in app_spec : warnings . warn ( "DASHBOARD_FEATURED_APPS[]['verbose_name'] = '%s' is deprecated. " "Use 'name' instead)" % app_spec [...
Given a list of apps return a set of pseudo - apps considered featured .
33,366
def _remove_app_models ( all_apps , models_to_remove ) : filtered_apps = [ ] for app in all_apps : models = [ x for x in app [ 'models' ] if x not in models_to_remove ] if models : app [ 'models' ] = models filtered_apps . append ( app ) return filtered_apps
Remove the model specs in models_to_remove from the models specs in the apps in all_apps . If an app has no models left don t include it in the output .
33,367
def filter_sorted_apps ( admin_apps , request ) : sorted_apps = [ ] for orig_app_spec in appsettings . DASHBOARD_SORTED_APPS : app_spec = orig_app_spec . copy ( ) app_spec [ 'models' ] = _build_app_models ( request , admin_apps , app_spec [ 'models' ] , ensure_all_models = True ) if app_spec [ 'models' ] : sorted_apps ...
Filter admin_apps to show the ones in DASHBOARD_SORTED_APPS first and remove them from the subsequent listings .
33,368
def formfield_for_foreignkey ( self , db_field , * args , ** kwargs ) : formfield = super ( FluentLayoutsMixin , self ) . formfield_for_foreignkey ( db_field , * args , ** kwargs ) if db_field . name == 'layout' : formfield . queryset = formfield . queryset . for_model ( self . model ) return formfield
Update queryset for layout field .
33,369
def get_placeholder_data ( self , request , obj ) : if not obj or not getattr ( obj , 'layout' , None ) : data = [ PlaceholderData ( slot = 'main' , role = 'm' , title = 'Main' ) ] else : data = obj . layout . get_placeholder_data ( ) return data
Get placeholder data from layout .
33,370
def get_thumbnail_source ( self , obj ) : if hasattr ( self , 'thumbnail_field' ) and self . thumbnail_field : return resolve ( obj , self . thumbnail_field ) if hasattr ( obj , 'get_list_image' ) : return resolve ( obj , "get_list_image" ) logger . warning ( 'ThumbnailAdminMixin.thumbnail_field unspecified' ) return N...
Obtains the source image field for the thumbnail .
33,371
def preview ( self , obj , request = None ) : source = self . get_thumbnail_source ( obj ) if source : try : from easy_thumbnails . files import get_thumbnailer except ImportError : logger . warning ( _ ( '`easy_thumbnails` is not installed and required for ' 'icekit.admin_tools.mixins.ThumbnailAdminMixin' ) ) return '...
Generate the HTML to display for the image .
33,372
def one_instance ( function = None , key = '' , timeout = DEFAULT_ONE_INSTANCE_TIMEOUT ) : def _dec ( run_func ) : def _caller ( * args , ** kwargs ) : ret_value = None have_lock = False if REDIS_CLIENT . config_get ( 'appendonly' ) . values ( ) [ 0 ] == 'no' : REDIS_CLIENT . config_set ( 'appendonly' , 'yes' ) lock = ...
Decorator to enforce only one Celery task execution at a time when multiple workers are available .
33,373
def index_queryset ( self , using = None ) : translation . activate ( settings . LANGUAGE_CODE ) return self . get_model ( ) . objects . filter ( status = UrlNode . PUBLISHED ) . select_related ( )
Index current language translation of published objects .
33,374
def get_context ( self , request , page , ** kwargs ) : context = super ( ListingPagePlugin , self ) . get_context ( request , page , ** kwargs ) context [ 'items_to_list' ] = page . get_items_to_list ( request ) return context
Include in context items to be visible on listing page
33,375
def get_view_response ( self , request , page , view_func , view_args , view_kwargs ) : return view_func ( request , page , * view_args , ** view_kwargs )
Render the custom view that was exposed by the extra plugin URL patterns . This gives the ability to add extra middleware logic .
33,376
def clean ( self ) : data = super ( PublishingAdminForm , self ) . clean ( ) cleaned_data = self . cleaned_data instance = self . instance unique_fields_set = instance . get_unique_together ( ) if not unique_fields_set : return data for unique_fields in unique_fields_set : unique_filter = { } for unique_field in unique...
Additional clean data checks for path and keys .
33,377
def has_publish_permission ( self , request , obj = None ) : if is_automatic_publishing_enabled ( self . model ) : return False user_obj = request . user if not user_obj . is_active : return False if user_obj . is_superuser : return True if user_obj . has_perm ( '%s.can_publish' % self . opts . app_label ) : return Tru...
Determines if the user has permissions to publish .
33,378
def has_preview_permission ( self , request , obj = None ) : if self . has_publish_permission ( request , obj = obj ) : return True user_obj = request . user if not user_obj . is_active : return False if user_obj . is_staff : return True return False
Return True if the user has permissions to preview a publishable item .
33,379
def publishing_column ( self , obj ) : if hasattr ( obj , 'get_real_instance' ) : obj = obj . get_real_instance ( ) try : object_url = obj . get_absolute_url ( ) except ( NoReverseMatch , AttributeError ) : object_url = '' template_name = 'admin/publishing/_change_list_publishing_column.html' t = loader . get_template ...
Render publishing - related status icons and view links for display in the admin .
33,380
def publish ( self , request , qs ) : try : qs = self . model . objects . get_real_instances ( qs ) except AttributeError : pass for q in qs : if self . has_publish_permission ( request , q ) : q . publish ( )
Publish bulk action
33,381
def unpublish ( self , request , qs ) : try : qs = self . model . objects . get_real_instances ( qs ) except AttributeError : pass for q in qs : q . unpublish ( )
Unpublish bulk action
33,382
def find_first_available_template ( self , template_name_list ) : if isinstance ( template_name_list , six . string_types ) : return template_name_list else : return _select_template_name ( template_name_list )
Given a list of template names find the first one that actually exists and is available .
33,383
def get_queryset ( self , request ) : self . request = request qs = self . model . objects try : qs_language = self . get_queryset_language ( request ) if qs_language : qs = qs . language ( qs_language ) except AttributeError : pass qs = self . publishing_admin_filter_for_drafts ( qs ) ordering = getattr ( self , 'orde...
The queryset to use for the administration list page .
33,384
def save_related ( self , request , form , * args , ** kwargs ) : result = super ( PublishingAdmin , self ) . save_related ( request , form , * args , ** kwargs ) if form . instance : publishing_signals . publishing_post_save_related . send ( sender = type ( self ) , instance = form . instance ) return result
Send the signal publishing_post_save_related when a draft copy is saved and all its relationships have also been created .
33,385
def render_change_form ( self , request , context , add = False , change = False , form_url = '' , obj = None ) : obj = context . get ( 'original' , None ) if obj : context [ 'object' ] = obj context [ 'has_been_published' ] = obj . has_been_published context [ 'is_dirty' ] = obj . is_dirty context [ 'has_preview_permi...
Provides the context and rendering for the admin change form .
33,386
def get_queryset ( self , request ) : self . request = request qs = super ( PublishingFluentPagesParentAdminMixin , self ) . get_queryset ( request ) qs = qs . filter ( status = UrlNode . DRAFT ) return qs
Show only DRAFT Fluent page items in admin .
33,387
def find_existing_page ( self , titles_hierarchy ) : titles_filters = { 'publishing_is_draft' : True } for parent_count , ancestor_title in enumerate ( titles_hierarchy [ : : - 1 ] ) : parent_path = '__' . join ( [ 'parent' ] * parent_count ) filter_name = '%s%stranslations__title' % ( parent_path , parent_path and '__...
Find and return existing page matching the given titles hierarchy
33,388
def apply_request_and_page_to_values ( self , request , page = None ) : value_is_set = False for value in self . _values : value . apply_request_and_page ( request , page )
Use the request and page config to figure out which values are active
33,389
def get_applicable_values ( self ) : return [ v for v in self . _values if v . is_active and not v . is_all_results ]
Return selected values that will affect the search result
33,390
def get_value ( self ) : try : return self . get_applicable_values ( ) [ 0 ] except IndexError : if not self . select_many and self . get_values ( ) : return self . get_values ( ) [ 0 ]
Returns the label of the first value
33,391
def is_default ( self ) : if not self . get_applicable_values ( ) : return True if self . get_value ( ) . is_default : return True return False
Return True if no active values or if the active value is the default
33,392
def save ( self , * args , ** kwargs ) : self . modified = timezone . now ( ) super ( AbstractBaseModel , self ) . save ( * args , ** kwargs )
Update self . modified .
33,393
def publishing_set_update_time ( sender , instance , ** kwargs ) : if hasattr ( instance , 'publishing_linked' ) : if getattr ( instance , '_skip_update_publishing_modified_at' , False ) : instance . _skip_update_publishing_modified_at = False return instance . publishing_modified_at = timezone . now ( )
Update the time modified before saving a publishable object .
33,394
def handle_publishable_m2m_changed ( sender , instance , action , reverse , model , pk_set , ** kwargs ) : if not issubclass ( model , PublishingModel ) : return if reverse : for rel_obj in instance . _meta . get_all_related_many_to_many_objects ( ) : if rel_obj . field . rel . through == sender : m2m = getattr ( insta...
Cache related published objects in pre_clear so they can be restored in post_clear .
33,395
def sync_mptt_tree_fields_from_draft_to_published_post_save ( sender , instance , ** kwargs ) : mptt_opts = getattr ( instance , '_mptt_meta' , None ) published_copy = getattr ( instance , 'publishing_linked' , None ) if mptt_opts and published_copy : sync_mptt_tree_fields_from_draft_to_published ( instance )
Post save trigger to immediately sync MPTT tree structure field changes made to draft copies to their corresponding published copy .
33,396
def sync_mptt_tree_fields_from_draft_to_published ( draft_copy , dry_run = False , force_update_cached_urls = False ) : mptt_opts = getattr ( draft_copy , '_mptt_meta' , None ) published_copy = getattr ( draft_copy , 'publishing_linked' , None ) if not mptt_opts or not published_copy : return { } parent_changed = draft...
Sync tree structure changes from a draft publishable object to its published copy and updates the published copy s Fluent cached URLs when necessary . Or simulates doing this if dry_run is True .
33,397
def create_can_publish_and_can_republish_permissions ( sender , ** kwargs ) : for model in sender . get_models ( ) : if not issubclass ( model , PublishingModel ) : continue content_type = ContentType . objects . get_for_model ( model ) permission , created = Permission . objects . get_or_create ( content_type = conten...
Add can_publish and ca_nrepublish permissions for each publishable model in the system .
33,398
def maybe_automatically_publish_drafts_on_save ( sender , instance , ** kwargs ) : if not is_automatic_publishing_enabled ( sender ) : return if not instance or not hasattr ( instance , 'publishing_linked' ) : return if instance . is_published : return if not instance . is_dirty : return instance . publish ( )
If automatic publishing is enabled immediately publish a draft copy after it has been saved .
33,399
def has_been_published ( self ) : if self . is_published : return True elif self . is_draft : return self . publishing_linked_id is not None raise ValueError ( "Publishable object %r is neither draft nor published" % self )
Return True if the item is either published itself or has an associated published copy .