Example #1
0
def location(request, loc, format=None):
	'''
	Will one day be a wrapper for all data models, searching over all locations
	and organizations, maybe even people too
	'''
	from campus.models import Building, Location
	
	try:
		location = Building.objects.get(pk=loc)
	except Building.DoesNotExist:
		try:
			location = Location.objects.get(pk=loc)
		except Location.DoesNotExist:
			raise Http404()
	
	html = location_html(location, request)
	location = location.json()
	location['info'] = html
	base_url = request.build_absolute_uri('/')[:-1]
	location['marker'] = base_url + settings.MEDIA_URL + 'images/markers/yellow.png'
	
	if format == 'bubble':
		return render(request, template, context)
	
	if format == 'json':
		if settings.DEBUG:
			import time
			time.sleep(.5)
		
		response = HttpResponse(json.dumps(location))
		response['Content-type'] = 'application/json'
		return response
	
	return home(request, location=location)
Example #2
0
def view(request, id):
    index = r.get(id)

    if request.method == 'GET':
        if index is None:
            return redirect('create')
        ctx = {}
        ctx['id'] = id
        ctx['posts'] = []
        for i in range(0, int(index)):
            ctx['posts'].append({
                'timestamp': r.get(timestampkey(id, i)),
                'headers': r.hgetall(headerkey(id, i)),
                'body': r.hgetall(bodykey(id, i)),
            })
        return render(request, 'view.html', ctx)

    elif request.method == 'POST':
        if index is None:
            return HttpResponseBadRequest()
        index = r.incr(id) - 1
        r.set(timestampkey(id, index), datetime.datetime.now())
        for h, v in request.META.iteritems():
            if h in header_whitelist or h.startswith('HTTP_'):
                r.hset(headerkey(id, index), h, unquote(v))
        for p, v in request.POST.iteritems():
            try:
                d = json.loads(v)
                r.hset(bodykey(id, index), p, json.dumps(d, indent=4))
            except ValueError:
                r.hset(bodykey(id, index), p, v)
        return HttpResponse()

    else:
        return HttpResponseBadRequest()
Example #3
0
def add_organization(request, *args, **kwargs):
    if request.POST:
        data = request.POST
        userform = UserForm(data=data)
        orgform = OrganizationForm(data=data)
        location = {}
        if orgform.is_valid():
            new_organization = orgform.save(commit=False)
            if not request.user == AnonymousUser:
                if userform.is_valid():
                    if userform.cleaned_data['password'] == userform.cleaned_data['passconf']:
                        new_user = User.objects.create_user(
                            userform.cleaned_data['username'],
                            userform.cleaned_data['email'],
                            userform.cleaned_data['password'])
            else:
                new_user = request.user
                try:
                    del_member_class(new_user.member)
                except:
                    pass
            new_organization.leader = new_user.member
            new_organization.save()
            new_organization.save()
            messages.add_message(request, messages.SUCCESS,
                _("Successfully added %(org)s as organization.") % {
                    "org": new_organization.leader.user.username
                }
            )
            return HttpResponseRedirect(new_organization.get_absolute_url())
    else:
        userform = UserForm()
        orgform = OrganizationForm()
    ret = dict(userform=userform, orgform=orgform)
    return render(request, 'verbena/organization/organization_form.html', ret)
Example #4
0
def location(request, loc, format=None):
    '''
	Will one day be a wrapper for all data models, searching over all locations
	and organizations, maybe even people too
	'''
    from campus.models import Building, Location

    try:
        location = Building.objects.get(pk=loc)
    except Building.DoesNotExist:
        try:
            location = Location.objects.get(pk=loc)
        except Location.DoesNotExist:
            raise Http404()

    html = location_html(location, request)
    location = location.json()
    location['info'] = html
    base_url = request.build_absolute_uri('/')[:-1]
    location[
        'marker'] = base_url + settings.MEDIA_URL + 'images/markers/yellow.png'

    if format == 'bubble':
        return render(request, template, context)

    if format == 'json':
        if settings.DEBUG:
            import time
            time.sleep(.5)

        response = HttpResponse(json.dumps(location))
        response['Content-type'] = 'application/json'
        return response

    return home(request, location=location)
