def latest(request, format=None): c = Context(request, posts=posts.get_list(listed__exact=True, limit=5, order_by=['-posted'])) if format == 'atom': t = template_loader.get_template('blog/atom.xml') ct = atom_content_type else: t = template_loader.get_template('blog/latest') ct = None return HttpResponse(t.render(c), ct)
def sendPaymentEmails(pmt, request): d = {'pmt': pmt} t = template_loader.get_template('emailPmtSent.txt') c = RequestContext(request, d) sendEmail("Payment confirmation", t.render(c), pmt.payer_email) t = template_loader.get_template('emailPmtReceived.txt') c = RequestContext(request, d) sendEmail("Payment received", t.render(c), pmt.recipient_email)
def sendPaymentEmails(pmt, request): d = {'pmt':pmt} t = template_loader.get_template('emailPmtSent.txt') c = RequestContext(request, d) sendEmail("Payment confirmation", t.render(c), pmt.payer_email) t = template_loader.get_template('emailPmtReceived.txt') c = RequestContext(request, d) sendEmail("Payment received", t.render(c), pmt.recipient_email)
def g(request, *args): format = request.GET.get('format', None) isAlphaNumeric(format, None) ct = format_content_types.get(format, None) if format: t = template_loader.get_template(template_name + '.' + format) else: t = template_loader.get_template(template_name) c = f(request, *args) return HttpResponse(t.render(c), ct)
def tag_posts(request, slug, format=None, limit=None): try: category = categories.get_object(slug__exact=slug) except categories.CategoryDoesNotExist: raise Http404 c = Context(request, tag=category, posts=category.get_listed_post_list(order_by=['-posted'], limit=limit)) if format == 'atom': t = template_loader.get_template('blog/atom.xml') ct = atom_content_type else: t = template_loader.get_template('blog/tag-posts') ct = None return HttpResponse(t.render(c), ct)
def insight(request): t = template_loader.get_template('webstart/insight.xml') codebase = request.build_absolute_uri(settings.STATIC_URL+'webstart/jars/') href = request.build_absolute_uri(reverse("webstart_insight")) pattern = os.path.abspath(os.path.join(settings.OMERO_HOME, "lib", "insight", "*.jar").replace('\\','/')) jarlist = glob(pattern) jarlist = [os.path.basename(x) for x in jarlist] # ticket:9478 put insight jar at the start of the list if available # This can be configured via omero.web.webstart_jar to point to a # custom value. idx = jarlist.index(settings.WEBSTART_JAR) if idx > 0: jarlist.pop(idx) jarlist.insert(0, settings.WEBSTART_JAR) context = {'codebase': codebase, 'href': href, 'jarlist': jarlist, 'icon': settings.WEBSTART_ICON, 'heap': settings.WEBSTART_HEAP, 'host': settings.WEBSTART_HOST, 'port': settings.WEBSTART_PORT, 'class': settings.WEBSTART_CLASS, 'title': settings.WEBSTART_TITLE, 'vendor': settings.WEBSTART_VENDOR, 'homepage': settings.WEBSTART_HOMEPAGE, } c = Context(request, context) return HttpResponse(t.render(c), content_type="application/x-java-jnlp-file")
def cancelPayment(request, pmtId): userNode = checkLogin(request) if not userNode: return HttpResponseRedirect('/login/?redirect=%s' % request.path) if not Payment.objects.filter(pk=pmtId).count() > 0: return HttpResponseRedirect('/payments/') pmt = Payment.objects.get(pk=pmtId) if pmt.payer_id != userNode.id: return HttpResponseRedirect('/payments/') if pmt.status not in ('RQ', 'PE'): # requested, pending return HttpResponseRedirect('/payments/') if pmt.status == 'RQ': pmt.status = 'RF' # refused # *** todo: Send refusal email to requester. t = template_loader.get_template('emailPmtRequestRefused.txt') c = RequestContext(request, {'req': pmt}) sendEmail("Payment request refusal notification", t.render(c), pmt.recipient.getPrimaryEmail()) else: pmt.status = 'CA' # cancelled pmt.save() request.session['infos'] = ["Payment cancelled."] return HttpResponseRedirect('/payments/')
def wrapper(request, *args, **kwargs): """ Wrapper calls the view function, processes the result and returns HttpResponse """ # call the view function itself... context = f(request, *args, **kwargs) # if we happen to have a Response, return it if isinstance(context, HttpResponse): return context # get template from view dict. Can be overridden from the **kwargs template = 'template' in context and context['template'] or None template = kwargs.get('template', template) logger.debug("Rendering template: %s" % template) # allows us to return the dict as json (NB: BlitzGateway objects don't serialize) if template is None or template == 'json': json_data = simplejson.dumps(context) return HttpResponse(json_data, mimetype='application/javascript') else: # allow additional processing of context dict ctx.prepare_context(request, context, *args, **kwargs) t = template_loader.get_template(template) c = RequestContext(request, context) return HttpResponse(t.render(c))
def send_comment(request): error = None form = CommentForm() if request.method == "POST": form = CommentForm(data=request.REQUEST.copy()) if form.is_valid(): comment = request.REQUEST['comment'] email = None if request.REQUEST['email'] is not None or request.REQUEST['email'] != "": email = request.REQUEST['email'] try: sf = SendFeedback() sf.give_comment(comment, email) except: logger.error('handler500: Feedback could not be sent') logger.error(traceback.format_exc()) error = "Feedback could not been sent. Please contact administrator." else: return HttpResponseRedirect(reverse("fthanks")) context = {'form':form, 'error':error} t = template_loader.get_template('comment.html') c = RequestContext(request, context) return HttpResponse(t.render(c))
def create(request, year, month, day): manipulator = events.AddManipulator() # Handle POSTs uphere (unless they contain errors). if request.POST: new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if not errors: manipulator.do_html2python(new_data) event = manipulator.save(new_data) return HttpResponseRedirect(event.get_absolute_url()) else: errors, new_data = {}, {} # A fresh GET or a POST with errors, falls through here. # Fetch start_date and end_date defaults from URL. try: year = int(year) month = int(month) day = int(day) start_date = end_date = datetime.date(year, month, day) except ValueError: raise Http404 new_data['start_date'] = start_date new_data['end_date'] = end_date # Send back a create form. form = formfields.FormWrapper(manipulator, new_data, errors) t = template_loader.get_template('calendar/create') c = Context(request, { 'form': form, }) return HttpResponse(t.render(c))
def forgotPassword(request): errors = [] if request.method == 'POST': email = request.POST['email'] if not isEmail(email): errors.append("%s does not appear to be a valid email address. Please try again." % escape(email)) if not errors: if EmailAddr.objects.filter(email=email).count() > 0: emailAddr = EmailAddr.objects.get(email=email) code = makeReminderCode() t = template_loader.get_template('emailForgotPassword.txt') c = RequestContext(request, {'email':email, 'code':code}) if sendEmail('How to reset your password', t.render(c), email): node = emailAddr.node existingReminders = node.reminder_set.all() for reminder in existingReminders: reminder.delete() # only one oustanding reminder per node allowed newReminder = Reminder(node=emailAddr.node, code=code) newReminder.save() else: errors.append("Could not send email to %s. Please verify the email address and try again." % escape(email)) else: # email address not in system pass # pretend like we're sending a reminder anyways, so no one knows whether an email is registered or not if not errors: return HttpResponseRedirect('/passwordReminderSent/') d = {} d['infos'] = errors return render_to_response('forgotPassword.html', d, context_instance=RequestContext(request))
def send_comment(request): error = None form = CommentForm() if request.method == "POST": form = CommentForm(data=request.REQUEST.copy()) if form.is_valid(): comment = request.REQUEST['comment'] email = None if request.REQUEST['email'] is not None or request.REQUEST['email'] != "": email = request.REQUEST['email'] try: sf = SendFeedback() sf.give_comment(comment, email) except: logger.error('handler500: Feedback could not be sent') logger.error(traceback.format_exc()) error = "Feedback could not been sent. Please contact administrator." else: return HttpResponseRedirect(reverse("fthanks")) context = {'form':form, 'error':error} t = template_loader.get_template('comment.html') c = Context(request, context) return HttpResponse(t.render(c))
def send_feedback(request): error = None form = ErrorForm(data=request.REQUEST.copy()) if form.is_valid(): error = request.REQUEST['error'] comment = None if request.REQUEST.get('comment',None) is not None and request.REQUEST['comment'] != "": comment = request.REQUEST['comment'] email = None if request.REQUEST.get('email', None) is not None and request.REQUEST['email'] != "": email = request.REQUEST['email'] try: sf = SendFeedback() sf.give_feedback(error, comment, email) except: logger.error('handler500: Feedback could not be sent') logger.error(traceback.format_exc()) error = "Feedback could not been sent. Please contact administrator." fileObj = open(("%s/error500-%s.html" % (settings.LOGDIR, datetime.datetime.now())),"w") try: try: fileObj.write(request.REQUEST['error']) except: logger.error('handler500: Error could not be saved.') logger.error(traceback.format_exc()) finally: fileObj.close() return HttpResponseRedirect(reverse("fthanks")) context = {'form':form, 'error':error} t = template_loader.get_template('500.html') c = Context(request, context) return HttpResponse(t.render(c))
def flatpage(request, url): """ Flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.startswith('/'): url = "/" + url f = get_object_or_404(flatpages, url__exact=url, sites__id__exact=SITE_ID) # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and request.user.is_anonymous(): from django.views.auth.login import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = template_loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = template_loader.get_template(DEFAULT_TEMPLATE) c = DjangoContext(request, { 'flatpage': f, }) return HttpResponse(t.render(c))
def archive_month(request, year, month): c = Context(request, date=datetime.date(int(year), int(month), 1), posts=posts.get_list(listed__exact=True, posted__year=int(year), posted__month=int(month), order_by=['posted'])) t = template_loader.get_template('blog/archive-month') return HttpResponse(t.render(c))
def accountAction(request, acctId, action): userNode = checkLogin(request) if not userNode: return HttpResponseRedirect('/accounts/%s/' % acctId) if request.method == 'POST': if request.POST['submit'] == 'Cancel': return HttpResponseRedirect('/accounts/%s/' % acctId) if Account.objects.filter(pk=acctId).count() == 0: return HttpResponseRedirect('/accounts/') acct = Account.objects.get(pk=acctId) if acct.owner_id != userNode.id: return HttpResponseRedirect('/accounts/') if action == 'close': sharedData = acct.shared_data if abs(sharedData.balance) >= 0.005: request.session['infos'] = ["Account balance must be zero before it can be closed."] return HttpResponseRedirect('/accounts/%d/' % acct.id) # to be sure a transaction doesn't hit this account before it gets # deactivated, set limits to zero, save, and then check for zero balance again myIOULimit = acct.iou_limit partnerAcct = acct.get_partner_acct() partnerIOULimit = partnerAcct.iou_limit acct.iou_limit = 0.0 acct.save() partnerAcct.iou_limit = 0.0 partnerAcct.save() if abs(sharedData.balance) >= 0.005: request.session['infos'] = ["Account balance must be zero before it can be closed."] # restore limits on accts acct.iou_limit = myIOULimit acct.save() partnerAcct.iou_limit = partnerIOULimit partnerAcct.save() return HttpResponseRedirect('/accounts/%d/' % acct.id) # now it's impossible for a transaction to change the balance, and the balance is zero, so: sharedData.active = False sharedData.save() # notify user request.session['infos'] = ["Account %d (%s) closed." % (sharedData.id, acct.name)] # notify partner by email note = '' if request.method == 'POST': note = request.POST['note'] t = template_loader.get_template('emailAcctClosed.txt') c = RequestContext(request, {'acct':partnerAcct, 'note':note}) sendEmail("One of your accounts has been closed", t.render(c), acct.partner.getPrimaryEmail()) pass return HttpResponseRedirect('/accounts/')
def accept_proposed_rate(request, shared_data): # this is node_to_confirm's account acct = Account.objects.get(shared_data=shared_data, owner__pk=shared_data.node_to_confirm_id) pmt = None if acct.getBalance( ) and shared_data.interest_rate: # otherwise no update necessary pmt = Payment(payer=acct.owner, payer_email=acct.owner.getPrimaryEmail(), recipient=acct.partner, recipient_email=acct.partner.getPrimaryEmail(), currency=shared_data.currency, amount=0.0, status='PE', description='Interest rate change: %s%% to %s%%.' % \ (shared_data.displayRate(), shared_data.displayProposedRate())) pmt.save() # set pmt time #pmt = Payment.objects.get(pk=pmt.id) # reload because django doesn't update date that is auto-set on save interest = computeInterest(acct.getBalance(), shared_data.interest_rate, shared_data.last_update, pmt.date) path = PaymentPath(payment=pmt, amount=pmt.amount) path.save() link = PaymentLink(path=path, payer_account=acct, position=1, amount=pmt.amount, interest=-interest, interest_rate=shared_data.interest_rate) link.save() shared_data.balance += interest * acct.balance_multiplier if pmt: shared_data.last_update = pmt.date else: shared_data.last_update = datetime.datetime.now() shared_data.interest_rate = shared_data.proposed_rate shared_data.proposed_rate = None shared_data.node_to_confirm_id = None shared_data.save() if pmt: # could do this initially now that this is wrapped in a transaction pmt.status = 'OK' pmt.save() t = template_loader.get_template('emailAcceptRateProposal.txt') c = RequestContext(request, {'acct': acct.get_partner_acct()}) sendEmail("Interest rate proposal accepted", t.render(c), acct.partner.getPrimaryEmail())
def index(request): """ Not used """ t = template_loader.get_template('register/index') c = Context(request, {'ads':extract(), 'mn': menu_items, }) return HttpResponse(t.render(c))
def object_detail(request, year, month, day, app_label, module_name, date_field, month_format='%b', day_format='%d', object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=template_loader, extra_lookup_kwargs={}, extra_context={}): """ Generic detail view from year/month/day/slug or year/month/day/id structure. Templates: ``<app_label>/<module_name>_detail`` Context: object: the object to be detailed """ try: date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3]) except ValueError: raise Http404 mod = get_module(app_label, module_name) now = datetime.datetime.now() lookup_kwargs = { '%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max)), } # Only bother to check current date if the date isn't in the past. if date >= now.date(): lookup_kwargs['%s__lte' % date_field] = now if object_id: lookup_kwargs['%s__exact' % mod.Klass._meta.pk.name] = object_id elif slug and slug_field: lookup_kwargs['%s__exact' % slug_field] = slug else: raise AttributeError("Generic detail view must be called with either an object_id or a slug/slugfield") lookup_kwargs.update(extra_lookup_kwargs) try: object = mod.get_object(**lookup_kwargs) except ObjectDoesNotExist: raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs)) if not template_name: template_name = "%s/%s_detail" % (app_label, module_name) if template_name_field: template_name_list = [getattr(object, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = Context(request, { 'object': object, }) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value response = HttpResponse(t.render(c)) populate_xheaders(request, response, app_label, module_name, getattr(object, object._meta.pk.name)) return response
def reject_proposed_rate(request, shared_data): proposed_rate = shared_data.proposed_rate * 100.0 partner_acct = Account.objects.exclude(owner__pk=shared_data.node_to_confirm_id).get(shared_data=shared_data) shared_data.proposed_rate = None shared_data.node_to_confirm_id = None shared_data.save() t = template_loader.get_template('emailRejectRateProposal.txt') c = RequestContext(request, {'acct': partner_acct, 'proposed_rate': proposed_rate}) sendEmail("Interest rate proposal not accepted", t.render(c), partner_acct.owner.getPrimaryEmail())
def propose_rate(request, shared_data, interest_rate, node_to_confirm): acct_to_confirm = Account.objects.get(shared_data=shared_data, owner=node_to_confirm) shared_data.proposed_rate = interest_rate shared_data.node_to_confirm_id = node_to_confirm.id shared_data.save() t = template_loader.get_template('emailInterestRateProposal.txt') c = RequestContext(request, {'acct': acct_to_confirm}) if sendEmail("Interest rate proposal", t.render(c), node_to_confirm.getPrimaryEmail(), attempts=2): return "Your partner has been notified of your proposed rate change." else: return "Your rate proposal has been recorded, however, the system could not send an email notifying them. Please contact them manually."
def insight(request): t = template_loader.get_template('webstart/insight.xml') codebase = request.build_absolute_uri(settings.STATIC_URL+'webstart/jars/') href = request.build_absolute_uri(reverse("webstart_insight")) pattern = os.path.abspath(os.path.join(settings.OMERO_HOME, "lib", "insight", "*.jar").replace('\\','/')) jarlist = glob(pattern) jarlist = [os.path.basename(x) for x in jarlist] context = {'codebase': codebase, 'href': href, 'jarlist': jarlist} c = Context(request, context) return HttpResponse(t.render(c), content_type="application/x-java-jnlp-file")
def dutyroster(request): """ Shows attendance status for employees """ list = persons.get_list() t = template_loader.get_template('register/officials') c = Context(request, {'list':list, 'ads':extract(), 'mn': menu_items, }) return HttpResponse(t.render(c))
def post(request, year, month, day, slug): try: p = posts.get_object(posted__year=int(year), posted__month=int(month), posted__day=int(day), slug__exact=slug) except posts.PostDoesNotExist: raise Http404() c = Context(request, post=p) t = template_loader.get_template('blog/post') return HttpResponse(t.render(c))
def custom_server_error(request, error500): """ Custom 500 error handler. Templates: `500.html` Context: ErrorForm """ form = ErrorForm(initial={'error':error500}) context = {'form':form} t = template_loader.get_template('500.html') c = Context(request, context) return HttpResponse(t.render(c))
def custom_server_error(request, error500): """ Custom 500 error handler. Templates: `500.html` Context: ErrorForm """ form = ErrorForm(initial={'error':error500}) context = {'form':form} t = template_loader.get_template('500.html') c = RequestContext(request, context) return HttpResponse(t.render(c))
def fac(request,type): """ View for display of the documentation generates all pages on the fly """ list = facilitys.get_list(type__exact=type,) t = template_loader.get_template('register/fac') c = Context(request, {'list':list,'tp':type, 'ads':extract(), 'mn': menu_items, }) return HttpResponse(t.render(c))
def archive_month(request, year, month, app_label, module_name, date_field, month_format='%b', template_name=None, template_loader=template_loader, extra_lookup_kwargs={}, extra_context={}): """ Generic monthly archive view. Templates: ``<app_label>/<module_name>_archive_month`` Context: month: this month object_list: list of objects published in the given month """ try: date = datetime.date(*time.strptime(year+month, '%Y'+month_format)[:3]) except ValueError: raise Http404 mod = get_module(app_label, module_name) now = datetime.datetime.now() # Calculate first and last day of month, for use in a date-range lookup. first_day = date.replace(day=1) last_day = date for i in (31, 30, 29, 28): try: last_day = last_day.replace(day=i) except ValueError: continue else: break lookup_kwargs = {'%s__range' % date_field: (first_day, last_day)} # Only bother to check current date if the month isn't in the past. if last_day >= now.date(): lookup_kwargs['%s__lte' % date_field] = now lookup_kwargs.update(extra_lookup_kwargs) object_list = mod.get_list(**lookup_kwargs) if not object_list: raise Http404 if not template_name: template_name = "%s/%s_archive_month" % (app_label, module_name) t = template_loader.get_template(template_name) c = Context(request, { 'object_list': object_list, 'month': date, }) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c))
def archive_day(request, year, month, day, app_label, module_name, date_field, month_format='%b', day_format='%d', template_name=None, template_loader=template_loader, extra_lookup_kwargs={}, extra_context={}, allow_empty=False): """ Generic daily archive view. Templates: ``<app_label>/<module_name>_archive_day`` Context: object_list: list of objects published that day day: (datetime) the day previous_day (datetime) the previous day next_day (datetime) the next day, or None if the current day is today """ try: date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3]) except ValueError: raise Http404 mod = get_module(app_label, module_name) now = datetime.datetime.now() lookup_kwargs = { '%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max)), } # Only bother to check current date if the date isn't in the past. if date >= now.date(): lookup_kwargs['%s__lte' % date_field] = now lookup_kwargs.update(extra_lookup_kwargs) object_list = mod.get_list(**lookup_kwargs) if not allow_empty and not object_list: raise Http404 if not template_name: template_name = "%s/%s_archive_day" % (app_label, module_name) t = template_loader.get_template(template_name) c = Context(request, { 'object_list': object_list, 'day': date, 'previous_day': date - datetime.timedelta(days=1), 'next_day': (date < datetime.date.today()) and (date + datetime.timedelta(days=1)) or None, }) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c))
def month(request, year, month): try: year = int(year) month = int(month) except ValueError: raise Http404 t = template_loader.get_template('calendar/month') c = Context(request, { 'year': year, 'month': month, 'matrix': get_month_matrix(year, month), }) return HttpResponse(t.render(c))
def gal(request,id): """ View for display of the thumbnails in the gallery """ list = photos.get_list(pk=id) gals = tags.get_list() t = template_loader.get_template('website/gal') c = Context(request, {'list':list, 'ads':extract(), 'mn': menu_items, 'gals':gals, }) return HttpResponse(t.render(c))
def accept_proposed_rate(request, shared_data): # this is node_to_confirm's account acct = Account.objects.get(shared_data=shared_data, owner__pk=shared_data.node_to_confirm_id) pmt = None if acct.getBalance() and shared_data.interest_rate: # otherwise no update necessary pmt = Payment(payer=acct.owner, payer_email=acct.owner.getPrimaryEmail(), recipient=acct.partner, recipient_email=acct.partner.getPrimaryEmail(), currency=shared_data.currency, amount=0.0, status='PE', description='Interest rate change: %s%% to %s%%.' % \ (shared_data.displayRate(), shared_data.displayProposedRate())) pmt.save() # set pmt time #pmt = Payment.objects.get(pk=pmt.id) # reload because django doesn't update date that is auto-set on save interest = computeInterest(acct.getBalance(), shared_data.interest_rate, shared_data.last_update, pmt.date) path = PaymentPath(payment=pmt, amount=pmt.amount) path.save() link = PaymentLink(path=path, payer_account=acct, position=1, amount=pmt.amount, interest=-interest, interest_rate=shared_data.interest_rate) link.save() shared_data.balance += interest * acct.balance_multiplier if pmt: shared_data.last_update = pmt.date else: shared_data.last_update = datetime.datetime.now() shared_data.interest_rate = shared_data.proposed_rate shared_data.proposed_rate = None shared_data.node_to_confirm_id = None shared_data.save() if pmt: # could do this initially now that this is wrapped in a transaction pmt.status = 'OK' pmt.save() t = template_loader.get_template('emailAcceptRateProposal.txt') c = RequestContext(request, {'acct': acct.get_partner_acct()}) sendEmail("Interest rate proposal accepted", t.render(c), acct.partner.getPrimaryEmail())
def archive_index(request): c = db.cursor() # FIXME -- use db abstraction layer for DATE_TRUNC c.execute("""SELECT DISTINCT DATE_TRUNC('month', posted) AS posted FROM blog_posts ORDER BY posted DESC""") rows = c.fetchall() c.close() c = Context(request, months=[ { 'date': date, 'posts': len(posts.get_list(listed__exact=True, posted__year=date.year, posted__month=date.month)), } for date, in rows ]) t = template_loader.get_template('blog/archive-index') return HttpResponse(t.render(c))
def reject_proposed_rate(request, shared_data): proposed_rate = shared_data.proposed_rate * 100.0 partner_acct = Account.objects.exclude( owner__pk=shared_data.node_to_confirm_id).get(shared_data=shared_data) shared_data.proposed_rate = None shared_data.node_to_confirm_id = None shared_data.save() t = template_loader.get_template('emailRejectRateProposal.txt') c = RequestContext(request, { 'acct': partner_acct, 'proposed_rate': proposed_rate }) sendEmail("Interest rate proposal not accepted", t.render(c), partner_acct.owner.getPrimaryEmail())
def object_detail(request, app_label, module_name, object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=template_loader, extra_lookup_kwargs={}, extra_context={}): """ Generic list of objects. Templates: ``<app_label>/<module_name>_detail`` Context: object the object """ mod = models.get_module(app_label, module_name) lookup_kwargs = {} if object_id: lookup_kwargs['pk'] = object_id elif slug and slug_field: lookup_kwargs['%s__exact' % slug_field] = slug else: raise AttributeError("Generic detail view must be called with either an object_id or a slug/slug_field") lookup_kwargs.update(extra_lookup_kwargs) try: object = mod.get_object(**lookup_kwargs) except ObjectDoesNotExist: raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs)) if not template_name: template_name = "%s/%s_detail" % (app_label, module_name) if template_name_field: template_name_list = [getattr(object, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = Context(request, { 'object': object, }) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value response = HttpResponse(t.render(c)) populate_xheaders(request, response, app_label, module_name, getattr(object, object._meta.pk.name)) return response
def send_feedback(request): error = None form = ErrorForm(data=request.REQUEST.copy()) if form.is_valid(): error = request.REQUEST['error'] comment = None if request.REQUEST.get( 'comment', None) is not None and request.REQUEST['comment'] != "": comment = request.REQUEST['comment'] email = None if request.REQUEST.get( 'email', None) is not None and request.REQUEST['email'] != "": email = request.REQUEST['email'] try: sf = SendFeedback() sf.give_feedback(error, comment, email) except: logger.error('handler500: Feedback could not be sent') logger.error(traceback.format_exc()) error = "Feedback could not been sent. Please contact administrator." fileObj = open(("%s/error500-%s.html" % (settings.LOGDIR, datetime.datetime.now())), "w") try: try: fileObj.write(request.REQUEST['error']) except: logger.error('handler500: Error could not be saved.') logger.error(traceback.format_exc()) finally: fileObj.close() if request.is_ajax(): return HttpResponse( "<h1>Thanks for your feedback</h1><p>You may need to refresh your browser to recover from the error</p>" ) return HttpResponseRedirect(reverse("fthanks")) context = {'form': form, 'error': error} t = template_loader.get_template('500.html') c = RequestContext(request, context) return HttpResponse(t.render(c))
def handlerInternalError(request, error): """ This is mostly used in an "object not found" situation, So there is no feedback form - simply display "not found" message. If the call was AJAX, we return the message in a 404 response. Otherwise return an html page, with 404 response. """ logger.warning('Object Not Found: %s' % request.path, extra={ 'status_code': 404, 'request': request }) if request.is_ajax(): return HttpResponseNotFound(error) context = {"error":error} t = template_loader.get_template("error.html") c = RequestContext(request, context) return HttpResponseNotFound(t.render(c))
def forgotPassword(request): errors = [] if request.method == 'POST': email = request.POST['email'] if not isEmail(email): errors.append( "%s does not appear to be a valid email address. Please try again." % escape(email)) if not errors: if EmailAddr.objects.filter(email=email).count() > 0: emailAddr = EmailAddr.objects.get(email=email) code = makeReminderCode() t = template_loader.get_template('emailForgotPassword.txt') c = RequestContext(request, {'email': email, 'code': code}) if sendEmail('How to reset your password', t.render(c), email): node = emailAddr.node existingReminders = node.reminder_set.all() for reminder in existingReminders: reminder.delete( ) # only one oustanding reminder per node allowed newReminder = Reminder(node=emailAddr.node, code=code) newReminder.save() else: errors.append( "Could not send email to %s. Please verify the email address and try again." % escape(email)) else: # email address not in system pass # pretend like we're sending a reminder anyways, so no one knows whether an email is registered or not if not errors: return HttpResponseRedirect('/passwordReminderSent/') d = {} d['infos'] = errors return render_to_response('forgotPassword.html', d, context_instance=RequestContext(request))
def insight(request): t = template_loader.get_template('webstart/insight.xml') codebase = request.build_absolute_uri(settings.STATIC_URL + 'webstart/jars/') href = request.build_absolute_uri(reverse("webstart_insight")) pattern = os.path.abspath( os.path.join(settings.OMERO_HOME, "lib", "insight", "*.jar").replace('\\', '/')) jarlist = glob(pattern) jarlist = [os.path.basename(x) for x in jarlist] # ticket:9478 put insight jar at the start of the list if available # This can be configured via omero.web.webstart_jar to point to a # custom value. idx = jarlist.index(settings.WEBSTART_JAR) if idx > 0: jarlist.pop(idx) jarlist.insert(0, settings.WEBSTART_JAR) context = { 'codebase': codebase, 'href': href, 'jarlist': jarlist, 'icon': settings.WEBSTART_ICON, 'heap': settings.WEBSTART_HEAP, 'host': settings.WEBSTART_HOST, 'port': settings.WEBSTART_PORT, 'class': settings.WEBSTART_CLASS, 'title': settings.WEBSTART_TITLE, 'vendor': settings.WEBSTART_VENDOR, 'homepage': settings.WEBSTART_HOMEPAGE, } c = Context(request, context) return HttpResponse(t.render(c), content_type="application/x-java-jnlp-file")
def sendConfirmationEmail(email, code, request): t = template_loader.get_template('emailConfirmation.txt') c = RequestContext(request, {'email': email, 'code': code}) return sendEmail('Please confirm email address', t.render(c), email)
def accountAction(request, acctId, action): userNode = checkLogin(request) if not userNode: return HttpResponseRedirect('/accounts/%s/' % acctId) if request.method == 'POST': if request.POST['submit'] == 'Cancel': return HttpResponseRedirect('/accounts/%s/' % acctId) if Account.objects.filter(pk=acctId).count() == 0: return HttpResponseRedirect('/accounts/') acct = Account.objects.get(pk=acctId) if acct.owner_id != userNode.id: return HttpResponseRedirect('/accounts/') if action == 'close': sharedData = acct.shared_data if abs(sharedData.balance) >= 0.005: request.session['infos'] = [ "Account balance must be zero before it can be closed." ] return HttpResponseRedirect('/accounts/%d/' % acct.id) # to be sure a transaction doesn't hit this account before it gets # deactivated, set limits to zero, save, and then check for zero balance again myIOULimit = acct.iou_limit partnerAcct = acct.get_partner_acct() partnerIOULimit = partnerAcct.iou_limit acct.iou_limit = 0.0 acct.save() partnerAcct.iou_limit = 0.0 partnerAcct.save() if abs(sharedData.balance) >= 0.005: request.session['infos'] = [ "Account balance must be zero before it can be closed." ] # restore limits on accts acct.iou_limit = myIOULimit acct.save() partnerAcct.iou_limit = partnerIOULimit partnerAcct.save() return HttpResponseRedirect('/accounts/%d/' % acct.id) # now it's impossible for a transaction to change the balance, and the balance is zero, so: sharedData.active = False sharedData.save() # notify user request.session['infos'] = [ "Account %d (%s) closed." % (sharedData.id, acct.name) ] # notify partner by email note = '' if request.method == 'POST': note = request.POST['note'] t = template_loader.get_template('emailAcctClosed.txt') c = RequestContext(request, {'acct': partnerAcct, 'note': note}) sendEmail("One of your accounts has been closed", t.render(c), acct.partner.getPrimaryEmail()) pass return HttpResponseRedirect('/accounts/')
if conn is not None: try: conn.reportForgottenPassword( smart_str(request.REQUEST.get('username')), smart_str(request.REQUEST.get('email'))) error = "Password was reseted. Check you mailbox." form = None except Exception, x: logger.error(traceback.format_exc()) error = "Internal server error, please contact administrator." else: form = ForgottonPasswordForm() context = {'error': error, 'form': form} t = template_loader.get_template(template) c = Context(request, context) rsp = t.render(c) return HttpResponse(rsp) @login_required() def index(request, **kwargs): conn = None try: conn = kwargs["conn"] except: logger.error(traceback.format_exc()) if conn.isAdmin(): return HttpResponseRedirect(reverse("waexperimenters"))
def paymentForm(request, pmtId=None, otherUserId=None, is_request=False): userNode = checkLogin(request) if not userNode: return HttpResponseRedirect('/login/?redirect=%s' % request.path) errors = [] d = {} if request.method == 'POST': # get post data and attempt payment email = request.POST['email'] d['email'] = email # for maintaining form value in case of error if EmailAddr.objects.filter(email=email, confirmed=True).count() == 0: errors.append("Email '%s' does not belong to any Ripple user," "or has not yet been confirmed." % escape(email)) else: emailAddr = EmailAddr.objects.get(email=email) otherUser = emailAddr.node if otherUser == userNode: action = is_request and 'request payment from' or 'pay' errors.append("You can't %s yourself." % action) amountStr = request.POST['amount'] d['amount'] = amountStr try: amount = float(amountStr) if amount <= 0.0: raise Exception except: errors.append( "Amount must be a positive number. '%s' is not valid." % escape(amountStr)) currencyName = request.POST[ 'currency'] # this should be OK, since it's from a generated list currency = CurrencyUnit.objects.get(short_name=currencyName) d['selectedUnitId'] = currency.id d['description'] = request.POST['description'] if not errors: # check for enough credit available = availableCredit(userNode, currency, incoming=is_request) if available < amount: action = is_request and 'request' or 'make' errors.append( "You do not have enough available credit to %s payment. " "Available: %s %.2f." % (action, currency.short_name, available)) if availableCredit(otherUser, currency, incoming=not is_request) < amount: if is_request: pass # Other user might get more credit to fulfill request else: errors.append( "Your intended recipient has not offered enough credit " "to receive your payment.") pmt = None if request.POST['pmtId'] != 'None': pmt = Payment.objects.get(pk=request.POST['pmtId']) # Check if user can edit if (not is_request and pmt.payer_id != userNode.id) or \ (is_request and pmt.recipient_id != userNode.id): return HttpResponseRedirect('/payments/') if pmt.status == 'OK': # can't edit completed payment d = { 'message': 'Payment has already been completed.', 'link': '/payments/' } return render_to_response( 'error.html', d, context_instance=RequestContext(request)) d['pmtId'] = pmt.id # in case of errors, re-post pmtId if not errors: payer = is_request and otherUser or userNode recipient = is_request and userNode or otherUser if pmt is None: pmt = Payment() # Create new Payment. pmt.payer = payer pmt.payer_email = is_request and email or payer.getPrimaryEmail() pmt.recipient = recipient pmt.recipient_email = is_request and recipient.getPrimaryEmail( ) or email pmt.amount = amount pmt.currency = currency pmt.date = datetime.now() pmt.status = is_request and 'RQ' or 'PE' pmt.description = d['description'] pmt.save() if is_request: # Send payment request email t = template_loader.get_template('emailPmtRequestReceived.txt') c = RequestContext(request, {'req': pmt}) sendEmail("Payment request notification", t.render(c), pmt.payer_email) request.session['infos'] = [ "Your payment request has been recorded " "and a notification email sent to the payer." ] return HttpResponseRedirect('/payments/') else: # Go to payment confirmation page return HttpResponseRedirect('/payments/%s/confirm/' % pmt.id) # present make payment form d['infos'] = errors if otherUserId: # paying a specific user - URL = payUser/id/ if Node.objects.filter( pk=otherUserId).count() > 0 and userNode.id != otherUserId: d['email'] = Node.objects.get(pk=otherUserId).getPrimaryEmail() if pmtId: # editing a pending payment from DB - URL = paymentForm/id/ if Payment.objects.filter(pk=pmtId).count() > 0: pmt = Payment.objects.get(pk=pmtId) if pmt.status == 'OK': # can't edit completed payment d = { 'message': 'Payment has already been completed.', 'link': '/payments/' } return render_to_response( 'error.html', d, context_instance=RequestContext(request)) d['email'] = is_request and pmt.payer_email or pmt.recipient_email d['amount'] = pmt.amount d['selectedUnitId'] = pmt.currency_id d['description'] = pmt.description d['pmtId'] = pmtId d['paymentUnits'] = makeUnitsList(userNode) # set selected units to account units, if paying account partner, or to default units if not d.has_key('selectedUnitId'): if otherUserId and userNode.account_set.filter( partner__pk=otherUserId).count() > 0: acct = userNode.account_set.filter(partner__pk=otherUserId)[0] d['selectedUnitId'] = acct.shared_data.currency_id else: d['selectedUnitId'] = userNode.display_units_id d['is_request'] = is_request return render_to_response('paymentForm.html', d, context_instance=RequestContext(request))
def offerAction(request, offerId, action): """Accept or reject somebodys offer of credit""" userNode = checkLogin(request) if not userNode: return HttpResponseRedirect('/login/?redirect=%s' % request.path) message = '' if Offer.objects.filter(pk=offerId).count() == 1: offer = Offer.objects.get(pk=offerId) else: # offer has been deleted since action link was displayed to user if action == 'accept' or action == 'reject': message = "Offer has been withdrawn and cannot be accepted or rejected." else: message = "Offer has already been acted on and cannot be withdrawn." request.session['infos'] = [message] return HttpResponseRedirect('/summary/') # check the offer is for the logged-in user if action is accept or reject if (action == 'accept' or action == 'reject') and \ offer.recipient_email not in getEmails(userNode): return HttpResponseRedirect('/summary/') if action == 'accept': initiator = offer.initiator # check for existing account between nodes # *** temporary until multiple accounts permitted if Account.objects.filter(owner=userNode, partner=initiator, shared_data__active=True).count() > 0: request.session['infos'] = [ "Account already exists with %s. Multiple accounts with the same neighbour are not permitted (yet)." % escape(initiator.name) ] offer.delete() return HttpResponseRedirect('/summary/') currencyId = offer.currency_id shared = SharedAccountData(currency_id=currencyId, balance=0.0, active=True, interest_rate=offer.interest_rate / 100.0) shared.save() acct1 = Account(owner=initiator, partner=userNode, shared_data=shared, balance_multiplier=1, iou_limit=0.0, partner_limit=offer.amount, name=userNode.name) acct1.save() acct2 = Account(owner=userNode, partner=initiator, shared_data=shared, balance_multiplier=-1, iou_limit=offer.amount, partner_limit=0.0, name=initiator.name) acct2.save() offer.delete() # shuffle node locations *** slow - consider doing as a regular script instead circle = routing.Circle() circle.shuffle(10 * Node.objects.count()) # send email informing initiator that offer was accepted t = template_loader.get_template('emailInvitationAccepted.txt') c = RequestContext(request, {'offer': offer, 'acct': acct1}) initiator_email = initiator.getPrimaryEmail() sendEmail("Invitation accepted", t.render(c), initiator_email) request.session['infos'] = [ "This is your new connection account with %s. Please take the time to give your account a meaningful name and assign your new neighbour a credit limit." % escape(initiator_email) ] return HttpResponseRedirect('/accounts/%d/' % acct2.id) elif action == 'reject': offer.delete() note = '' if request.method == 'POST': note = request.POST['note'] # send email informing initiator that offer was rejected t = template_loader.get_template('emailInvitationRejected.txt') c = RequestContext(request, {'offer': offer, 'note': note}) sendEmail("Your invitation was not accepted", t.render(c), offer.initiator.getPrimaryEmail()) message = "Offer from %s rejected." % escape( offer.initiator.getPrimaryEmail()) elif action == 'withdraw': if userNode != offer.initiator: return HttpResponseRedirect('/accounts/') offer.delete() message = "Offer to %s withdrawn." % offer.recipient_email if message: request.session['infos'] = [message] return HttpResponseRedirect('/accounts/')
def offer(request): """offer credit to multiple nodes""" userNode = checkLogin(request) if not userNode: return HttpResponseRedirect('/login/?redirect=%s' % request.path) if not request.POST: return HttpResponseRedirect('/summary/') if request.POST[ 'phase'] == 'make_offers': # check if offers are finalized, or if we're just listing emails and the form # extract info from POST dictionary rows = [] for i in range(0, int(request.POST['count'])): row = Struct() row.email = request.POST['email_%d' % i] # already parsed as email addresses row.amount = request.POST['amount_%d' % i] row.currency = request.POST['currency_%d' % i] row.interest = request.POST['interest_%d' % i] rows.append(row) # find errors in entries error = False for row in rows: # ensure no double-offers or double-accounts emailList, errors = validateOfferEmails([row.email], userNode) if not emailList: # if row.email is in list, then offer is valid error = True row.error = errors[0] # only show first error continue # only one error per row # validate amounts as numbers try: row.amount = float(row.amount) if row.amount <= 0.0: raise ValueError except ValueError: error = True row.error = "Credit limit must be a number greater than zero." else: if row.amount >= 10**12: error = True row.error = "Amount is too large to be stored in the database. Please enter another amount." elif row.amount <= 10**-12: error = True row.error = "Amount is too small to be stored in the database. Please enter another amount." if error: continue # only one error per row try: row.interest = float(row.interest) except ValueError: error = True row.error = "Interest rate must be a number." note = request.POST['note'] if note == '': note = None if error: # show form again with errors and values still there (in row objects) d = {'rows': rows, 'count': len(rows)} d['infos'] = [ "One of more of your entries had errors. Please make corrections below." ] else: # create and save offers, and send out emails infos = [] infos.append( 'The system has recorded your offers of credit and is sending out invitation emails. <a href="/accounts/#offers">Click here to see your offers.</a>' ) #infos.append("If the invitation does not arrive, it may be in the destination's spam folder...") for row in rows: currency = CurrencyUnit.objects.get(short_name=row.currency) offer = Offer(initiator=userNode, recipient_email=row.email, amount=row.amount, currency=currency, interest_rate=row.interest) offer.save() # send out email t = template_loader.get_template('emailInvitation.txt') c = RequestContext( request, { 'row': row, 'userNode': userNode, 'currency': currency, 'note': note }) sender = '"%s" <%s>' % (userNode.name, userNode.getPrimaryEmail()) if not sendEmail('Invitation to Ripple', t.render(c), row.email, sender=sender, attempts=2, includeServiceName=False): infos.append( "An email could not be sent to %s, but your offer has been stored. Please contact %s manually." % (escape(row.email), escape(row.email))) request.session['infos'] = infos return HttpResponseRedirect('/accounts/') else: # else, list emails + form emails = parseEmails(request.POST['emailText']) emails, infos = validateOfferEmails(emails, userNode) if emails == [] and infos == []: infos.append("You didn't enter any valid email addresses.") rows = [] for email in emails: row = Struct() row.email = email row.currency = None row.interest = 0 rows.append(row) d = {'infos': infos, 'rows': rows, 'count': len(rows)} d['currencies'] = CurrencyUnit.objects.order_by('long_name') return render_to_response('offer.html', d, context_instance=RequestContext(request))