Beispiel #1
0
def create_event (request):
    if request.method == "POST":
        stuff = request.POST.copy ()
        stuff["submitter"] = request.user
        print "BACON"
        form = EventRegisterForm (request.POST)
        if form.is_valid ():
            event = form.save (commit = False)
            event.submitter = request.user
            """
            event.start = adjust_datetime_to_timezone (event.start, request.user_profile)
            event.end = adjust_datetime_to_timezone (event.end, request.user_profile)
            """
            event.save ()
            return redirect ("event_details", event.id)
        else:
            print 'JLKLJFSDKL'
            context = {
                "form": form,
            }
            return direct_to_template (request, "create_event.html", context)

    elif request.method == "GET":
        context = {
            "form": EventRegisterForm (),
        }
        return direct_to_template (request, "create_event.html", context)

    return HttpResponseBadRequest()
Beispiel #2
0
def json_box(request, manager=None):
    try:
        coords = get_coordinates(request.GET.get('bbox', ''))
    except CoordinateError as e:
        return direct_to_template(request, 'routes/error.html', 
                {'msg' : e.value})
    
    ids = []
    for i in request.GET.get('ids', '').split(','):
        try:
            ids.append(int(i))
        except ValueError:
            pass # ignore

    if not ids:
        return HttpResponse('[]', content_type="text/json")

    ids = ids[:settings.ROUTEMAP_MAX_ROUTES_IN_LIST]

    selquery = """ST_Intersection(st_transform(SetSRID(
                     'BOX3D(%f %f, %f %f)'::Box3d,4326),900913) , geom)
               """ % coords
    ydiff = 10*(coords[3]-coords[1])

    if ydiff > 1:
        selquery = "ST_Simplify(%s, %f)"% (selquery, ydiff*ydiff*ydiff/2)
    selquery = "ST_AsGeoJSON(%s)" % selquery

    qs = manager.filter(id__in=ids).extra(
            select={'way' : selquery}).only('id')
    # print qs.query

    return direct_to_template(request, 'routes/route_box.json',
                              { 'rels' : qs },
                              mimetype="text/html")
Beispiel #3
0
def del_location(request, loc_id):
	import re
	if(request.user.is_authenticated()):
		try:
			location = Location.objects.get(pk=loc_id)
			if(location.user.id == request.user.id):
				err = None
				tag = ''
				old_tag = location.tag
				mus = MovieUser.objects.filter(user = request.user)
				for mu in mus:
					tags = mu.location
					tags_arr = tags.split(',')
					final_tags_arr = []
					for t in tags_arr:
						t = t.strip()
						if(t != '' and t != old_tag):
							final_tags_arr.append(t)
					mu.location = ','.join(final_tags_arr)
					mu.save()
				location.delete()
				return HttpResponseRedirect('/locations/' + str(request.user.id) + '/?info=removed')
			else:
				return direct_to_template(request, 'err_perms.html', {  })
		except:
			return direct_to_template(request, 'err_404.html', {  })
	else:
		return direct_to_template(request, 'login_req.html', { 'next':'/locations/edit/' + loc_id + '/' })
Beispiel #4
0
def api_info(request):
  try:
    user = _validate_and_get_geniuser(request)
  except LoggedInButFailedGetGeniUserError:
    return _show_failed_get_geniuser_page(request)
  
  if request.method == 'GET':
    return direct_to_template(request, 'control/api_info.html',
                              {'username' : user.username,
                               'api_key' : user.api_key,
                               'msg' : ""})

  # This is a POST, so it should be generation of an API key.
  if not request.POST.get('generate_api_key', False):
    msg = "Sorry, we didn't understand your request."
    return direct_to_template(request, 'control/api_info.html',
                              {'username' : user.username,
                               'api_key' : user.api_key,
                               'msg' : msg})
    
  interface.regenerate_api_key(user)
  msg = "Your API key has been regenerated. Your old one will no longer work."
  msg += " You should update any places you are using the API key"
  msg += " (e.g. in programs using the XML-RPC client)."
  return direct_to_template(request, 'control/api_info.html',
                            {'username' : user.username,
                             'api_key' : user.api_key,
                             'msg' : msg})
Beispiel #5
0
def edit_location(request, loc_id):
	import re
	if(request.user.is_authenticated()):
		try:
			location = Location.objects.get(pk=loc_id)
			if(location.user.id == request.user.id):
				err = None
				if(request.POST):
					tag = request.POST['tag']
					if(tag != ''):
						old_tag = location.tag
						mus = MovieUser.objects.filter(user = request.user)
						for mu in mus:
							mu.location = re.sub(old_tag, tag, mu.location)
							mu.save()
						location.tag = tag
						location.save()
						return HttpResponseRedirect('/locations/' + str(request.user.id) + '/?info=modded')
					else:
						err = "You can't leave the location field blank."
				return direct_to_template(request, 'movies/edit_location.html', { 'location':location, 'err':err })
			else:
				return direct_to_template(request, 'err_perms.html', {  })
		except:
			return direct_to_template(request, 'err_404.html', {  })
	else:
		return direct_to_template(request, 'login_req.html', { 'next':'/locations/edit/' + loc_id + '/' })
Beispiel #6
0
def list_vms(request, server_id):

	if (not request.user.is_superuser):
        
		return simple.direct_to_template(request,
						template = 'not_admin.html',
						extra_context = {'user':request.user},
					)
	vmProjects = {}
	vmSlices = {}
	try:
		for vm in VTDriver.getVMsInServer(VTDriver.getServerById(server_id)):
			if vm.projectName not in vmProjects:
				vmProjects[vm.projectName] = vm.projectId
			if vm.sliceName not in vmSlices:
				vmSlices[vm.sliceName] = vm.sliceId
	except Exception as e:
		print e
		pass

	server = get_object_or_404(VTServer, pk=server_id)
			
	context = { 'vmProjects': vmProjects, 'vmSlices': vmSlices,'server':server}

	return simple.direct_to_template(
		request,
		template="servers/servers_list_vms.html",
		extra_context=context,
	)
Beispiel #7
0
def success_checkout(request):
	last = compras_historico_utils.get_last_order_by_user(request.user.email)
	if last == None:
		return direct_to_template(request, 'success_checkout.html', {'no_orders':"XXX"})

	user = page_users_utils.get_user_info(request.user.email)
	
	saldo = user.saldo
	
	if saldo < 0:
		saldo = saldo*-1
		
		###WRONG!!!!
		nice_metodo = "Paypal"
		
		page_users_utils.add_payment_user(request,request.user.email, saldo, nice_metodo,store=True)
		if user.pais == "Portugal":
			return direct_to_template(request, 'success_checkout.html',
				{'order':last,
				'portugal':user.pais,
				'negative_client':saldo,
				'negative_client_conversion':card_database_utils.real_price_by_credits(saldo,user.pais)})
		if user.pais == "Brasil":
			return direct_to_template(request, 'success_checkout.html',
				{'order':last,
				'brasil':user.pais,
				'negative_client':saldo,
				'negative_client_conversion':card_database_utils.real_price_by_credits(saldo,user.pais)})
	
	return direct_to_template(request, 'success_checkout.html',{'order':last})
Beispiel #8
0
def delete_server(request, server_id):

	if (not request.user.is_superuser):
        
		return simple.direct_to_template(request,
				template = 'not_admin.html',
				extra_context = {'user':request.user},
		)
	if request.method == 'POST':
		try:
			VTDriver.deleteServer(VTDriver.getServerById(server_id))
			return HttpResponseRedirect(reverse('dashboard'))

		except Exception as e:
			logging.error(e)
			e = HttpUtils.processException(e)
			return simple.direct_to_template(request,
				template = 'servers/delete_server.html',
				extra_context = {'user':request.user, 'exception':e, 'next':reverse("admin_servers")},
				)	
	elif request.method == 'GET':
		return simple.direct_to_template(request,
				template = 'servers/delete_server.html',
				extra_context = {'user':request.user, 'next':reverse("admin_servers"),'object':VTDriver.getServerById(server_id)},
		)