Example #5
0
def member_signup(request, *args, **kwargs):
    """
    Signup a new member
    Add the member to a group-type if necessary
    """
    data = request.POST or None
    form = UserForm(data=data)
    mdata = request.FILES or None
    avatar_form = AvatarForm(data, mdata)
    if avatar_form.is_valid() and form.is_valid():
        user = form.save()
        avatar = avatar_form.save()
        user.member.avatar = avatar
        try:
            user.member.save()
            form.login(request, user)
            messages.add_message(request, messages.SUCCESS,
                    _("Successfully added %(member)s as a member.") % {
                        "member": user.username
                    }
                )
            return redirect(user.member.get_absolute_url())
        except:
            return redirect("member_signup")
    ret = dict(form=form,avform=avatar_form)
    return render(request, 'verbena/members/signup.html', ret)
Example #6
0
def regional_campuses(request, campus=None, format=None):
    from campus.models import RegionalCampus

    # TODO - regional campuses API
    if format == 'json':
        response = HttpResponse(
            json.dumps("API not available for Regional Campuses"))
        response['Content-type'] = 'application/json'
        return response

    if format == 'txt':
        response = HttpResponse("API not available for Regional Campuses")
        response['Content-type'] = 'text/plain; charset=utf-8'
        return response

    if campus:
        try:
            rc = RegionalCampus.objects.get(pk=campus)
        except RegionalCampus.DoesNotExist:
            raise Http404()
        else:
            img = rc.img_tag
            rc = rc.json()
            rc['html'] = img + '<a href="%s">More info...</a>' % (
                reverse('regional'))
            return home(request, regional_campus=rc)

    campuses = RegionalCampus.objects.all()
    context = {"campuses": campuses}

    return render(request, 'campus/regional-campuses.djt', context)
Example #7
0
def regional_campuses(request, campus=None, format=None):
	from campus.models import RegionalCampus
	
	# TODO - regional campuses API
	if format == 'json':
		response = HttpResponse(json.dumps("API not available for Regional Campuses"))
		response['Content-type'] = 'application/json'
		return response
	
	if format == 'txt':
		response = HttpResponse("API not available for Regional Campuses")
		response['Content-type'] = 'text/plain; charset=utf-8'
		return response
	
	if campus:
		try:
			rc = RegionalCampus.objects.get(pk=campus)
		except RegionalCampus.DoesNotExist:
			raise Http404()
		else:
			img = rc.img_tag
			rc = rc.json()
			rc['html'] = img + '<a href="%s">More info...</a>' % (reverse('regional'))
			return home(request, regional_campus=rc)
	
	campuses = RegionalCampus.objects.all()
	context = { "campuses": campuses }
	
	return render(request, 'campus/regional-campuses.djt', context)
Example #8
0
def view(request, id):
    index = r.get(id)

    if request.method == 'GET':
        if index is None:
            return redirect('create')
        ctx = {}
        ctx['id'] = id
        ctx['posts'] = []
        for i in range(0, int(index)):
            ctx['posts'].append({
                'timestamp': r.get(timestampkey(id, i)),
                'headers': r.hgetall(headerkey(id, i)),
                'body': r.hgetall(bodykey(id, i)),
            })
        return render(request, 'view.html', ctx)

    elif request.method == 'POST':
        if index is None:
            return HttpResponseBadRequest()
        index = r.incr(id) - 1
        r.set(timestampkey(id, index), datetime.datetime.now())
        for h, v in request.META.iteritems():
            if h in header_whitelist or h.startswith('HTTP_'):
                r.hset(headerkey(id, index), h, unquote(v))
        for p, v in request.POST.iteritems():
            try:
                d = json.loads(v)
                r.hset(bodykey(id, index), p, json.dumps(d, indent=4))
            except ValueError:
                r.hset(bodykey(id, index), p, v)
        return HttpResponse()

    else:
        return HttpResponseBadRequest()
Example #9
0
def add_actiongroup(request, *args, **kwargs):
    """
    Create an action group and set up logged-in user as the leader
    """
    data = request.POST or None
    agform = ActionGroupForm(data=data)
    mdata = request.FILES or None
    avatar_form = AvatarForm(data, mdata)
    if agform.is_valid() and avatar_form.is_valid():
        new_ag = agform.save(commit=False)
        user = request.user.member
        try:
            new_ag.leader = user
