def commonplan(request, planid):
    """
    A common method that gets the same data structures for viewing
    and editing. This method is called by the viewplan and editplan 
    views.
    
    Parameters:
        request -- An HttpRequest
        planid -- The plan ID to fetch.
        
    Returns:
        A python dict with common plan attributes set to the plan's values.
    """
    note_session_activity(request)

    plan = Plan.objects.filter(id=planid)
    if plan.count() == 1:
        plan = plan[0]   
        plan.edited = getutc(plan.edited)
        levels = plan.legislative_body.get_geolevels()
        districts = plan.get_districts_at_version(plan.version,include_geom=False)
        editable = can_edit(request.user, plan)
        default_demo = plan.legislative_body.get_default_subject()
        max_dists = plan.legislative_body.max_districts
        body_member_short_label = plan.legislative_body.get_short_label()
        body_member_long_label = plan.legislative_body.get_label()
        body_members = plan.legislative_body.get_members_label()
        reporting_template = 'bard_%s.html' % plan.legislative_body.name if not plan.is_community() else None
       
        index = body_member_short_label.find('%(district_id)s')
        if index >= 0:
            body_member_short_label = body_member_short_label[0:index]
        index = body_member_long_label.find('%(district_id)s')
        if index >= 0:
            body_member_long_label = body_member_long_label[0:index]
        if not editable and not can_view(request.user, plan):
            plan = {}
            tags = []
            calculator_reports = []
        else:
            tags = Tag.objects.filter(name__startswith='type=').order_by('id').values_list('name',flat=True)
            tags = map(lambda x:x[5:], tags)

            # Reports defined with calculators (Score Displays, Panels, and Functions)
            # result is a map of relevant panels to score functions with labels and ids,
            # used for generating groups of checkboxes on the evaluate tab.
            calculator_reports = []
            if settings.REPORTS_ENABLED == 'CALC':
                report_displays = ScoreDisplay.objects.filter(name="%s_reports" % plan.legislative_body.name)
                if len(report_displays) > 0:
                    calculator_reports = map(lambda p: {
                                'title': p.__unicode__(),
                                'functions': map(lambda f: {
                                    'label': f.get_label(),
                                    'id': f.id
                                }, p.score_functions.all().filter(selectable_bodies=plan.legislative_body))
                            }, report_displays[0].scorepanel_set.all().order_by('position'))
        
    else:
        # If said plan doesn't exist, use an empty plan & district list.
        plan = {}
        levels = list()
        districts = {}
        editable = False
        default_demo = None
        max_dists = 0
        body_member_short_label = ''
        body_member_long_label = _('District') + ' '
        body_members = _n('district','districts',2)
        reporting_template = None
        tags = []
        calculator_reports = []
    demos = Subject.objects.all().order_by('sort_key')[0:3]
    layers = []
    snaplayers = []

    if len(levels) > 0:
        study_area_extent = list(levels[0].geounit_set.extent(field_name='simple'))
    else:
        # The geolevels with higher indexes are larger geography
        # Cycle through legislative bodies, since they may be in different regions
        for lb in LegislativeBody.objects.all():
            biglevel = lb.get_geolevels()[0]
            if biglevel.geounit_set.count() > 0:
                study_area_extent = biglevel.geounit_set.extent(field_name='simple')
                break

    for level in levels:
        # i18n-ize name here, not in js
        snaplayers.append({
            'geolevel': level.id,
            'level': level.name,
            'layer': 'simple_' + level.name, 
            'long_description': level.get_long_description(),
            'min_zoom': level.min_zoom
        })
    default_selected = False
    for demo in demos:
        isdefault = str((not default_demo is None) and (demo.id == default_demo.id)).lower()
        if isdefault == 'true':
            default_selected = True
        # i18n-ize name & short_display here, not in js
        layers.append({
            'id':demo.id,
            'text':demo.get_short_label(),
            'value':demo.name, 
            'isdefault':isdefault, 
            'isdisplayed':str(demo.is_displayed).lower()
        })
    # If the default demo was not selected among the first three, we'll still need it for the dropdown menus
    if default_demo and not default_selected:
        layers.insert( 0, {
            'id':default_demo.id,
            'text':default_demo.get_short_label(),
            'value':default_demo.name, 
            'isdefault':str(True).lower(), 
            'isdisplayed':str(default_demo.is_displayed).lower()
        })

    # Try to get the mapserver protocol from the settings module.
    # Set it to an empty string if the setting isn't defined so the 
    # front-end Javascript will set a reasonable default (currently
    # the same protocol as the request to the webserver).
    if 'MAP_SERVER_PROTOCOL' in settings.__members__:
        mapserver_protocol = settings.MAP_SERVER_PROTOCOL
    else:
        mapserver_protocol = ''

    short_label = body_member_short_label.strip().lower()
    long_label = body_member_long_label.strip().lower()

    has_regions = Region.objects.all().count() > 1
    bodies = LegislativeBody.objects.all().order_by('region__sort_key','sort_key')
    l_bodies = [b for b in bodies if b in [sd.legislative_body for sd in ScoreDisplay.objects.filter(is_page=True)]]

    try:
        loader.get_template(reporting_template)
    except:
        reporting_template = None

    return RequestContext(request, {
        'bodies': bodies,
        'has_regions': has_regions,
        'leaderboard_bodies': l_bodies,
        'plan': plan,
        'districts': districts,
        'mapserver': settings.MAP_SERVER,
        'mapserver_protocol': mapserver_protocol,
        'basemaps': settings.BASE_MAPS,
        'namespace': settings.MAP_SERVER_NS,
        'ns_href': settings.MAP_SERVER_NSHREF,
        'feature_limit': settings.FEATURE_LIMIT,
        'adjacency': settings.ADJACENCY,
        'convexchoropleth': settings.CONVEX_CHOROPLETH,
        'demographics': layers,
        'snaplayers': snaplayers,
        'unassigned_id': UNASSIGNED_DISTRICT_ID,
        'is_registered': request.user.username != 'anonymous' and request.user.username != '',
        'debugging_staff': settings.DEBUG and request.user.is_staff,
        'userinfo': get_user_info(request.user),
        'is_editable': editable,
        'max_dists': max_dists + 1,
        'ga_account': settings.GA_ACCOUNT,
        'ga_domain': settings.GA_DOMAIN,
        'body_member_short_label': short_label, 
        'body_member_long_label': long_label,
        'body_members': body_members,
        'reporting_template': reporting_template,
        'study_area_extent': study_area_extent,
        'has_leaderboard' : len(ScoreDisplay.objects.filter(is_page=True)) > 0,
        'calculator_reports' : json.dumps(calculator_reports),
        'allow_email_submissions': ('EMAIL_SUBMISSION' in settings.__members__),
        'tags': tags,
        'site': Site.objects.get_current(),
        'plan_text': _("community map") if (plan and plan.is_community()) else _("plan"),
        'language_code': translation.get_language(),
        'LANGUAGES': settings.LANGUAGES # needed (as CAPS) for language chooser
    })
dataset/ETHPy150Open PublicMapping/DistrictBuilder/django/publicmapping/redistricting/views.py/commonplan/original