Beispiel #9
0
def action_vm(request, server_id, vm_id, action):
	if (not request.user.is_superuser):
        
		return simple.direct_to_template(request,
			template = 'not_admin.html',
			extra_context = {'user':request.user},
		)

	if(action == 'list'):
          
		return simple.direct_to_template(
				request, template="servers/server_vm_details.html",
				extra_context={"vm": VTDriver.getVMbyId(vm_id), "server_id":server_id}
		)

	elif(action == 'check_status'):
		#XXX: Do this function if needed
		return simple.direct_to_template(
				request, template="servers/list_vm.html",
				extra_context={"vm": VM.objects.get(id = vm_id)}
		)
        elif(action == 'force_update_server'):
                InformationDispatcher.forceListActiveVMs(serverID=server_id)

        elif(action == 'force_update_vm'):
                InformationDispatcher.forceListActiveVMs(vmID=vm_id)
 
	else:
		#XXX: serverUUID should be passed in a different way
		VTDriver.PropagateActionToProvisioningDispatcher(vm_id, VTServer.objects.get(id=server_id).uuid, action)
    
	#return HttpResponseRedirect(reverse('edit_server', args = [server_id]))
	return HttpResponse("")
Beispiel #10
0
def view_build(request, typename):
    ownerid = request.user.profile.corpid
    corpname = request.user.profile.corp

    t = get_object_or_404(Type, typeName=typename)
    basket = build(ownerid, t)
    if basket is None or len(basket) == 0:
        return direct_to_template(request, 'industry/build_direct.html',
                                  extra_context={
                'tab': 'build',
                'corpname': corpname,
                'typename': t.typeName,
                'totalcost': cost(ownerid, t)})
    components = []
    for type_, quantity in basket.items():
        pu = cost(ownerid, type_)
        components.append((type_, quantity, pu, pu * quantity))
    components.sort(key=lambda x: x[0].typeName)
    totalcost = sum(x[1] * x[2] for x in components)
    return direct_to_template(request, 'industry/build_detail.html',
                              extra_context={
            'tab': 'build',
            'corpname': corpname,
            'typename': t.typeName,
            'component_list': components,
            'totalcost': totalcost,
            'source': basket.note,
            })