##            import pdb; pdb.set_trace()
            portrait = avatar_form.save()
            new_ag.portrait = portrait
            try:
                new_ag.save()
                messages.add_message(request, messages.SUCCESS,
                    _("Successfully added %(ag)s to action groups.") % {
                        "ag": new_ag.title
                    }
                )
                return HttpResponseRedirect(new_ag.get_absolute_url())
            except:
                return HttpResponse(status=500)
        except Member.DoesNotExist:
            return HttpResponse(status=404)
        return HttpResponseRedirect(new_ag.get_absolute_url())
    ret = dict(form=agform, avform=avatar_form)
    return render(request, 'verbena/act_group/actiongroup_form.html', ret)
Example #10
0
def edit_action_group(request, slug, *args, **kwargs):
    data = request.POST or None
    mdata = request.FILES or None
    try:
        ag = ActionGroup.objects.get(slug=slug)
        if ag.leader != request.user.member:
            messages.add_message(request, messages.ERROR,
                _("You do not have permission to edit %(ag)s.") % {
                    "ag": ag.title,
                }
            )
            return HttpResponse(status=403)
    except ActionGroup.DoesNotExist:
        return HttpResponse(status=404)
    avform = AvatarForm(data, mdata, instance=ag.portrait)
    agform = ActionGroupForm(data, instance=ag)
    ret = dict(form=agform, avform=avform)
    if agform.is_valid() and avform.is_valid():
        agform.save(commit=False)
        av = avform.save()
        agform.portrait = av
        ag = agform.save()
        messages.add_message(request, messages.SUCCESS,
                _("Successfully edited %(ag)s.") % {
                    "ag": ag.title,
                }
            )
        return redirect(ag.get_absolute_url())
    return render(request, "verbena/act_group/actiongroup_form.html", ret)
Example #11
0
def search(request, format=None):
	'''
	one day will search over all data available
	'''
	from campus.models import Building
	
	query_string = ''
	bldgs = None
	if ('q' in request.GET) and request.GET['q'].strip():
		query_string = request.GET['q']
		entry_query = get_query(query_string, ['name',])		
		bldgs = Building.objects.filter(entry_query).order_by('name')
		
	if format == 'list':
		''' used with the search ajax '''
		
		if settings.DEBUG:
			# otherwise too many/too fast, gives browser a sad
			import time
			time.sleep(.5)
		
		response = ''
		if len(bldgs) < 1:
			response = '<li><a data-pk="null">No results</a></li>'
			return HttpResponse(response)
		count = 0
		for item in bldgs:
			response += '<li>%s</li>' % (item.link)
			count += 1
			if(count > 9):
				response += '<li class="more"><a href="%s?q=%s" data-pk="more-results">More results &hellip;</a></li>' % (
					reverse('search'), query_string)
				return HttpResponse(response)
		return HttpResponse(response)
	
	if format == 'json':
		def clean(item):
			return {
				'type' : str(item.__class__.__name__),
				'name' : item.name,
				'id'   : item.pk }
		search = {
			"query"   : query_string,
			"results" : map(clean, bldgs)
		}
		response = HttpResponse(json.dumps(search))
		response['Content-type'] = 'application/json'
		return response
	
	from apps.views import phonebook_search
	phonebook = phonebook_search(query_string)
	
	found_entries = {
		'buildings' : bldgs,
		'phonebook' : phonebook['results']
	}
	
	context = {'search':True, 'query':query_string, 'results':found_entries }
	return render(request, 'campus/search.djt', context)
