def account(request): if not request.user.is_active: return render( request, 'techpong/error.html', dict( error_title="Account Inactive", error_message="Your account is currently inactive. Please contact an administrator." ) ) # create form from company model company_form_class = modelform_factory(Company, fields=( 'name', 'location', 'show_rank', 'show_rating', 'order_by') ) # handle post if request.method == 'POST': company_form = company_form_class( request.POST, instance=request.user.profile.company) if company_form.is_valid(): company_form.save() else: company_form = company_form_class(instance=request.user.profile.company) # render account page return render(request, 'techpong/account.html', { 'form': company_form, 'company': request.user.profile.company, 'player': request.user, 'api_account_id': request.user.profile.company.get_api_account_id(), 'api_access_key': request.user.profile.company.get_api_access_key() })
def player(request, company_name, player_id): try: company = Company.objects.filter(short_name = company_name).get() except ObjectDoesNotExist: # todo: show signup form raise Http404() # check permission if not company.check_permission(request.user): # todo: show permission denied raise Http404() # look for target player in the same company try: player = Player.objects.filter(company=company, id=player_id).get() except ObjectDoesNotExist: raise Http404() # check if company is currently recalculating if company.recalculating: return render(request, 'techpong/recalculating.html', { 'company': company }) # process cached data cached_results = json.loads(player.cached_results or '[]') cached_ratings = json.loads(player.cached_rating_changes or '[]') cached_ranks = json.loads(player.cached_rank_changes or '[]') create_sparklines(player) # ratings graphs ymin, ymax = None, None for rating_info in cached_ratings: rating = rating_info['rating'] if rating < ymin or ymin is None: ymin = rating if rating > ymax or ymax is None: ymax = rating if ymin is None: ymin = 0 if ymax is None: ymax = 500 ratings_spread = ymax - ymin graph_offset = RATINGS_GRAPH_RANGE_MULTIPLIER * ratings_spread graph_min = max(0, 10 * round((ymin - graph_offset) / 10)) graph_max = 10 * math.ceil((ymax + graph_offset) / 10) # render the player screen return render(request, 'techpong/player.html', { 'player': player, 'company': company, 'cached_results': cached_results, 'cached_ratings': cached_ratings, 'cached_ranks': cached_ranks, 'ymin': graph_min, 'ymax': graph_max })
def player(request, company_name, player_id): try: company = Company.objects.filter(short_name=company_name).get() except ObjectDoesNotExist: # todo: show signup form raise Http404() # check permission if not company.check_permission(request.user): # todo: show permission denied raise Http404() # look for target player in the same company try: player = Player.objects.filter(company=company, id=player_id).get() except ObjectDoesNotExist: raise Http404() # check if company is currently recalculating if company.recalculating: return render(request, 'techpong/recalculating.html', {'company': company}) # process cached data cached_results = json.loads(player.cached_results or '[]') cached_ratings = json.loads(player.cached_rating_changes or '[]') cached_ranks = json.loads(player.cached_rank_changes or '[]') create_sparklines(player) # ratings graphs ymin, ymax = None, None for rating_info in cached_ratings: rating = rating_info['rating'] if rating < ymin or ymin is None: ymin = rating if rating > ymax or ymax is None: ymax = rating if ymin is None: ymin = 0 if ymax is None: ymax = 500 ratings_spread = ymax - ymin graph_offset = RATINGS_GRAPH_RANGE_MULTIPLIER * ratings_spread graph_min = max(0, 10 * round((ymin - graph_offset) / 10)) graph_max = 10 * math.ceil((ymax + graph_offset) / 10) # render the player screen return render( request, 'techpong/player.html', { 'player': player, 'company': company, 'cached_results': cached_results, 'cached_ratings': cached_ratings, 'cached_ranks': cached_ranks, 'ymin': graph_min, 'ymax': graph_max })
def dashboard(request, company_name): try: company = Company.objects.filter(short_name = company_name).get() except ObjectDoesNotExist: return render( request, 'techpong/error.html', dict( error_title="Company Not Found", error_message='Could not find Company "%s"' % company_name ) ) # check permission if not company.check_permission(request.user): return render( request, 'techpong/error.html', dict( error_title="Permission Denied", error_message='You do not have permission to access this ladder. You may need to log in to a different account.' ) ) # check if company is currently recalculating if company.recalculating: return render(request, 'techpong/recalculating.html', { 'company': company }) # get company info company_info = company.get_info() # go through each player and add sparkline graph info for player in company_info['players']: create_sparklines(player) # notifications notifications = Notification.objects.all() if request.user.profile.last_viewed_notifications: notifications = notifications.filter( notification_time__gte=request.user.profile.last_viewed_notifications ) notifications = notifications[:10] # render the dashboard return render(request, 'techpong/dashboard.html', { "csrf_token": csrf(request)['csrf_token'], 'company': company, 'info': company_info, 'notifications': notifications })
def dashboard(request, company_name): try: company = Company.objects.filter(short_name=company_name).get() except ObjectDoesNotExist: return render( request, 'techpong/error.html', dict(error_title="Company Not Found", error_message='Could not find Company "%s"' % company_name)) # check permission if not company.check_permission(request.user): return render( request, 'techpong/error.html', dict( error_title="Permission Denied", error_message= 'You do not have permission to access this ladder. You may need to log in to a different account.' )) # check if company is currently recalculating if company.recalculating: return render(request, 'techpong/recalculating.html', {'company': company}) # get company info company_info = company.get_info() # go through each player and add sparkline graph info for player in company_info['players']: create_sparklines(player) # notifications notifications = Notification.objects.all() if request.user.profile.last_viewed_notifications: notifications = notifications.filter( notification_time__gte=request.user.profile. last_viewed_notifications) notifications = notifications[:10] # render the dashboard return render( request, 'techpong/dashboard.html', { "csrf_token": csrf(request)['csrf_token'], 'company': company, 'info': company_info, 'notifications': notifications })
def api_docs(request, api_version='latest'): # TODO: implement, then enforce api version :D # TODO: get api prefix from url config api_version = 1 api_version_url_path = 'v1' company = request.user.profile.company players = company.player_set.all() player1, player2 = None, None if len(players) > 0: player1 = players[0] if len(players) > 1: player2 = players[1] raw_new_player_name = 'new_player' new_player_name = raw_new_player_name count = 1 while Player.objects.filter(name=new_player_name, company=company).count() > 0: count += 1 new_player_name = raw_new_player_name + str(count) return render( request, 'techpong/docs.html', dict(api_version=api_version, api_prefix='/api/%s/' % api_version_url_path, api_account_id=request.user.profile.company.get_api_account_id(), api_access_key=request.user.profile.company.get_api_access_key(), players=players, player1=player1, player2=player2, new_player_name=new_player_name))
def index(request): return render( request, 'techpong/index.html', dict(total_companies=Company.objects.count(), total_players=Player.objects.count(), total_matches=Match.objects.count(), total_rounds=Round.objects.count()))
def api_docs(request, api_version='latest'): # TODO: implement, then enforce api version :D # TODO: get api prefix from url config api_version = 1 api_version_url_path = 'v1' company = request.user.profile.company players = company.player_set.all() player1, player2 = None, None if len(players) > 0: player1 = players[0] if len(players) > 1: player2 = players[1] raw_new_player_name = 'new_player' new_player_name = raw_new_player_name count = 1 while Player.objects.filter( name=new_player_name, company=company).count() > 0: count += 1 new_player_name = raw_new_player_name + str(count) return render(request, 'techpong/docs.html', dict( api_version=api_version, api_prefix='/api/%s/' % api_version_url_path, api_account_id=request.user.profile.company.get_api_account_id(), api_access_key=request.user.profile.company.get_api_access_key(), players=players, player1=player1, player2=player2, new_player_name=new_player_name ))
def index(request): return render(request, 'techpong/index.html', dict( total_companies = Company.objects.count(), total_players = Player.objects.count(), total_matches = Match.objects.count(), total_rounds = Round.objects.count() ))
def page(request, path): preview = request.GET.get('preview', 'false').lower() try: page = Page.objects.get(path=path) except Page.DoesNotExist: raise Http404(path) if not page.published: if (request.user.is_staff and preview != 'true') or not request.user.is_staff: raise Http404(path) if page.login_required and not request.user.is_authenticated(): return redirect_to_login(page.full_path) try: version = int(request.GET['version']) data = page.version_data(version) if not request.user.is_staff: return redirect(settings.LOGIN_URL) except KeyError: data = page.published_data data_dict = yaml.load(data) if not page.template: raise KonohaError("Page doesn't have template") return render(request, page.template, dictionary=data_dict, content_type=page.content_type_with_charset)
def index(request): print request.method if request.method == "POST": photoList = [] flickrURL = request.POST["ScanFlickr[flickrURL]"].strip() page = request.POST["ScanFlickr[page]"] urlType = isValid(flickrURL) if not urlType: # If the URL the user submitted is not valid (despite being validated on the front end) return HttpResponse(json.dumps({"photoList": []})) else: t1 = threading.Thread(target=producerThread, args=(flickrURL, urlType, page)) t2 = ThreadWithReturnValue(target=consumerThread, args=(photoList,)) t1.start() t1.join() t2.start() q.join() # The value of photoList is invisibly returned from t2 via dark magic from the ThreadWithReturnValue class # If the URL is invalid or the Flickr API call fails for some other reason, return an empty array of photos to the user return HttpResponse(json.dumps({"photoList": photoList})) # Return this if the API call fails else: context = {} return render(request, "index.html", context)
def generate_dashboard(request): username = request.user.username #hard coded for now start_time = datetime.strptime('Thu Feb 28 23:13:32 PST 2013', '%a %b %d %H:%M:%S %Z %Y') end_time = datetime.strptime('Thu Feb 28 23:25:39 PST 2013', '%a %b %d %H:%M:%S %Z %Y') avg_speed = get_average(username, 'vehicle_speed', start_time, end_time) return render(request, 'dashboard.html', {'vehicle_speed' : avg_speed})
def _render(error=None): context.update({ 'no_errors': error is None, }) if error: messages.error(request, unicode(error)) return render(request, template_name, context)
def _process_signup(request, sociallogin): # If email is specified, check for duplicate and if so, no auto signup. auto_signup = app_settings.AUTO_SIGNUP email = user_email(sociallogin.account.user) if auto_signup: # Let's check if auto_signup is really possible... if email: if account_settings.UNIQUE_EMAIL: if email_address_exists(email): # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. We cannot check # on 'email_address.verified' either, because # 'email_address' is not guaranteed to be verified. auto_signup = False # FIXME: We redirect to signup form -- user will # see email address conflict only after posting # whereas we detected it here already. elif app_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... auto_signup = False if not auto_signup: request.session['socialaccount_sociallogin'] = sociallogin url = reverse('socialaccount_signup') ret = HttpResponseRedirect(url) else: # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) try: if not get_account_adapter().is_open_for_signup(request): return render(request, "account/signup_closed.html") except ImmediateHttpResponse as e: return e.response u = sociallogin.account.user if account_settings.USER_MODEL_USERNAME_FIELD: user_username( u, generate_unique_username(user_username(u) or email or 'user')) for field in ['last_name', 'first_name']: if hasattr(u, field): truncated_value = (user_field(u, field) or '') \ [0:User._meta.get_field(field).max_length] user_field(u, field, truncated_value) user_email(u, email or '') u.set_unusable_password() sociallogin.save(request) from allauth.account.models import EmailAddress email_address = EmailAddress.objects.get(user=u, email__iexact=email) if app_settings.AUTO_EMAIL_VERIFY == True: email_address.verified = True email_address.save() #send_email_confirmation(request, u) ret = complete_social_signup(request, sociallogin) return ret
def archive(request, week_num): try: archive = Archive.objects.get(edition=week_num) return render(request, "archive.html", locals()) except Archive.DoesNotExist: pass return redirect('index')
def archive(request, week_num): try: archive = Archive.objects.get(edition=week_num) return render(request, "archive.html", locals()) except Archive.DoesNotExist: pass return redirect("index")
def channel(request): provider = providers.registry.by_id(FacebookProvider.id) locale = provider.get_locale_for_request(request) response = render(request, 'facebook/channel.html', {'facebook_jssdk_locale': locale}) cache_expire = 60 * 60 * 24 * 365 patch_response_headers(response, cache_expire) response['Pragma'] = 'Public' return response
def get(self, request, *args, **kwargs): """ Handles sign in GET request. """ redirect_to = request.REQUEST.get(self.redirect_field_name, '') context = { 'sign_in_page': True, 'sign_in_next': redirect_to, } return render(request, self.template_name, context)
def incident_detail(request, pk): """ Detail view for a single incident, which may have multiple victims. """ incident = get_object_or_404(Incident.objects.public(), pk=pk) victims = list(incident.victims.public() .select_related('incident', 'race', 'method')) return render(request, 'gundeaths/incident_detail.html', { 'incident': incident, 'victims': victims })
def incident_detail(request, pk): """ Detail view for a single incident, which may have multiple victims. """ incident = get_object_or_404(Incident.objects.public(), pk=pk) victims = list(incident.victims.public().select_related( 'incident', 'race', 'method')) return render(request, 'gundeaths/incident_detail.html', { 'incident': incident, 'victims': victims })
def admin_payments(request): last_year = datetime.today().year - 1 previous_years = [year for year in range(2011, last_year)] context = { "title_prefix": _(u"Pagos a terceros"), "active_tab": "payments", "last_year": last_year, "previous_years": previous_years, } return render(request, "admin/payments.html", context)
def admin_general(request): current_year = datetime.today().year previous_years = [year for year in range(2011, current_year)] context = { "title_prefix": _(u"Presupuesto general"), "active_tab": "general", "current_year": current_year, "previous_years": previous_years, } return render(request, "admin/general.html", context)
def admin_execution(request): current_year = datetime.today().year previous_years = [year for year in range(2011, current_year)] context = { "title_prefix": _(u"Ejecución mensual"), "active_tab": "execution", "current_year": current_year, "previous_years": previous_years, } return render(request, "admin/execution.html", context)
def contact(request, template_name="website/pages/contact.html"): """ A view for sending messages to support team. """ if not request.method == 'GET': return HttpResponseBadRequest() form_class = AnonymousContactForm if request.user.is_anonymous() else \ ContactForm context = { 'form': form_class(), } return render(request, template_name, context)
def account(request): if not request.user.is_active: return render( request, 'techpong/error.html', dict( error_title="Account Inactive", error_message= "Your account is currently inactive. Please contact an administrator." )) # create form from company model company_form_class = modelform_factory(Company, fields=('name', 'location', 'show_rank', 'show_rating', 'order_by')) # handle post if request.method == 'POST': company_form = company_form_class( request.POST, instance=request.user.profile.company) if company_form.is_valid(): company_form.save() else: company_form = company_form_class( instance=request.user.profile.company) # render account page return render( request, 'techpong/account.html', { 'form': company_form, 'company': request.user.profile.company, 'player': request.user, 'api_account_id': request.user.profile.company.get_api_account_id(), 'api_access_key': request.user.profile.company.get_api_access_key() })
def user_settings(request, general_settings_form_class=GeneralSettingsForm, password_change_form_class=PasswordChangeForm, change_callsign_form_class=ChangeCallsignForm, template_name='auth_custom/pages/user-settings.html'): """ Display user settings and apply changes. """ if not request.method == 'GET': return HttpResponseBadRequest() context = { 'form_general': general_settings_form_class(request.user), 'form_password': password_change_form_class(request.user), 'form_callsign': change_callsign_form_class(request.user), } return render(request, template_name, context)
def paypal_record(request): transaction = Transaction.objects.get(processor_payment_id=request.REQUEST['paymentId']) try: payment = get_payment(request.REQUEST['paymentId']) except PaymentNotFoundError: mark_transaction_expired(transaction) return redirect(reverse('event:detail')) update_transaction(transaction, request.REQUEST['token'], payment) context = get_event_context(transaction.event) context['transaction'] = transaction.to_json() return render(request, "event/detail.html", context)
def index(request): current_time = timezone.now() one_day_ago = current_time + datetime.timedelta(days=-1) tweets = Tweet.objects.filter(created_at__range=[one_day_ago, current_time]).order_by('-created_at') good_tweets = tweets.filter(is_good=True) bad_tweets = tweets.filter(is_good=False) good_tweets_without_retweets = good_tweets.filter(is_retweet=False)[:25] bad_tweets_without_retweets = bad_tweets.filter(is_retweet=False)[:25] good_score_acc = sum(map(score, good_tweets, [one_day_ago]*len(good_tweets))) bad_score_acc = sum(map(score, bad_tweets, [one_day_ago]*len(bad_tweets))) good_score = int((good_score_acc/(good_score_acc + bad_score_acc + 1)) * 100) bad_score = 100 - good_score return render(request, "index.html", locals())
def perform_login(request, user, email_verification, redirect_url=None, signal_kwargs={}, signup=False): """ Keyword arguments: signup -- Indicates whether or not sending the email is essential (during signup), or if it can be skipped (e.g. in case email verification is optional and we are only logging in). """ from .models import EmailAddress # not is_active: social users are redirected to a template # local users are stopped due to form validation checking is_active assert user.is_active has_verified_email = EmailAddress.objects.filter(user=user, verified=True).exists() if email_verification == EmailVerificationMethod.NONE: pass elif email_verification == EmailVerificationMethod.OPTIONAL: # In case of OPTIONAL verification: send on signup. if not has_verified_email and signup: send_email_confirmation(request, user, signup=signup) elif email_verification == EmailVerificationMethod.MANDATORY: if not has_verified_email: send_email_confirmation(request, user, signup=signup) return render(request, "account/verification_sent.html", {"email": user_email(user)}) # HACK: This may not be nice. The proper Django way is to use an # authentication backend, but I fail to see any added benefit # whereas I do see the downsides (having to bother the integrator # to set up authentication backends in settings.py if not hasattr(user, 'backend'): user.backend = "django.contrib.auth.backends.ModelBackend" signals.user_logged_in.send(sender=user.__class__, request=request, user=user, **signal_kwargs) login(request, user) get_adapter().add_message(request, messages.SUCCESS, 'account/messages/logged_in.txt', {'user': user}) return HttpResponseRedirect(get_login_redirect_url(request, redirect_url))
def password_reset(request, uidb64, token, form_class=SetPasswordForm, template_name='auth_custom/pages/password-reset.html', token_generator=default_token_generator): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ assert uidb64 is not None and token is not None # checked by URLconf try: uid = urlsafe_base64_decode(uidb64) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None valid_link = user is not None and token_generator.check_token(user, token) if valid_link: if request.method == 'POST': form = form_class(user, request.POST) if form.is_valid(): form.save() is_anonymous = request.user.is_anonymous() message = _("Your password was successfully updated.") if is_anonymous: message = message + " " + \ _("You can use it to sign in right now!") messages.success(request, message) next_name = 'auth-custom-sign-in' if is_anonymous else \ 'website-index' return redirect(resolve_url(next_name)) else: form = form_class(None) else: form = None context = { 'form': form, 'valid_link': valid_link, } return render(request, template_name, context)
def paypal_execute(request): logger = logging.getLogger(__name__) transaction = Transaction.objects.get(processor_payment_id=request.REQUEST['paymentId']) payment = get_payment(request.REQUEST['paymentId']) if payment.execute({'payer_id': payment.to_dict()['payer']['payer_info']['payer_id']}): mark_transaction_successful(transaction) logger.critical("Payment execute successfully") if transaction.status == 'completed': return redirect("{}?paymentId={}".format(reverse('payment:receipt'), request.REQUEST['paymentId'])) mark_transaction_error(transaction) logger.critical(payment.error) # Error Hash context = get_event_context(transaction.event) context['transaction'] = transaction.to_json() return render(request, "event/detail.html", context)
def apply(request): if request.is_ajax() and request.method == "POST": application = ApplyForm(request.POST) if application.is_valid(): cd = application.cleaned_data app = Application(name=cd['name'], email=cd['email'], major=cd['major'], attendance=cd['attendance'], interest=cd['interest'], background=cd['background'], comments=cd['comments']) app.save() appreview = ApplicationReview(application=app) appreview.save() results = json.dumps({'status': 'success'}, ensure_ascii=False) return HttpResponse(results, mimetype='application/json') return render(request, "application.html", locals()) return redirect('index')
def apply(request): if request.is_ajax() and request.method == "POST": application = ApplyForm(request.POST) if application.is_valid(): cd = application.cleaned_data app = Application( name=cd['name'], email=cd['email'], major=cd['major'], attendance=cd['attendance'], interest=cd['interest'], background=cd['background'], comments=cd['comments']) app.save() appreview = ApplicationReview(application=app) appreview.save() results = json.dumps({ 'status' : 'success' }, ensure_ascii=False) return HttpResponse(results, mimetype='application/json') return render(request, "application.html", locals()) return redirect('index')
def index(request): current_time = timezone.now() one_day_ago = current_time + datetime.timedelta(days=-1) tweets = Tweet.objects.order_by('-created_at') good_tweets = tweets.filter(is_good=True)[:300] bad_tweets = tweets.filter(is_good=False)[:300] good_tweets_without_retweets = tweets.filter(is_good=True, is_retweet=False)[:30] bad_tweets_without_retweets = tweets.filter(is_good=False, is_retweet=False)[:30] good_score_acc = sum( map(score, good_tweets, [one_day_ago] * len(good_tweets))) bad_score_acc = sum(map(score, bad_tweets, [one_day_ago] * len(bad_tweets))) good_score = int( (good_score_acc / (good_score_acc + bad_score_acc + 1)) * 100) bad_score = 100 - good_score return render(request, "index.html", locals())
def index(request): n = len(Sleeper.objects.all()) return render(request, "index.html", locals())
def show(request, username): try: sleeper = Sleeper.objects.get(username=username) return render(request, "show.html", locals()) except Sleeper.DoesNotExist: return redirect(index)
def render(self, request, *args, **kwargs): return render(request, *args, **kwargs)
def students(request): students = Student.objects.all() return render(request, "students.html", locals())
def admin_glossary_en(request): context = {"title_prefix": _(u"Glosario"), "active_tab": "glossary"} return render(request, "admin/glossary_en.html", context)
def lecture(request, lecture_id): return render(request, "lectures/lecture%s.html" % lecture_id, locals())
def review(request): if not request.user.is_superuser: return redirect('index') apps = sorted(ApplicationReview.objects.all(), key=operator.attrgetter('application.created_at')) return render(request, "review.html", locals())
def admin_inflation(request): context = {"title_prefix": _(u"Inflación"), "active_tab": "inflation"} return render(request, "admin/inflation.html", context)
def index(request): return render(request, "index.html", locals())
def index(request): archives = Archive.objects.all() return render(request, "index.html", locals())
from django.conf import settings from django.core.cache import cache from django.http import Http404 from wordpress import WordPress, WordPressError wp = WordPress(settings.WORDPRESS_BLOG_URL, cache) def wp_proxy(request, **kwargs): """ Proxy request to WordPress. """ try: resp = wp.proxy(request.path) except WordPressError, e: if 'Not found' in e.args: raise Http404 else: raise # get a template name, using an index by default template = kwargs.pop('template', 'news/blog_index.html') # pass any remaining kwargs into context resp.update(kwargs) # send everything along return render(request, template, resp)
def student(request, student_id): try: student = Student.objects.get(id=student_id) except Student.DoesNotExist: return redirect('students') return render(request, "student.html", locals())
def lesson(request, lesson_id): return render(request, "lessons/lesson%s.html" % lesson_id, locals())
def lessons(request): return render(request, "lessons/index.html", locals())
def admin_population(request): context = {"title_prefix": _(u"Población"), "active_tab": "population"} return render(request, "admin/population.html", context)