Beispiel #11
0
def profile(request, user_id=None):
    user = get_object_or_404(User, pk=user_id)
    all_lessons = user.lessons.all()
    lesson_paginator = Paginator(all_lessons, 16)
    lesson_page = request.GET.get('page')
    try:
        lessons = lesson_paginator.page(lesson_page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        lessons = lesson_paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        lessons = lesson_paginator.page(lesson_paginator.num_pages)

    if request.user.is_authenticated() and user_id in [None, str(request.user.id)]:
        profile = request.user.get_profile()

        if request.method == "POST":
            form = ProfileForm(request.POST, profile=profile)
            if form.is_valid():
                profile = form.save()
                form = ProfileForm(profile=profile)
        else:
            form = ProfileForm(profile=profile)
        cpass_form = PasswordChangeForm(request.user)
        return direct_to_template(request, "profile.html", {"lessons": lessons, "u":user, "form": form, "cpass_form":cpass_form})
    elif request.user.is_anonymous() and user_id is None:
        return HttpResponseRedirect(reverse("account:auth_login"))
    else:
        user = get_object_or_404(User, pk=user_id, profile__professional_chef=True)
        return direct_to_template(request, "chef_profile.html", {"lessons": lessons, "u":user})
Beispiel #12
0
def search(request):

    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            search = form.cleaned_data['search']
            terms = search.split(' ')
            # Exact matches
            artist_list = Artist.objects.filter(name__icontains=search)
            song_list = Song.objects.filter(title__icontains=search)

            # Partial matches
            for term in terms:
                artist_list = artist_list | Artist.objects.filter(
                    name__icontains=term
                    )
                song_list = song_list | Song.objects.filter(
                    title__icontains=term
                    )

            genre_list = Genre.objects.filter(name__icontains=search)
            return direct_to_template(request, template='search/results.html',
                                      extra_context={
                                          'artist_list': artist_list,
                                          'song_list': song_list,
                                          'genre_list': genre_list,
                                          'form': form,
                                          },)
    else:
        form = SearchForm()
    return direct_to_template(request, 'search/search_form.html',
                              {'form': form,})
Beispiel #13
0
def user_change_pw(request, up):
    tn = 'vns/user_change_pw.html'
    is_admin = up.user != request.user
    Form = AdminChangePasswordForm if is_admin else ChangePasswordForm
    if request.method == 'POST':
        form = Form(request.POST)
        if form.is_valid():
            if not is_admin:
                old_pw = form.cleaned_data['old_pw']
            new_pw1 = form.cleaned_data['new_pw1']
            new_pw2 = form.cleaned_data['new_pw2']

            if new_pw1 != new_pw2:
                messages.error(request, "Try again: the two versions of your new password do not match.")
                return direct_to_template(request, tn, { 'form': form, 'un':up.user.username })

            if not is_admin and not authenticate(username=up.user.username, password=old_pw):
                messages.error(request, "Incorrect current password.")
                return direct_to_template(request, tn, { 'form': form, 'un':up.user.username })

            up.user.set_password(new_pw1)
            up.user.save()

            if is_admin:
                messages.success(request, "You have successfully updated %s's password." % up.user.username)
            else:
                messages.success(request, "You have successfully updated your password.")
            return HttpResponseRedirect('/user/%s/' % up.user.username)
    else:
        form = Form()

    return direct_to_template(request, tn, { 'form': form, 'un':up.user.username })
Beispiel #14
0
def doseries(request, serie_pk):
    aantal_deelnemers = models.User.objects.count()
    aantal_antwoorden = models.Antwoord.objects.count()
    gem_antwoorden = aantal_antwoorden / aantal_deelnemers

    serie = models.Serie.objects.get(pk=serie_pk)
    vraag = random.choice(serie.vragen.all())
    # The items that have already been answered
    answered_obj = [x['obj'] for x in request.user.antwoorden.filter(serievraag__serie=serie).values('obj')]
    avail_items = serie.items.exclude(objid__in=answered_obj)

    if avail_items.count() < 1:
        return direct_to_template(request, 'seriescomplete.html', 
                                  {'serie': serie,
                                  'aantal_deelnemers': aantal_deelnemers,
                                  'aantal_antwoorden': aantal_antwoorden,
                                  'gem_antwoorden': gem_antwoorden,    
                                  })
    obj = random.choice(avail_items).obj
    util.update_pic_url(obj)
    antwoorden = request.user.antwoorden.filter(serievraag__serie=serie)

    return direct_to_template(request, 'doseries.html',
                              {'serie': serie,
                               'serievraag': vraag,
                               'vraag': vraag.vraag,
                               'antwoorden': antwoorden,
                               'pagename': 'home',
                               'obj': obj,
                               'aantal_deelnemers': aantal_deelnemers,
                               'aantal_antwoorden': aantal_antwoorden,
                               'gem_antwoorden': gem_antwoorden,
                              })
Beispiel #15
0
def registermethod(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')        

        # Create the user, and set the school in it's profile
        kusername = [x for x in username.lower() if x in 'abcdefghijklmnopqrstuvwxyz']
        kusername = ''.join(kusername)[:30]
        try:
            u = models.User.objects.get(username=kusername)
            return direct_to_template(request, 'register.html', 
                {'schools': models.School.objects.all(),
                 'msg': u'De gebruiker met email: %s bestaat reeds' % username,
                })
        except models.User.DoesNotExist:
            u, created = models.User.objects.get_or_create(username=kusername, 
                                                      email=username)
            u.set_password(password)
            u.save()
        school = request.POST.get('school')
        if school:
            school = models.School.objects.get(pk=school)        
            u_profile = u.get_profile()
            u_profile.school = school
            u_profile.save()

        user = authenticate(username=kusername, password=password)
        login(request, user)
        return HttpResponseRedirect('/')
    return direct_to_template(request, 'register.html', 
                {'schools': models.School.objects.all()})
def profile(request, creator):
    if creator:
        creator = get_object_or_None(Profile, username=creator)

        if not creator:
            return direct_to_template(
                request,
                'profile/does_not_exists.html',
                {
                    'username': creator,
                    'all_users': Profile.objects.all()
                }
            )
    else:
        creator = request.user

    annots = Annotation.objects.filter(
        author=creator,
        deleted=False,
    )
    if request.user.is_authenticated():
        annots = annots.exclude(~Q(author=request.user), private=True)

    return direct_to_template(
        request,
        'profile/profile.html',
        {
            'annotations': annots.filter(type='Comment'),
            'replies': annots.filter(type='Reply'),
            'creator': creator,
            'all_users': User.objects.all()

        }
    )
Beispiel #17
0
def practice_list(request, template='memorize/practice_list.html',
                  paginate_by=None, page=None, allow_empty=True):
    practice_list = Practice.objects.filter(user=request.user)\
        .order_by('next_practice')

    if paginate_by:
        paginator = Paginator(practice_list, paginate_by,
                              allow_empty_first_page=allow_empty)
        if not page:
            page = request.GET.get('page', 1)
        try:
            page_number = int(page)
        except ValueError:
            if page == 'last':
                page_number = paginator.num_pages
            else:
                # Page is not 'last', nor can it be converted to an int.
                raise Http404
        try:
            page_obj = paginator.page(page_number)
        except InvalidPage:
            raise Http404

        return direct_to_template(request, template, {
                'paginator': paginator,
                'page_obj': page_obj,})

    return direct_to_template(request, template, {
            'practice_list': practice_list})
def login(request):
    " Process a login request. "
    vars = {}
    
    # If there is post data - process the form
    if request.POST:
        
        form = LoginForm(data=request.POST)
        if not form.is_valid():
            vars['form'] = form
            return direct_to_template(request, 'login.html', vars)
            
        username = form.cleaned_data['email']
        password = form.cleaned_data['password']
        
        # Try to auth the user
        user = auth.authenticate(username=username, password=password)
        if user is None:
            vars['form'] = form
            vars['error'] = 'Invalid Email and/or Password'
            return direct_to_template(request, 'auth/login.html', vars)
        
        # Log the user in to this session
        auth.login(request, user)
        return HttpResponseRedirect(reverse('sample_project.sample_app.views.clipcloud.profile'))
        
    vars['form'] = LoginForm()
    return direct_to_template(request, 'login.html', vars)
Beispiel #19
0
def subscription_update( req, info_id ) :
	info = MembershipInfo.objects.get(id=info_id)
	if info.user != req.user :
		path = urlquote(req.get_full_path())
		from django.contrib.auth import REDIRECT_FIELD_NAME
		tup = settings.LOGIN_URL, REDIRECT_FIELD_NAME, path
		return HttpResponseRedirect('%s?%s=%s' % tup)

	membership = info.latter_membership()

	if membership.has_expired() :
		return subscription_renew(req, info_id)

	old_email = info.email

	if req.method == 'POST' :
		form = MembershipInfoForm(req.POST, instance=info)
		if form.is_valid() :
			info = form.save()
			if info.user is not None :
				u = info.user
				if u.email != info.email :
					u.email = info.email
					u.save()
			if info.email != old_email :
				MembershipInfoEmailChange.objects.create(old_email=old_email, info=info)
			return direct_to_template(req, "membership/subscription_updated.html", {"membership" : membership})
	else :
		form = MembershipInfoForm(instance=info)

	return direct_to_template(req, "membership/subscription_update.html", 
		{"form": form, "membership": membership})
Beispiel #20
0
def profile_delete(request):

    if not request.POST.has_key('delete'):
        # Extra sanity-check that this is a POST request
        log.error('Received deletion request but was not POST')
        message = _("There was a problem with your request to delete this profile.")
        return direct_to_template(request, 'profile.html', { 'message':message})

    if not request.POST['delete'] == request.user.email:
        # And that we're POSTing from our own form (this is a sanity check, 
        # not a security feature.  The current logged-in user profile is always
        # the one to be deleted, regardless of the value of 'delete')
        log.error('Received deletion request but nickname did not match: received %s but current user is %s' % (request.POST['delete'], request.user.nickname()))
        message = _("There was a problem with your request to delete this profile.")
        return direct_to_template(request, 'profile.html', { 'message':message})

    request.user.get_profile().delete()

    # Delete all their books (this is likely to time out for large numbers of books)
    documents = EpubArchive.objects.filter(user_archive__user=request.user)

    for d in documents:
        _delete_document(request, d)

    return HttpResponseRedirect('/') # fixme: actually log them out here
def signup(request):
    " Process a request for a user to create an account. "
    vars = {}
    
    # If a post, process a signup
    if request.POST:
                
        # Bind and validate the form
        form = SignUpForm(request.POST)
        if not form.is_valid():
            vars['form'] = form
            return direct_to_template(request, 'signup.html', vars)
        
        # Create a new user 
        user = models.User.objects.create_user(
            username=form.cleaned_data['email'], 
            email=form.cleaned_data['email'], 
            password=form.cleaned_data['password']
        )
        # Create a new profile bound to this user
        profile = Profile.objects.create(user=user)
        
        # Attempt to authenticate the user and log them in
        user.backend = "%s.%s" % (backends.ModelBackend.__module__, backends.ModelBackend.__name__)
        auth.login(request, user)
        
        # Redirect user to the profile page
        return HttpResponseRedirect(reverse('sample_project.sample_app.views.clipcloud.profile'))
    
    # If this is NOT a post, simple render the signup form and allow the user to sign up 
    vars['form'] = SignUpForm()
    return direct_to_template(request, 'signup.html', vars)
Beispiel #22
0
def topology_permitted_user_add(request, tid, topo):
    tn = 'vns/topology_add_permitted_user.html'
    APUForm = make_apu_form(request.user, topo)
    if request.method == 'POST':
        form = APUForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['usr']

            try:
                user = db.UserProfile.objects.get(user__username=username, retired=False).user
            except db.UserProfile.DoesNotExist:
                return direct_to_template(request, tn, {'form':form, 'more_error':'invalid username', 'tid':tid})

            if topo.owner == user:
                messages.error(request, 'This topology is already owned by %s.' % username)
                return HttpResponseRedirect('/topology%d/' % tid)

            tuf = db.TopologyUserFilter()
            tuf.topology = topo
            tuf.user = user
            tuf.save()
            messages.success(request, "%s (%s) has been added to the permitted users list." % (username, user.get_full_name()))
            return HttpResponseRedirect('/topology%d/' % tid)
    else:
        form = APUForm()
    return direct_to_template(request, tn, {'form':form, 'tid':tid })
Beispiel #23
0
def dummy_page(request):
    """
        It only makes user login if not logged in and the
        page forwards back to root :meth:`legals_population_survey`

        :url: /pickadish/legals/

    """
    if not request.facebook.check_session(request):
        return direct_to_template(request, 'presurvey/canvas.fbml', extra_context={'appname': APP_NAME})
    else:
        # Get the User object for the currently logged in user
        user = User.objects.get_current()
        logger.debug("Displaying dummy_page with user logged in")

        friends_in_app = request.facebook.friends.getAppUsers()
        logger.debug("Friends that use the app initial: %s"%friends_in_app)
        if len(friends_in_app)>0:
            if len(friends_in_app)>10:
                friends_in_app = random.sample(friends_in_app,10)
            friends = request.facebook.users.getInfo( friends_in_app, ['pic_square'])
        else:
            friends = []
        logger.debug("Friends that use the app after random: %s"%friends)

        # User is guaranteed to be logged in, so pass canvas.fbml
        # an extra 'fbuser' parameter that is the User object for
        # the currently logged in user.
        return direct_to_template(request, 'presurvey/canvas.fbml', extra_context={'fbuser': user, 'friends': friends, 'appname': APP_NAME})
Beispiel #24
0
def object_mover(request):
    """
    Displays and process form for moving objects by their PID to
    a different parent PID

    :param request: Django request
    """
    if request.method == 'POST':
        mover_form = MoverForm(request.POST)
        if mover_form.is_valid():
            collection_pid = mover_form.cleaned_data['collection_pid']
            source_pid = mover_form.cleaned_data['source_pid']
            repository_move(source_pid,collection_pid)
            new_log = RepositoryMovementLog(collection_pid=collection_pid,
                                            source_pid=source_pid)
            new_log.save()
            message = 'PID %s moved to collection PID %s' % (source_pid,
                                                             collection_pid)
            return direct_to_template(request,
                                      'repository/index.html',
                                      {'history': RepositoryMovementLog.objects.all(),
                                       'message':message})
    else:
        mover_form = MoverForm()
    return direct_to_template(request,
                              'repository/index.html',
                              {'history':RepositoryMovementLog.objects.all(),
                               'mover_form':mover_form})
Beispiel #25
0
def cc(request, run_id):
    """
    Operating the test run cc objects, such as add to remove cc from run

    Return: Hash
    """
    tr = get_object_or_404(TestRun, run_id=run_id)

    if request.REQUEST.get('do'):
        if not request.REQUEST.get('user'):
            return direct_to_template(request, 'run/get_cc.html', {
                'test_run': tr,
                'message': 'User name or email is required by this operation'
            })

        try:
            user = User.objects.get(
                Q(username=request.REQUEST['user'])
                | Q(email=request.REQUEST['user'])
            )
        except ObjectDoesNotExist, error:
            return direct_to_template(request, 'run/get_cc.html', {
                'test_run': tr,
                'message': 'The user you typed does not exist in database'
            })
        if request.REQUEST['do'] == 'add':
            tr.add_cc(user=user)

        if request.REQUEST['do'] == 'remove':
            tr.remove_cc(user=user)
Beispiel #26
0
def projects(request, project_id=None, skill_id=None):
    '''View for handling mentorship request category and detail views'''
    if request.method == 'POST':
        note = request.POST['note']
        user = request.user
        project = Project.objects.get(pk=project_id)
        join = JoinRequest.objects.get_or_create(
                project = project,
                added_by = user,
                note = note)
        join.send_notification()
        resp = {'message': 'created'}
        return HttpResponse(json.dumps(resp), mimetype='json')
    if bool(project_id):
        project = get_object_or_404(Project, pk=project_id)
        return direct_to_template(
                request, 'mentorship_detail.html', locals())
    projects = Project.objects.filter(
            closed=False).select_related(
                    'sponsor_set', 'added_by')
    if request.GET.get('my_projects'):
        skill = {'name':'My Projects'}
        projects = projects.filter(added_by=request.user)
    if bool(skill_id):
        skill = Skill.objects.get(pk=skill_id)
        projects = projects.filter(skills=skill)
    skills = Skill.objects.all()
    return direct_to_template(request, 'mentorship_category.html', locals())
Beispiel #27
0
def topologytemplate_create(request):
    """Creates a topology template from the template description that's given"""
    
    tn = 'vns/topologytemplate_create.html'

    if request.method == 'POST':
        form = CreateTopologyTemplateForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            description = form.cleaned_data['description']
            rtable = form.cleaned_data['rtable']
            readme = form.cleaned_data['readme']

            try:
                insert_topologytemplate(description=description, rtable=rtable, readme=readme, user=request.user, template_name=name)
            except (TopologyArgumentError, TopologySyntaxError, TopologyNameError) as err:
                messages.error(request, str(err))
                return direct_to_template(request, tn, {'form':form})

            messages.success(request, "Successfully created topology template")
            return HttpResponseRedirect('/')

        else:
            messages.error(request, "Invalid form - did you forget to fill in the readme and routing table?")
            return HttpResponseRedirect('/')

    else:
        f = CreateTopologyTemplateForm()
        return direct_to_template(request, tn, {'form':f})
Beispiel #28
0
    def validate_payment_form(self):
        payment_form = self.payment_form_class(self.request.POST)
        billing_form = self.billing_form_class(self.request.POST)
        
        if self.shipping_form_class:
            shipping_form = self.shipping_form_class(self.request.POST)

        #if shipping for exists also validate it
        if payment_form.is_valid() and billing_form.is_valid() and (not self.shipping_form_class or shipping_form.is_valid()):
            
            if not self.shipping_form_class:
                args = payment_form, billing_form
            else:
                args = payment_form, billing_form, shipping_form
            
            form_data = combine_form_data(*args)
            response = process_payment(form_data, self.extra_data)
            self.context['response'] = response
            if response.is_approved:
                return direct_to_template(self.request,
                                          self.success_template,
                                          self.context)
            else:
                self.context['errors'] = self.processing_error
        self.context['payment_form'] = payment_form
        self.context['billing_form'] = billing_form
        if self.shipping_form_class:
            self.context['shipping_form'] = shipping_form
        self.context.setdefault('errors', self.form_error)
        return direct_to_template(self.request,
                                  self.payment_template,
                                  self.context)
Beispiel #29
0
def inscribirse(request, slug):
    """Un usuario puede inscribirse a un envento si no se ha inscrito ya,
    está autenticado y el evento está activo"""
    user = request.user
    evento = get_object_or_404(Evento, slug = slug)
    inscripcion = None
    if evento.activo:
        if request.method == 'GET':
            form = InscripcioForm()
        else:
            form = InscripcioForm(request.POST)
            if form.is_valid():
                try:
                    inscripcion = Inscrito.objects.get(user=user, evento = evento)
                    msg = _("Ja estàs inscrit a l'event")
                except Inscrito.DoesNotExist:
                    inscripcion = Inscrito(user=user, evento=evento, 
                                    comentario = form.cleaned_data['comentario'])
                    inscripcion.en_lista_espera = evento.completo
                    inscripcion.save()
                    return redirect('inscripcion-realizada', slug = slug) 
        return direct_to_template(request, 'evento/inscripcion_evento.html', 
                                    {'evento': evento, 'form':form})
    else:
        msg = _("L'event ja està tancat i no admet més inscripcions")
    data = {'msg': msg, 'inscripcion': inscripcion}
    return direct_to_template(request, 'evento/message.html', data)
Beispiel #30
0
def add_bookmark(request):
    """
    This view serves and validates a bookmark form.
    If requested via ajax it also returns the drop bookmark form to replace the 
    add bookmark form.
    """
    if request.method == "POST":
        form = BookmarkForm(user=request.user, data=request.POST)
        if form.is_valid():
            bookmark = form.save()
            if not request.is_ajax():
                request.user.message_set.create(message='Bookmark added')
                if request.POST.get('next'):
                    return HttpResponseRedirect(request.POST.get('next'))
                return HttpResponse('Added')
            return direct_to_template(request, 'admin_tools/menu/remove_bookmark_form.html', {
                'bookmark': bookmark,
                'url': bookmark.url,
            });
    else:
        form = BookmarkForm(user=request.user)
    return direct_to_template(request, 'admin_tools/menu/form.html', {
        'form': form,   
        'title': 'Add Bookmark',
    })
Beispiel #31
0
def donate_instantpaymentnotification(request):
    return direct_to_template(request,
            'texas/donate_instantpaymentnotification.html')
Beispiel #32
0
def contact(request):
    events = Event.objects.filter(occurrence__end_date__gte=datetime.now())
    return direct_to_template(request, 'texas/contact.html', {'events': events})
Beispiel #33
0
def comps(request):
    return direct_to_template(request, 'texas/comps.html')
Beispiel #34
0
def about(request):
    return direct_to_template(request, 'texas/about.html')
Beispiel #35
0
def test(request):
    return direct_to_template(request, 'texas/test.html')
Beispiel #36
0
def view_event(request, event_id):
    events = Event.objects.filter(pk=event_id)
    return direct_to_template(request, 'texas/index.html', {'events': events})
Beispiel #37
0
def do_buy(request, occurrences):
    code = request.POST.get('code', None)
    show = request.GET.get('show', None)
    total_tickets = 0
    ip_address = request.META['REMOTE_ADDR']

    # coupon
    coupon = None
    cou = request.POST.get("coupon", None)
    if cou:
        try:
            coupon = Coupon.objects.get(key=cou)
            if coupon.cap <= coupon.purchaserequest_set.filter(
                    purchase__isnull=True).count() +\
                    coupon.purchase_set.count():
                return direct_to_template(request, 'texas/buy.html',
                        {'occurrences': occurrences,
                        'error': 'Coupon already used!', 'code': code})
        except:
            return direct_to_template(request, 'texas/buy.html',
                    {'occurrences': occurrences,
                    'error': 'Invalid coupon code!', 'code': code})

    purchase_request = None
    for occurrence in occurrences:
        for tier in occurrence.tier_set.all():
            tickets_requested = int(
                    request.POST.get("tickets_%i" % tier.id, 0))
            if tickets_requested > 0:
                if tier.reservation_required:
                    if not request.user.is_authenticated():
                        form = LoginForm()
                        message = "Please log in before purchasing."
                        return direct_to_template(request,
                                'registration/login.html', {'form': form,
                                'message': message})
                    tickets_purchased = Ticket.objects.filter(
                            purchase__user=request.user,
                            tier__occurrence=occurrence,
                            purchase__status='P')
                    tickets_pending = Ticket.objects.filter(
                            purchase__user=request.user,
                            tier__occurrence=occurrence,
                            purchase__status='T',
                            purchase__expiration_date__gt=datetime.now())
                    reservations = Reservation.objects.filter(
                            email=request.user.email, occurrence=occurrence)
                    reservation_count = 0
                    for reservation in reservations:
                        reservation_count += reservation.tickets_granted
                    all_tickets = tickets_purchased.count() + \
                            tickets_pending.count() + tickets_requested
                    if reservation_count < all_tickets:
                        return direct_to_template(request, 'texas/buy.html',
                                {'occurrences': occurrences,
                                'error': 'Reservation required!', 'code': code})
                if tier.password != "":
                    if request.POST.get(
                            "password_%i" % tier.id, "") != tier.password:
                        return direct_to_template(request, 'texas/buy.html',
                                {'occurrences': occurrences,
                                'error': 'Incorrect password!', 'code': code})
                if tier.use_queue and code:
                    if not use_queue_code(code, tickets_requested):
                        return direct_to_template(request, 'texas/error.html',
                                {'message': "Invalid queue code!"})
                if tier.is_lottery and code:
                    if not check_lottery_code(request, code):
                        return direct_to_template(request, 'texas/error.html',
                                {'message': "Invalid queue code!"})
                if tier.price > 0:
                    total_tickets += tickets_requested
                request_date = datetime.now()
                expires = timedelta(minutes=15)
                expiration_date = request_date + expires
                purchase_request = PurchaseRequest(tier=tier,
                        ip_address=ip_address,
                        tickets_requested=tickets_requested,
                        request_date=request_date,
                        expiration_date=expiration_date, coupon=coupon,
                        queue_code=code)
                # add donation if present
                #donation_amount = request.POST.get("donation_%i" % tier.id, "")
                donation_amount = ""
                if donation_amount != "":
                    try:
                        purchase_request.donation_amount =\
                                float(donation_amount)
                    except:
                        pass
                purchase_request.save()
                # add options
                for option in occurrence.options.all():
                    opt = request.POST.get("option_%s" % option.id, None)
                    if opt:
                        purchase_request.options.add(option)

    if total_tickets == 0:
        if purchase_request:
            purchase_request.delete()
        return direct_to_template(request, 'texas/buy.html', {'occurrences':
                occurrences, 'error': 'You have not selected anything!',
                'code': code, 'show': show})
    else:
        # purchases were requested
        if request.user.is_authenticated():
            ip_address = request.META['REMOTE_ADDR']
            do_process_requests(ip_address, request.user)
            return redirect_to(request, '/buy/purchases/')
        else:
            return redirect_to(request, '/buy/requests/')
Beispiel #38
0
def donate_thanks(request):
    return direct_to_template(request, 'texas/donate_thanks.html')
Beispiel #39
0
def user_profile(request):
    return direct_to_template(request, 'registration/profile.html')
Beispiel #40
0
def donate_ohwell(request):
    return direct_to_template(request, 'texas/donate_ohwell.html')
Beispiel #41
0
                    vcf = vobjects.next()
                    if vcf.contents.has_key('email'):
                        contacts.append((vcf.email.value,
                                         vcf.fn.value))

                except Exception, e:
                    print e
                    break


        for (email, name) in contacts:
            sent.append(_send_invite(request.user, email, name))

    return direct_to_template(request, "invite/send.html",
                              dict(send_form=send_form,
                                   import_form=import_form,
                                   sent=sent
                                   ))


def _send_invite(sender, email, name):
    if User.objects(email=email).count():
        return (email, _('User already registered'), False)

    invite = Invite(sender=sender,
                recipient_email=email,
                recipient_name=name)

    invite.save()
    invite.send()
Beispiel #42
0
def amazon_ipn(request):
    return direct_to_template(request, 'texas/paypal_cancel.html')
Beispiel #43
0
def principal(request, data):
    if request.method == 'GET':
        #incluye los parametros del get no va a ignorar el lenguaje (solo se usa para memcache)
        var_full_path = request.get_full_path()
        #incluye hasta la ? y va a ignorar el lenguaje
        var_path = request.path

        leng = re.findall('^(\/leng-)([a-zA-Z]{3})(\/)', var_path)

        if (len(leng) > 0):
            leng = leng[0][1].lower()
            var_path = var_path[9:]
            data = data[9:]
        else:
            leng = LENGUAJE_PRED

        user = users.get_current_user()

        #El usuario no administrativo pasa por memcache
        if not users.is_current_user_admin():
            anterior = memcache.get(var_full_path)
            #if (anterior):
            #    anterior = anterior.replace('__USER__', generarVariablesUsuario(var_full_path, leng), 1)
            #    anterior = anterior.replace('__USER_BASE__', generarVariablesUsuarioBase(var_full_path, leng), 1)
            #    return HttpResponse(anterior, content_type='text/html')

        #Buscar un template valido para la url
        partes = data.split('/')
        archivo = None
        directorio = None
        archivoExistente = None

        if (not data in COMMON_TEMPLATES.keys()):
            for parte in partes:
                #Se elimina la extension
                parte = parte.split('.')[0]
                if (archivo == None):
                    archivo = os.path.join(TEMPLATE_DIRS[0], parte + '.html')
                    directorio = os.path.join(TEMPLATE_DIRS[0], parte)
                else:
                    archivo = os.path.join(directorio, parte + '.html')
                    directorio = os.path.join(directorio, parte)

                if (os.path.isfile(archivo)):
                    archivoExistente = archivo
                    break

            #se valida la direccion
            if (archivoExistente == None):
                archivoExistente = 'index.html'
            tmpl = os.path.join(TEMPLATE_DIRS[0], archivoExistente)
        else:
            if ((COMMON_TEMPLATES[data]['admin']
                 and users.is_current_user_admin())
                    or not COMMON_TEMPLATES[data]['admin']):
                archivo = os.path.join(ROOT_PATH, 'templates/' + data)
                archivoExistente = archivo
                tmpl = archivo
            else:
                archivo = os.path.join(ROOT_PATH, 'templates/403.html')
                archivoExistente = archivo
                tmpl = archivo

        #Se lee el template para saber cuales ids se deben buscar de la base de datos
        llavesEntidades = []
        identificadores = []
        module = __import__('models')

        todo = procesarTemplate(tmpl, var_path, TEMPLATE_DIRS[0])

        for parte in todo['nodos']:
            class_ = getattr(module, parte['tipo'])
            identificadores.append(ndb.Key(class_, parte['id']))

        llavesEntidades = todo['busquedas']

        #Se leen las entidades
        list_of_entities = ndb.get_multi(identificadores)
        dicci = {}
        for entidad in list_of_entities:
            if entidad is not None:
                nombreClase = entidad.__class__.__name__
                if not dicci.has_key(nombreClase):
                    dicci[nombreClase] = {}
                dicci[nombreClase][entidad.key.id()] = entidad.to_dict()

        entidades = {}
        cursores = {}

        data_q = request.GET.get('data-q', None)
        data_next = request.GET.get('data-next', None)

        for llaveEntidad in llavesEntidades:
            objeto_busqueda = simplejson.loads(llaveEntidad)
            if (data_q == llaveEntidad and not data_next == None):
                objeto_busqueda['next'] = data_next
            objeto = comun.buscarGQL(objeto_busqueda)
            entidades[llaveEntidad] = comun.to_dict(objeto['datos'])
            if (objeto.has_key('next')):
                cursores[llaveEntidad] = objeto['next']

        valAnalytics = ''

        if (dicci.has_key('Configuracion')):
            millave = 'analytics_' + leng
            if (dicci['Configuracion'].has_key('/general')
                    and dicci['Configuracion']['/general'].has_key(millave)):
                valor = dicci['Configuracion']['/general'][millave]
                if (not valor is None and len(valor) > 0):
                    valAnalytics = ANALYTICS.replace('$1', valor)

        context = {
            'ANALYTICS': valAnalytics,
            'admin': users.is_current_user_admin(),
            'path': var_path,
            'dicci': dicci,
            'leng': leng,
            'leng_pred': LENGUAJE_PRED,
            'user': user,
            'entidades': entidades,
            'cursores': cursores,
            'JS_COMUNES0': JS_COMUNES0,
            'JS_COMUNES1': JS_COMUNES1,
            'JS_COMUNES2': JS_COMUNES2,
            'JS_COMUNES3': JS_COMUNES3,
            'DATETIME_NOW': comun.DATETIME_NOW,
            'DATETIME_NOW_LAST': comun.DATETIME_NOW_LAST,
            'DATETIME_NOW_FIRST': comun.DATETIME_NOW_FIRST,
            'DATE_NOW': comun.DATE_NOW
        }

        respuesta = direct_to_template(request, archivoExistente, context)

        if not users.is_current_user_admin():
            memcache.set(var_full_path, respuesta.content)

        respuesta.content = respuesta.content.decode('utf-8').replace(
            '__USER__', generarVariablesUsuario(var_full_path, leng), 1)
        respuesta.content = respuesta.content.decode('utf-8').replace(
            '__USER_BASE__', generarVariablesUsuarioBase(var_full_path, leng),
            1)
        return respuesta
Beispiel #44
0
                    password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    ip_address = request.META['REMOTE_ADDR']
                    do_process_requests(ip_address, user)
                    login(request, user)
                    if next_url:
                        return redirect_to(request, next_url)
                    else:
                        return redirect_to(request, '/buy/purchases/')
                else:
                    #return direct_to_template(request, 'registration/inactive_account.html')
                    form = LoginForm()
                    message = "Your account is not active."
                    return direct_to_template(request,
                            'registration/login.html',
                            {'form': form, 'message': message,
                            'next_url': next_url})
            else:
                #return direct_to_template(request, 'registration/invalid_login.html')
                form = LoginForm()
                message = "Invalid credentials."
                return direct_to_template(request, 'registration/login.html',
                        {'form': form, 'message': message,
                         'next_url': next_url})
    else:
        next_url = request.GET.get('next', '')
        form = LoginForm()
        return direct_to_template(request, 'registration/login.html', {'form':
                form, 'next_url': next_url})

def user_confirm(request, user_id, code):
Beispiel #45
0
def index(request, url):
    page = get_object_or_404(Page, url=url)
    return direct_to_template(request, 'minicms/page_detail.html',
        {'page': page})
Beispiel #46
0
def index(request):
    return direct_to_template(request, 'eav/index.html')
Beispiel #47
0
def not_found(request):
    return HttpResponseNotFound(direct_to_template(request, "404.html"))
Beispiel #48
0
def list_person(request):
    return direct_to_template(request, 'list.html', {
        'objects': Person.objects.all(),
        'title': Person._meta.verbose_name,
    })
Beispiel #49
0
def activate(request,
             username,
             activation_key,
             template_name='userena/activate_fail.html',
             success_url=None,
             extra_context=None):
    """
    Activate a user with an activation key.

    The key is a SHA1 string. When the SHA1 is found with an
    :class:`UserenaSignup`, the :class:`User` of that account will be
    activated.  After a successfull activation the view will redirect to
    ``succes_url``.  If the SHA1 is not found, the user will be shown the
    ``template_name`` template displaying a fail message.

    :param username:
        String of the username that wants to be activated.

    :param activation_key:
        String of a SHA1 string of 40 characters long. A SHA1 is always 160bit
        long, with 4 bits per character this makes it --160/4-- 40 characters
        long.

    :param template_name:
        String containing the template name that is used when the
        ``activation_key`` is invalid and the activation failes. Defaults to
        ``userena/activation_fail.html``.

    :param success_url:
        Named URL where the user should be redirected to after a succesfull
        activation. If not specified, will direct to
        ``userena_profile_detail`` view.

    :param extra_context:
        Dictionary containing variables which could be added to the template
        context. Default to an empty dictionary.

    """
    user = UserenaSignup.objects.activate_user(username, activation_key)
    if user:
        # Sign the user in.
        auth_user = authenticate(identification=user.email,
                                 check_password=False)
        login(request, auth_user)

        if userena_settings.USERENA_USE_MESSAGES:
            messages.success(
                request,
                _('Your account has been activated and you have been signed in.'
                  ),
                fail_silently=True)

        if success_url: redirect_to = success_url
        else:
            redirect_to = reverse('userena_profile_detail',
                                  kwargs={'username': user.username})
        return redirect(redirect_to)
    else:
        if not extra_context: extra_context = dict()
        return direct_to_template(request,
                                  template_name,
                                  extra_context=extra_context)
Beispiel #50
0
    categorie = get_object_or_404(Categorie, link=categorie_link)
    # Récupération des différentes publication de la categorie
    try:
        typepub = getattr(models, "Article")
    except AttributeError, e:
        publications = ""
    else:
        publications = typepub.objects.filter(categorie=categorie.id,
                                              online=True)
    # Création du contexte
    contexte = {
        "categorie": categorie,
        "articles": publications,
        "categorie_arbre": Categorie.objects.get_recursives(categorie)
    }
    return direct_to_template(request, 'detail.html', contexte)


def view_publication(request, categorie_link, publication_label):
    cat = Categorie.objects.get(link=categorie_link)
    pub = get_object_or_404(models.Article,
                            label=publication_label,
                            categorie=cat)
    if (pub.auteur.first_name and pub.auteur.last_name):
        auteur = "%s %s" % (pub.auteur.first_name, pub.auteur.last_name)
    else:
        auteur = pub.auteur.username
    if pub.auteur.email:
        auteur = "<a href='mailto:%s' title=\"Contacter l'auteur\">%s</a>" % (
            pub.auteur.email, auteur)
    # Création du contexte
Beispiel #51
0
def password_change(request,
                    username,
                    template_name='userena/password_form.html',
                    pass_form=PasswordChangeForm,
                    success_url=None,
                    extra_context=None):
    """ Change password of user.

    This view is almost a mirror of the view supplied in
    :func:`contrib.auth.views.password_change`, with the minor change that in
    this view we also use the username to change the password. This was needed
    to keep our URLs logical (and REST) accross the entire application. And
    that in a later stadium administrators can also change the users password
    through the web application itself.

    :param username:
        String supplying the username of the user who's password is about to be
        changed.

    :param template_name:
        String of the name of the template that is used to display the password
        change form. Defaults to ``userena/password_form.html``.

    :param pass_form:
        Form used to change password. Default is the form supplied by Django
        itself named ``PasswordChangeForm``.

    :param success_url:
        Named URL that is passed onto a :func:`reverse` function with
        ``username`` of the active user. Defaults to the
        ``userena_password_complete`` URL.

    :param extra_context:
        Dictionary of extra variables that are passed on the the template. The
        ``form`` key is always used by the form supplied by ``pass_form``.

    **Context**

    ``form``
        Form used to change the password.

    """
    user = get_object_or_404(User, username__iexact=username)

    form = pass_form(user=user)

    if request.method == "POST":
        form = pass_form(user=user, data=request.POST)
        if form.is_valid():
            form.save()

            # Send a signal that the password has changed
            userena_signals.password_complete.send(sender=None, user=user)

            if success_url: redirect_to = success_url
            else:
                redirect_to = reverse('userena_password_change_complete',
                                      kwargs={'username': user.username})
            return redirect(redirect_to)

    if not extra_context: extra_context = dict()
    extra_context['form'] = form
    return direct_to_template(request,
                              template_name,
                              extra_context=extra_context)
Beispiel #52
0
def response(request, invite_key, answer='y'):
    """ When an invite is accepted or declined """
    invite = get_object_or_404(Invite, sha=invite_key, response=1)
    invite.response = 2 if answer == "y" else 3
    invite.sha = "ALREADY_USED"
    invite.save()
    # Accepted
    if answer == 'y':
        # User is authenticated, and the user that is asked, than redirect to project
        if request.user.is_authenticated(
        ) and request.user == invite.created_for_user:
            invite.project.members.add(request.user)
            request.user.message_set.create(
                message=_('You have been added to %(project)s.' %
                          {'project': invite.project.name}))
            return HttpResponseRedirect(reverse('project-list'))
        # User is authenticated as a different user
        elif request.user.is_authenticated() and invite.created_for_user:
            invite.project.members.add(invite.created_for_user)
            request.user.message_set.create(message=_(
                '%(username)s has been added to %(project)s. \
                                                      Login as him to go to this project.'
                % {
                    'username': invite.created_for_user.username,
                    'project': invite.project.name
                }))
            logout(request)
            return HttpResponseRedirect(reverse('user_signin'))
        # User is registered but not authenticated
        elif invite.created_for_user:
            invite.project.members.add(invite.created_for_user)
            return HttpResponseRedirect(
                reverse('user_signin') + '?next=%(project_url)s' % {
                    'project_url':
                    reverse('project-detail',
                            kwargs={'slug': invite.project.slug})
                })
        # User is not registered and not authenticated
        else:
            form = RegistrationFormUniqueEmail(
                initial={'email': invite.created_for_email})
            return direct_to_template(request,
                                      template='blinvite/pos_response.html',
                                      extra_context={
                                          'form': form,
                                          'project': invite.project
                                      })

    # User doesn't want to join the project.
    if answer == 'n':
        # User is registered.
        if invite.created_for_user:
            if request.user.is_authenticated():
                request.user.message_set.create(message=_(
                    'You have declined the invitation to %(project)s.' %
                    {'project': invite.project.name}))
                return HttpResponseRedirect(reverse('project-list'))
            else:
                return direct_to_template(
                    request, template='blinvite/neg_reg_response.html')
        # User is not registered.
        else:
            return direct_to_template(
                request, template='blinvite/neg_anon_response.html')
Beispiel #53
0
def signup(request,
           signup_form=SignupForm,
           template_name='userena/signup_form.html',
           success_url=None,
           extra_context=None):
    """
    Signup of an account.

    Signup requiring a username, email and password. After signup a user gets
    an email with an activation link used to activate their account. After
    successful signup redirects to ``success_url``.

    :param signup_form:
        Form that will be used to sign a user. Defaults to userena's
        :class:`SignupForm`.

    :param template_name:
        String containing the template name that will be used to display the
        signup form. Defaults to ``userena/signup_form.html``.

    :param success_url:
        String containing the URI which should be redirected to after a
        successfull signup. If not supplied will redirect to
        ``userena_signup_complete`` view.

    :param extra_context:
        Dictionary containing variables which are added to the template
        context. Defaults to a dictionary with a ``form`` key containing the
        ``signup_form``.

    **Context**

    ``form``
        Form supplied by ``signup_form``.

    """
    # If no usernames are wanted and the default form is used, fallback to the
    # default form that doesn't display to enter the username.
    if userena_settings.USERENA_WITHOUT_USERNAMES and (signup_form
                                                       == SignupForm):
        signup_form = SignupFormOnlyEmail

    form = signup_form()

    if request.method == 'POST':
        form = signup_form(request.POST, request.FILES)
        if form.is_valid():
            user = form.save()

            if success_url: redirect_to = success_url
            else:
                redirect_to = reverse('userena_signup_complete',
                                      kwargs={'username': user.username})

            # A new signed user should logout the old one.
            if request.user.is_authenticated():
                logout(request)
            return redirect(redirect_to)

    if not extra_context: extra_context = dict()
    extra_context['register_form'] = form
    return direct_to_template(request,
                              template_name,
                              extra_context=extra_context)
Beispiel #54
0
def profile_edit(request,
                 username,
                 edit_profile_form=EditProfileForm,
                 template_name='userena/profile_form.html',
                 success_url=None,
                 extra_context=None):
    """
    Edit profile.

    Edits a profile selected by the supplied username. First checks
    permissions if the user is allowed to edit this profile, if denied will
    show a 404. When the profile is succesfully edited will redirect to
    ``success_url``.

    :param username:
        Username of the user which profile should be edited.

    :param edit_profile_form:

        Form that is used to edit the profile. The :func:`EditProfileForm.save`
        method of this form will be called when the form
        :func:`EditProfileForm.is_valid`.  Defaults to :class:`EditProfileForm`
        from userena.

    :param template_name:
        String of the template that is used to render this view. Defaults to
        ``userena/edit_profile_form.html``.

    :param success_url:
        Named URL which be passed on to a django ``reverse`` function after the
        form is successfully saved. Defaults to the ``userena_detail`` url.

    :param extra_context:
        Dictionary containing variables that are passed on to the
        ``template_name`` template.  ``form`` key will always be the form used
        to edit the profile, and the ``profile`` key is always the edited
        profile.

    **Context**

    ``form``
        Form that is used to alter the profile.

    ``profile``
        Instance of the ``Profile`` that is edited.

    """
    user = get_object_or_404(User, username__iexact=username)

    profile = user.get_profile()

    user_initial = {'first_name': user.first_name, 'last_name': user.last_name}

    form = edit_profile_form(instance=profile, initial=user_initial)

    if request.method == 'POST':
        form = edit_profile_form(request.POST,
                                 request.FILES,
                                 instance=profile,
                                 initial=user_initial)

        if form.is_valid():
            profile = form.save()

            if userena_settings.USERENA_USE_MESSAGES:
                messages.success(request,
                                 _('Your profile has been updated.'),
                                 fail_silently=True)

            if success_url: redirect_to = success_url
            else:
                redirect_to = reverse('userena_profile_detail',
                                      kwargs={'username': username})
            return redirect(redirect_to)

    if not extra_context: extra_context = dict()
    extra_context['form'] = form
    extra_context['profile'] = profile
    return direct_to_template(request,
                              template_name,
                              extra_context=extra_context)
def change_request_sent(request):
    """
    Displays a confirmation page with instructions on how to follow the 
    change mail process
    """
    return direct_to_template(request, 'mailchange/change_request_sent.html')
Beispiel #56
0
def email_change(request,
                 username,
                 form=ChangeEmailForm,
                 template_name='userena/email_form.html',
                 success_url=None,
                 extra_context=None):
    """
    Change email address

    :param username:
        String of the username which specifies the current account.

    :param form:
        Form that will be used to change the email address. Defaults to
        :class:`ChangeEmailForm` supplied by userena.

    :param template_name:
        String containing the template to be used to display the email form.
        Defaults to ``userena/email_form.html``.

    :param success_url:
        Named URL where the user will get redirected to when succesfully
        changing their email address.  When not suplied will redirect to
        ``userena_email_complete`` URL.

    :param extra_context:
        Dictionary containing extra variables that can be used to render the
        template. The ``form`` key is always the form supplied by the keyword
        argument ``form`` and the ``user`` key by the user whose email address
        is being changed.

    **Context**

    ``form``
        Form that is used to change the email address supplied by ``form``.

    ``account``
        Instance of the ``Account`` whose email address is about to be changed.

    **Todo**

    Need to have per-object permissions, which enables users with the correct
    permissions to alter the email address of others.

    """
    user = get_object_or_404(User, username__iexact=username)

    form = ChangeEmailForm(user)

    if request.method == 'POST':
        form = ChangeEmailForm(user, request.POST, request.FILES)

        if form.is_valid():
            email_result = form.save()

            if success_url: redirect_to = success_url
            else:
                redirect_to = reverse('userena_email_change_complete',
                                      kwargs={'username': user.username})
            return redirect(redirect_to)

    if not extra_context: extra_context = dict()
    extra_context['form'] = form
    return direct_to_template(request,
                              template_name,
                              extra_context=extra_context)
Beispiel #57
0
def rule_create(request, table_name=None):

    errors = list()
    formMode = request.POST.get("conditionMode")
    tableName = request.POST.get("table")
    PreviousPriority = request.POST.get("ppriority")
    editing = request.POST.get("editing")
    ruleid = request.POST.get("uuid")
    ruleCondition = request.POST.get("condition")
    ruleDesc = request.POST.get("description")
    ruleError = request.POST.get("error_message")
    ruleType = request.POST.get("type")
    ruleAction = request.POST.get("action")
    ruleValue = request.POST.get("value")
    rulePriority = request.POST.get("priority")
    ruleEnable = request.POST.get("enable")
    previousTable = request.POST.get("hidden_name")
    expertRule = request.POST.get("expertRule")
    newConditions = request.POST.get("conditionID")
    saved = request.POST.get("saved")

    if rulePriority == 'Last' or rulePriority == '':
        priority = None
    else:
        priority = int(rulePriority)

    if formMode == "easy":
        #Avoid empty fields
        if ruleDesc == "":
            errors.append("Description Field is empty")
        if ruleError == "":
            errors.append("Error Message field is empty")
        if ruleCondition == "":
            errors.append("Condition field is empty")
        try:
            str(ruleDesc)
        except:
            errors.append(
                "Only ascii characters are allowed in Description field")
        try:
            str(ruleError)
        except:
            errors.append(
                "Only ascii characters are allowed in Error Message field")
        try:
            str(ruleCondition)
        except:
            errors.append("Only ascii characters are allowed in Conditions")

    if request.POST.get("enable") == 'enable':
        enable = True
    else:
        enable = False
    if ruleType == "terminal":
        ruleType = ""

    if saved == None:
        saved = False
    #Rule String convertion required
    if formMode == "easy":
        if ruleAction != "None":
            strings = "if " + ruleCondition + " then " + ruleValue + " " + ruleType + " do " + ruleAction + " denyMessage " + ruleError + " #" + ruleDesc
        else:
            strings = "if " + ruleCondition + " then " + ruleValue + " " + ruleType + " denyMessage " + ruleError + " #" + ruleDesc
    else:
        strings = expertRule
        try:
            str(expertRule)
        except:
            errors.append("Only ascii characters are allowed in a Rule")

    try:
        if errors:
            raise Exception("")

        if editing == '1':
            #Editing Rules Case:
            if previousTable == tableName:
                try:
                    RuleTableManager.editRule(strings, enable, priority,
                                              PreviousPriority, tableName)
                except Exception as e:
                    raise e
            #else:
                #Moving a rule to a different RuleTable --> this is not possible yet
                #print 'Changing table...'
                #RuleTableManager.AddRule(strings,enable,priority,tableName=tableName)
                #print 'successful add to ' + tableName
                #RuleTableManager.RemoveRule(None,int(PreviousPriority),'oldTableName')
                #print 'remove from ' +  previousTable + ' successful'
        else:
            RuleTableManager.AddRule(strings,
                                     enable,
                                     priority,
                                     tableName=tableName)

        return HttpResponseRedirect("/policies")

    except Exception as e:

        errors.append(e)
        errors.insert(
            0, "The Rule cannot be generated. Reason(s):"
        )  #Insterting the main message error in the first position of the table
        priority = RuleTableManager.getPriorityList(tableName)
        actionList = RuleTableManager.SetActionList(
            ruleAction, RuleTableManager.getActionMappings())
        priority = RuleTableManager.getPriorityList(tableName)

        #if a rule index is the last, insert "LAST" in the rule priority instead the true index.
        try:
            int(rulePriority)
            if int(rulePriority) in priority:
                priority.pop(priority.index(int(rulePriority)))
        except:
            rulePriority = "Last"

        if ruleValue == "accept":
            value2 = ["deny"]
        else:
            value2 = ["accept"]

        if ruleType == "nonterminal":
            type2 = ["terminal"]
        else:
            ruleType = "terminal"
            type2 = ["nonterminal"]

        context = {
            'user': request.user,
            'saved': True,
            'CurrentTable': tableName,
            'priority': PreviousPriority,
            'enabled': ruleEnable,
            'load': 'True',
            'valueS': ruleValue,
            'valueD': value2,
            'terminalS': ruleType,
            'terminalD': type2,
            'errorMsg': ruleError,
            'description': ruleDesc,
            'condition': " " + ruleCondition + " ",
            'ptable': tableName,
            'edit': request.POST.get('edit'),
            'action': ruleAction,
            'actionList': actionList[1],
            'PrioritySel': rulePriority,
            'priorityList': priority,
            'allMappings': RuleTableManager.GetResolverMappings(tableName),
            'ConditionMappings': RuleTableManager.getConditionMappings(),
            'ActionMappings': RuleTableManager.getActionMappings(),
            'errors': errors,
            'rule_uuid': ruleid,
        }
        #if ruleid == "":
        return simple.direct_to_template(
            request,
            template='policyEngine/policy_create.html',
            extra_context=context)
Beispiel #58
0
def signin(request,
           auth_form=AuthenticationForm,
           template_name='userena/signin_form.html',
           redirect_field_name=REDIRECT_FIELD_NAME,
           redirect_signin_function=signin_redirect,
           extra_context=None):
    """
    Signin using email or username with password.

    Signs a user in by combining email/username with password. If the
    combination is correct and the user :func:`is_active` the
    :func:`redirect_signin_function` is called with the arguments
    ``REDIRECT_FIELD_NAME`` and an instance of the :class:`User` whois is
    trying the login. The returned value of the function will be the URL that
    is redirected to.

    A user can also select to be remembered for ``USERENA_REMEMBER_DAYS``.

    :param auth_form:
        Form to use for signing the user in. Defaults to the
        :class:`AuthenticationForm` supplied by userena.

    :param template_name:
        String defining the name of the template to use. Defaults to
        ``userena/signin_form.html``.

    :param redirect_field_name:
        Form field name which contains the value for a redirect to the
        successing page. Defaults to ``next`` and is set in
        ``REDIRECT_FIELD_NAME`` setting.

    :param redirect_signin_function:
        Function which handles the redirect. This functions gets the value of
        ``REDIRECT_FIELD_NAME`` and the :class:`User` who has logged in. It
        must return a string which specifies the URI to redirect to.

    :param extra_context:
        A dictionary containing extra variables that should be passed to the
        rendered template. The ``form`` key is always the ``auth_form``.

    **Context**

    ``form``
        Form used for authentication supplied by ``auth_form``.

    """
    form = auth_form

    if request.method == 'POST':
        form = auth_form(request.POST, request.FILES)
        if form.is_valid():
            identification, password, remember_me = (
                form.cleaned_data['identification'],
                form.cleaned_data['password'],
                form.cleaned_data['remember_me'])
            user = authenticate(identification=identification,
                                password=password)
            if user.is_active:
                login(request, user)
                if remember_me:
                    request.session.set_expiry(
                        userena_settings.USERENA_REMEMBER_ME_DAYS[1] * 86400)
                else:
                    request.session.set_expiry(0)

                if userena_settings.USERENA_USE_MESSAGES:
                    messages.success(request,
                                     _('You have been signed in.'),
                                     fail_silently=True)

                # Whereto now?
                redirect_to = redirect_signin_function(
                    request.REQUEST.get(redirect_field_name), user)
                return redirect(redirect_to)
            else:
                return redirect(
                    reverse('userena_disabled',
                            kwargs={'username': user.username}))

    if not extra_context: extra_context = dict()
    extra_context['form'] = form
    return direct_to_template(request,
                              template_name,
                              extra_context=extra_context)
Beispiel #59
0
def rule_edit(request, table_name, rule_uuid, context=None):

    load = request.POST.get('load')
    if not load == 'True':
        rule = RuleTableManager.getRuleOrIndexOrIsEnabled(
            rule_uuid, 'Rule', table_name)
        rulevalues = RuleTableManager.getValue(rule)
        ruletypes = RuleTableManager.getType(rule)
        #Flag to be able to diferenciate edit state from creating estate
        edit = True
        actionList = RuleTableManager.SetActionList(
            rule, RuleTableManager.getActionMappings())
        priorityList = RuleTableManager.SetPriorityList(rule, table_name)
        error = str(rule.getErrorMsg())
        description = str(rule.getDescription())

        return simple.direct_to_template(
            request,
            template='policyEngine/policy_create.html',
            extra_context={
                'user':
                request.user,
                'edit':
                edit,
                'rule':
                rule,
                'priority':
                RuleTableManager.getRuleOrIndexOrIsEnabled(
                    rule_uuid, 'Index', table_name),
                'enabled':
                RuleTableManager.getRuleOrIndexOrIsEnabled(
                    rule_uuid, 'Enabled', table_name),
                'valueS':
                rulevalues[0],
                'valueD':
                rulevalues[1],
                'terminalS':
                ruletypes[0],
                'terminalD':
                ruletypes[1],
                'rule_uuid':
                rule_uuid,
                'ptable':
                table_name,
                'errorMsg':
                error,
                'description':
                description,
                'condition':
                rule.getConditionDump(),
                'action':
                actionList[0],
                'actionList':
                actionList[1],
                'PrioritySel':
                priorityList[0],
                'priorityList':
                priorityList[1],
                'allMappings':
                RuleTableManager.GetResolverMappings(),
                'ConditionMappings':
                RuleTableManager.getConditionMappings(),
                'ActionMappings':
                RuleTableManager.getActionMappings(),
                'CurrentTable':
                table_name
            },
        )
    else:
        return rule_create(request, table_name)
Beispiel #60
0
def list_question_media(request):
    # Handle file upload
    context = {}
    documents = []

    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            docfile = request.FILES['docfile']
            question_id = form.cleaned_data['question_id']

            question = Question.objects.get(id=question_id)
            docfile_name = docfile.name
            docfile_name_changed = docfile_name.replace('.','~^~')
            question.docs.update({docfile_name_changed:docfile.content_type})
            question.image.update({docfile_name_changed +'_url':'/static/display/s_'+docfile_name, docfile_name_changed +'_name': docfile_name, docfile_name_changed +'_content_type':docfile.content_type})
            file_read = docfile.file.read()
            file_data = base64.b64encode(file_read)
            question.image.update({docfile_name_changed +'_data': file_data})
            # question.save()
            nq = Question(
                user = question.user,
                date = question.date,
                question = question.question,
                docs = question.docs,
                image = question.image,
                audio = question.audio,
                other = question.other,
                vote_ids = question.vote_ids,
            )
            question.delete() # todo - there is an update issue here
            nq.save()

            questions = Question.objects.all()
            return render_to_response('question/home.html', {'questions':questions, 'the_user': request.user, 'message': 'Media updated!' })

            # Redirect to the document list after POST
            # return HttpResponseRedirect(reverse('data.views.list_question_media'))
    else:
        if 'q' in request.GET:
            question_id = request.GET['q']
            form = DocumentForm({ 'question_id':question_id,}, hide_condition=True)
            question = Question.objects.get(id=question_id)
            documents = []
            for docname in question.docs:
                file_data = question.image[docname+'_data']
                file_name = question.image[docname+'_name']
                orig_fname = settings.STATIC_ROOT + '/../moma_example/static/display/' + file_name
                new_fname = settings.STATIC_ROOT + '/../moma_example/static/display/tn_' + file_name
                _decode_image_to_size(file_data, orig_fname, new_fname, basewidth=128)
                documents.append({'docfile':{'url':question.image[docname +'_url'], 'name':question.image[docname+'_name'], 'thumb':'/static/display/tn_'+question.image[docname+'_name']}})
            context.update({'q': question_id, 'question':question})

    # Load documents for the list page
    # documents = [{'docfile':{'url':'blaaa', 'name':'Bleee'}}]

    context.update( {'documents': documents, 'form': form,})
    context.update(csrf(request))
    context.update({'the_user': request.user})

    return direct_to_template(request, 'question/question_media.html', context)