Example #12
0
def search(request, format=None):
    '''
	one day will search over all data available
	'''
    from campus.models import Building

    query_string = ''
    bldgs = None
    if ('q' in request.GET) and request.GET['q'].strip():
        query_string = request.GET['q']
        entry_query = get_query(query_string, [
            'name',
        ])
        bldgs = Building.objects.filter(entry_query).order_by('name')

    if format == 'list':
        ''' used with the search ajax '''

        if settings.DEBUG:
            # otherwise too many/too fast, gives browser a sad
            import time
            time.sleep(.5)

        response = ''
        if len(bldgs) < 1:
            response = '<li><a data-pk="null">No results</a></li>'
            return HttpResponse(response)
        count = 0
        for item in bldgs:
            response += '<li>%s</li>' % (item.link)
            count += 1
            if (count > 9):
                response += '<li class="more"><a href="%s?q=%s" data-pk="more-results">More results &hellip;</a></li>' % (
                    reverse('search'), query_string)
                return HttpResponse(response)
        return HttpResponse(response)

    if format == 'json':

        def clean(item):
            return {
                'type': str(item.__class__.__name__),
                'name': item.name,
                'id': item.pk
            }

        search = {"query": query_string, "results": map(clean, bldgs)}
        response = HttpResponse(json.dumps(search))
        response['Content-type'] = 'application/json'
        return response

    from apps.views import phonebook_search
    phonebook = phonebook_search(query_string)

    found_entries = {'buildings': bldgs, 'phonebook': phonebook['results']}

    context = {'search': True, 'query': query_string, 'results': found_entries}
    return render(request, 'campus/search.djt', context)
Example #13
0
def ev_list(request, *args, **kwargs):
    """
    list all events
    """
    try:
        events = Event.objects.filter(end_date__gte=datetime.datetime.now())
    except Event.DoesNotExist:
        events = {}
    ret = dict(events=events)
    return render(request, 'verbena/events/event_list.html', ret)
Example #14
0
def faculty_detail(request, *args, **kwargs):
    """ A wrapper to see if a faculty member is logged in as themselves """
    is_me = False
    try:
        faculty = Faculty.objects.get(member__slug=kwargs['slug'])
    except Faculty.DoesNotExist:
        return HttpResponse(status=404)
    if faculty.member.user == request.user:
        is_me = True
    ret = dict(is_me=is_me, object=faculty)
    return render(request, 'verbena/members/faculty_detail.html', ret)
Example #15
0
def student_detail(request, *args, **kwargs):
    """ A wrapper to see if a student is logged in as themselves """
    is_me = False
    try:
        student = Student.objects.get(member__slug=kwargs['slug'])
    except Student.DoesNotExist:
        return HttpResponse(status=404)
    if student.member.user == request.user:
        is_me = True
    ret = dict(is_me=is_me, object=student)
    return render(request, 'verbena/members/student_detail.html', ret)
Example #16
0
def organization(request, id, format=None):
	org = get_org(id)
	building = None
	try:
		from campus.models import Building
		building = Building.objects.get(pk=org['bldg_id'])
		from campus.views import location_html
		# TODO: make this a model method
		building_html = location_html(building, request)
	except Building.DoesNotExist:
		pass
	context = {'org': org, 'building':building, 'building_html': building_html }
	return render(request, "pages/organization.djt", context)
Example #17
0
def upload(request, form_class=OriginalForm,
           success=settings.UPLOAD_SUCCESS,
           template_name='cropper/upload.html' 
    ):
    """
    Upload picture to future cropping
    """
    form = form_class(request.POST or None, request.FILES or None)

    if form.is_valid():
        original = form.save()
        return success(request, form, original)

    return render(request, template_name, {
        'form': form,
    })
Example #18
0
def act_detail(request, *args, **kwargs):
    """
        List details for org, show if user is in or not
    """
    is_in = False
    try:
        act = ActionGroup.objects.get(slug=kwargs['slug'])
    except ActionGroup.DoesNotExist:
        return HttpResponse(status=404)
    try:
        member = request.user.member
        if member in act.supporters.all():
            is_in = True
    except AttributeError:
        is_in = False
    ret = dict(object=act, is_in=is_in)
    return render(request, 'verbena/act_group/actiongroup_detail.html', ret)
Example #19
0
def organization(request, id, format=None):
    org = get_org(id)
    building = None
    try:
        from campus.models import Building
        building = Building.objects.get(pk=org['bldg_id'])
        from campus.views import location_html
        # TODO: make this a model method
        building_html = location_html(building, request)
    except Building.DoesNotExist:
        pass
    context = {
        'org': org,
        'building': building,
        'building_html': building_html
    }
    return render(request, "pages/organization.djt", context)
Example #20
0
def dashboard(request):
    "Reporting dashboard."
    today = datetime.date.today()
    report_date = today
    initial = {"report_year": report_date.year, "report_month": report_date.month}
    form = ReportForm(request.GET or None, initial=initial)
    if form.is_valid():
        report_year = form.cleaned_data.get("report_year") or report_date.year
        report_month = form.cleaned_data.get("report_month") or report_date.month
        last_day = calendar.monthrange(report_year, report_month)[1]
        report_date = datetime.date(report_year, report_month, last_day)
    context = {}
    to_date = {
        "messages": messages_by_direction(),
        "users": user_stats(),
        "appointments": appointment_stats(),
        "reminders": reminder_stats(),
    }
    patients = Contact.objects.filter(patient__isnull=False)
    staff = Contact.objects.filter(patient__isnull=True)
    this_month = {
        "messages": messages_by_direction(day=report_date),
        "users": user_stats(day=report_date),
        "patient_messages": messages_by_direction(day=report_date, filters={"contact__in": patients}),
        "staff_messages": messages_by_direction(day=report_date, filters={"contact__in": staff}),
        "other_messages": messages_by_direction(day=report_date, filters={"contact__isnull": True}),
        "appointments": appointment_stats(day=report_date),
        "reminders": reminder_stats(day=report_date),
        "broadcasts": broadcast_stats(day=report_date),
    }
    prev_month = report_date - datetime.timedelta(days=report_date.day + 1)
    last_month = {
        "appointments": appointment_stats(day=prev_month),
        "reminders": reminder_stats(day=prev_month),
        "broadcasts": broadcast_stats(day=prev_month),
        "users": user_stats(day=prev_month),
    }
    context["to_date"] = to_date
    context["this_month"] = this_month
    context["last_month"] = last_month
    context["report_date"] = report_date
    context["report_form"] = form
    return render(request, "reports/dashboard.html", context)
Example #21
0
def buildings(request, format=None):

    from campus.models import Building
    buildings = Building.objects.exclude(googlemap_point__isnull=True)

    if format == 'json':
        arr = []
        for b in buildings:
            arr.append(b.json())
        response = HttpResponse(json.dumps(arr))
        response['Content-type'] = 'application/json'
        return response

    if format == 'kml':
        # helpful:
        # http://code.google.com/apis/kml/documentation/kml_tut.html#network_links

        def flat(l):
            '''
			TODO: move this into an abstract model
			flatten array and create a a list of coordinates separated by a space
			'''
            str = ""
            for i in l:
                if type(i[0]) == type([]):
                    return flat(i)
                else:
                    str += ("%.6f,%.6f ") % (i[0], i[1])
            return str

        for b in buildings:
            if b.poly_coords != None:
                arr = json.loads(b.poly_coords)
                kml_string = flat(arr)
                b.poly_coords = kml_string

        response = render_to_response('api/buildings.kml',
                                      {'buildings': buildings})
        response['Content-type'] = 'application/vnd.google-earth.kml+xml'
        return response

    context = {'buildings': buildings}
    return render(request, 'campus/buildings.djt', context)
Example #22
0
def add_grant(request, *args, **kwargs):
    """
    Add the current user as the applicant for the grant
    """
    if request.POST:
        data = request.POST
        grantform = GrantForm(data=data)
        if grantform.is_valid():
            grant = grantform.save(commit=False)
            grant.applicant = request.user.member
            try:
                grant.save()
            except:
                return HttpResponse(status=500)
            return redirect(grant.get_absolute_url())
    else:
        grantform = GrantForm()
    ret = dict(form=grantform)
    return render(request, 'verbena/grants/grant_form.html', ret)
Example #23
0
def pages(request, page=None, format=None):
	'''
	static pages with API placeholders
	'''
	if format == 'json':
		import json
		response = HttpResponse(json.dumps('Not this page silly!'))
		response['Content-type'] = 'application/json'
		return response
	
	if format == 'txt':
		response = HttpResponse('Not this page silly!')
		response['Content-type'] = 'text/plain; charset=utf-8'
		return response
	
	try:
		return render(request, "pages/%s.djt" % page, { 'page' : page })
	except TemplateDoesNotExist:
		raise Http404()
Example #24
0
def pages(request, page=None, format=None):
    '''
	static pages with API placeholders
	'''
    if format == 'json':
        import json
        response = HttpResponse(json.dumps('Not this page silly!'))
        response['Content-type'] = 'application/json'
        return response

    if format == 'txt':
        response = HttpResponse('Not this page silly!')
        response['Content-type'] = 'text/plain; charset=utf-8'
        return response

    try:
        return render(request, "pages/%s.djt" % page, {'page': page})
    except TemplateDoesNotExist:
        raise Http404()
Example #25
0
def buildings(request, format=None):
	
	from campus.models import Building
	buildings = Building.objects.exclude(googlemap_point__isnull=True)
	
	if format == 'json':
		arr = []
		for b in buildings:
			arr.append(b.json())
		response = HttpResponse(json.dumps(arr))
		response['Content-type'] = 'application/json'
		return response
		
	if format == 'kml':
		# helpful:
		# http://code.google.com/apis/kml/documentation/kml_tut.html#network_links
		
		def flat(l):
			'''
			TODO: move this into an abstract model
			flatten array and create a a list of coordinates separated by a space
			'''
			str = ""
			for i in l:
				if type(i[0]) == type([]):
					return flat(i)
				else:
					str += ("%.6f,%.6f ")  % (i[0], i[1])
			return str
		
		for b in buildings:
			if b.poly_coords != None:
				arr = json.loads(b.poly_coords)
				kml_string = flat(arr)
				b.poly_coords = kml_string
		
		response = render_to_response('api/buildings.kml', { 'buildings':buildings })
		response['Content-type'] = 'application/vnd.google-earth.kml+xml'
		return response
	
	context = { 'buildings' : buildings }
	return render(request, 'campus/buildings.djt', context)
Example #26
0
def add_project(request, *args, **kwargs):
    "Add a project: must be organization"
    if request.POST:
        data = request.POST
        projform = ProjectForm(data=data)
        if projform.is_valid():
            proj = projform.save(commit=False)
            try:
                organization =\
                    Organization.objects.get(leader=request.user.member)
            except Organization.DoesNotExist:
                return HttpResponse(status=403)
            proj.organization = organization
            proj.save()
            return redirect(proj.get_absolute_url())
    else:
        projform = ProjectForm()
    #return create_object(*args, **kwargs)
    ret = dict(form=projform)
    return render(request, 'verbena/arx/arx_form.html', ret)
Example #27
0
def member_avatar_edit(request, *args, **kwargs):
    """
    edit or add an avatar to the member
    """
    data = request.POST or None
    file_data = request.FILES
    form = AvatarForm(data, file_data)
    if form.is_valid():
        member = request.user.member
        member.avatar = form.save()
        try:
            member.save()
            messages.add_message(request, messages.SUCCESS,
                    _("Successfully added an avatar")
                )
            return redirect(member.get_absolute_url())
        except:
            return HttpResponse(status=404)
    ret = dict(form=form)
    return render(request, 'verbena/members/avatar_edit.html', ret)
Example #28
0
def add_event(request, slug, *args, **kwargs):
    data = request.POST or None
    try:
        ag = ActionGroup.objects.get(slug=slug)
    except ActionGroup.DoesNotExist:
        return HttpResponse(status=404)
    evform = EventForm(data=data)
    if evform.is_valid():
        ev = evform.save()
        ag.events.add(ev)
        ag.save()
        messages.add_message(request, messages.SUCCESS,
                _("Successfully added %(event)s to %(ag)s-hosted events.") % {
                    "event": ev.title,
                    "ag": ag.title,
                }
            )
        return redirect(ag.get_absolute_url())
    ret = dict(form=evform)
    return render(request, 'verbena/act_group/actiongroup_form_add_event.html', ret)
Example #29
0
def student_edit(request, *args, **kwargs):
    """ A wrapper to pull up a student and edit them """
    student = Student.objects.get(member__slug=kwargs['slug'])
    is_me = False
    if request.method == 'POST':
        form = StudentForm(request.POST, instance=student)
        if student.member.user == request.user:
            is_me=True
        if form.is_valid():
            new_student = form.save(commit=False)
            if is_me:
                new_student.member = request.user.member
                student.delete()
                new_student.save()
                return redirect(student.get_absolute_url())
            else:
                return HttpResponse(status=403)
    else:
        form = StudentForm(instance=student)
    ret = dict(object=student, form=form, is_me=is_me)
    return render(request, 'verbena/members/student_form.html', ret)
Example #30
0
def crop(request, original_id, form_class=CroppedForm,
         success=settings.CROP_SUCCESS
    ):
    """
    Crop picture and save result into model
    """
    original = get_object_or_404(Original, pk=original_id)
    cropped = None

    form = form_class(request.POST or None, initial={'original': original})

    if form.is_valid():
        cropped = form.save(commit=False)
        cropped.save()
        return success(request, form, original, cropped)

    return render(request, 'cropper/crop.html', {
        'form'     : form,
        'cropped'  : cropped,
        'original' : original,
    })
Example #31
0
def list_all_members(request, *args, **kargs):
    """
    List all of the members
    """
    ##import pdb; pdb.set_trace()
    ##member_list = []
    mems = Member.objects.all()
    #for mem in mems:
    #    member_list.append(mem)
    """
    orgs = Organization.objects.all()
    for org in orgs:
        member_list.append(org)
    students = Student.objects.all()
    for student in students:
        member_list.append(student)
    facultys = Faculty.objects.all()
    for faculty in facultys:
        member_list.append(faculty)
    """
    ret = dict(object_list=mems)
    return render(request, 'verbena/members/member_list.html', ret)
Example #32
0
def crop_success(request, form, original, cropped):
    """
    Default success crop handler
    """
    if request.is_ajax():
        return HttpResponse(
            simplejson.dumps({
                'image': {
                    'url': cropped.image.url,
                    'width': cropped.w,
                    'height': cropped.h,
                }
            }),
            mimetype='application/x-json',
        )

    return render(request, 'cropper/crop.html', {
        'form': form,
        'cropped': cropped,
        'original': original,
    })

    return redirect(original)
Example #33
0
def home(request, format=None, **kwargs):
    '''
	Renders the main google map.
	One thing that seems to be working well so far, json encoding kwargs and
	using as js options for the map, that way other views can call home and
	pass whatever map options are needed
	'''
    from time import time
    date = int(time())

    if format == 'json':
        from campus.templatetags.weather import weather
        campus = {
            "name": "UCF Campus Map",
            "weather": weather(json_request=True)
        }

        response = HttpResponse(json.dumps(campus))
        response['Content-type'] = 'application/json'
        return response

    if format == 'txt':
        from campus.templatetags.weather import weather
        text = u"UCF Campus Map - %s\n%s\n\n# Campus Address\n%s\n\n# Weather\n%s" % (
            request.build_absolute_uri(reverse('home')), "-" * 78,
            "4000 Central Florida Blvd. Orlando, Florida, 32816",
            weather(text_request=True))

        response = HttpResponse(text)
        response['Content-type'] = 'text/plain; charset=utf-8'
        return response

    # points on the map (will have to be extended with more data added)
    if 'points' in kwargs and kwargs['points']:
        from campus.models import Building
        buildings = Building.objects.all()
        points = {}
        for b in buildings:
            b = b.json()
            points[b['number']] = {
                'gpoint': b['googlemap_point'],
                'ipoint': b['illustrated_point']
            }
        '''
		from django.db.models import Q
		q1 = Q(googlemap_point__isnull=True)
		q2 = Q(googlemap_point__exact='')
		q3 = Q(googlemap_point__contains='None')
		q =  (q1 | q2 | q3)
		points = Building.objects.exclude( q )
		
		
		buildings = ["union", "millican"];
		q = Q()
		for name in buildings:
			q = q | Q(name__icontains = name)
		points = Building.objects.filter( q )
		'''
    else:
        points = None

    # urls
    version = 15  # clears google's cache
    # TODO: https://groups.google.com/group/kml-support-getting-started/browse_thread/thread/757295a81285c8c5
    if settings.GOOGLE_CAN_SEE_ME:
        buildings_kml = "%s.kml?v=%s" % (request.build_absolute_uri(
            reverse('buildings')), version)
        sidewalks_kml = "%s.kml?v=%s" % (request.build_absolute_uri(
            reverse('sidewalks')), version)
        parking_kml = "%s.kml?v=%s" % (request.build_absolute_uri(
            reverse('parking')), version)
    else:
        buildings_kml = "%s%s.kml?v=%s" % (settings.GOOGLE_LOOK_HERE,
                                           reverse('buildings'), version)
        sidewalks_kml = "%s%s.kml?v=%s" % (settings.GOOGLE_LOOK_HERE,
                                           reverse('sidewalks'), version)
        parking_kml = "%s%s.kml?v=%s" % (settings.GOOGLE_LOOK_HERE,
                                         reverse('parking'), version)
    loc = "%s.json" % reverse('location', kwargs={'loc': 'foo'})
    loc = loc.replace('foo', '%s')
    kwargs['map'] = 'gmap'
    context = {
        'options': json.dumps(kwargs),
        'points': json.dumps(points),
        'date': date,
        'buildings_kml': buildings_kml,
        'sidewalks_kml': sidewalks_kml,
        'parking_kml': parking_kml,
        'loc_url': loc
    }

    return render(request, 'campus/base.djt', context)
Example #34
0
def organizations(request, format=None):
	context = {'organizations': get_orgs() }
	return render(request, "pages/organizations.djt", context)
Example #35
0
def organizations(request, format=None):
    context = {'organizations': get_orgs()}
    return render(request, "pages/organizations.djt", context)
Example #36
0
def home(request, format=None, **kwargs):
	'''
	Renders the main google map.
	One thing that seems to be working well so far, json encoding kwargs and
	using as js options for the map, that way other views can call home and
	pass whatever map options are needed
	'''
	from time import time
	date = int(time())
		
	if format == 'json':
		from campus.templatetags.weather import weather
		campus = { 
			"name"    : "UCF Campus Map",
			"weather" : weather(json_request=True) 
		}
		
		response = HttpResponse(json.dumps(campus))
		response['Content-type'] = 'application/json'
		return response
	
	if format == 'txt':
		from campus.templatetags.weather import weather
		text = u"UCF Campus Map - %s\n%s\n\n# Campus Address\n%s\n\n# Weather\n%s" % (
				request.build_absolute_uri(reverse('home')),
				"-"*78,
				"4000 Central Florida Blvd. Orlando, Florida, 32816",
				weather(text_request=True))
				
				
		response = HttpResponse(text)
		response['Content-type'] = 'text/plain; charset=utf-8'
		return response
	
	# points on the map (will have to be extended with more data added)
	if 'points' in kwargs and kwargs['points']:
		from campus.models import Building
		buildings = Building.objects.all()
		points = {}
		for b in buildings:
			b = b.json()
			points[b['number']] = { 'gpoint' : b['googlemap_point'], 'ipoint' : b['illustrated_point'] }
		
		'''
		from django.db.models import Q
		q1 = Q(googlemap_point__isnull=True)
		q2 = Q(googlemap_point__exact='')
		q3 = Q(googlemap_point__contains='None')
		q =  (q1 | q2 | q3)
		points = Building.objects.exclude( q )
		
		
		buildings = ["union", "millican"];
		q = Q()
		for name in buildings:
			q = q | Q(name__icontains = name)
		points = Building.objects.filter( q )
		'''
	else:
		points = None
		
	# urls
	version = 15 # clears google's cache
	# TODO: https://groups.google.com/group/kml-support-getting-started/browse_thread/thread/757295a81285c8c5
	if settings.GOOGLE_CAN_SEE_ME:
		buildings_kml = "%s.kml?v=%s" % (request.build_absolute_uri(reverse('buildings')), version)
		sidewalks_kml = "%s.kml?v=%s" % (request.build_absolute_uri(reverse('sidewalks')), version)
		parking_kml   = "%s.kml?v=%s" % (request.build_absolute_uri(reverse('parking')), version)
	else:
		buildings_kml = "%s%s.kml?v=%s" % (settings.GOOGLE_LOOK_HERE, reverse('buildings'), version)
		sidewalks_kml = "%s%s.kml?v=%s" % (settings.GOOGLE_LOOK_HERE, reverse('sidewalks'), version)
		parking_kml    = "%s%s.kml?v=%s" % (settings.GOOGLE_LOOK_HERE, reverse('parking'), version)
	loc = "%s.json" % reverse('location', kwargs={'loc':'foo'})
	loc = loc.replace('foo', '%s')
	kwargs['map'] = 'gmap';
	context = {
		'options'       : json.dumps(kwargs), 
		'points'        : json.dumps(points), 
		'date'          : date,
		'buildings_kml' : buildings_kml,
		'sidewalks_kml' : sidewalks_kml,
		'parking_kml'   : parking_kml,
		'loc_url'       : loc
	}
	
	return render(request, 'campus/base.djt', context)