def get_from_context(request, what, default=None): context = RequestContext(request) if hasattr(context, 'bind_template'): # Django 1.8: force context processors with context.bind_template(Template('')): return context.get(what, default) return context.get(what, default)
def connect(request): ''' Exception and validation functionality around the _connect view Separated this out from _connect to preserve readability Don't bother reading this code, skip to _connect for the bit you're interested in :) ''' facebook_login = to_bool(request.REQUEST.get('facebook_login')) context = RequestContext(request) #validation to ensure the context processor is enabled if not context.get('FACEBOOK_APP_ID'): message = 'Please specify a Facebook app id and ensure the context processor is enabled' raise ValueError(message) #hide the connect page, convenient for testing with new users in production though if not facebook_login and not settings.DEBUG and facebook_settings.FACEBOOK_HIDE_CONNECT_TEST: raise Http404('not showing the connect page') try: response = _connect(request, facebook_login) except open_facebook_exceptions.FacebookUnreachable, e: #often triggered when Facebook is slow warning_format = u'%s, often caused by Facebook slowdown, error %s' warn_message = warning_format % (type(e), e.message) send_warning(warn_message, e=e) response = error_next_redirect(request, additional_params=dict( fb_error_or_cancel=1) )
def connect(request, graph): ''' Exception and validation functionality around the _connect view Separated this out from _connect to preserve readability Don't bother reading this code, skip to _connect for the bit you're interested in :) ''' backend = get_registration_backend() context = RequestContext(request) # validation to ensure the context processor is enabled if not context.get('FACEBOOK_APP_ID'): message = 'Please specify a Facebook app id and ensure the context processor is enabled' raise ValueError(message) try: response = _connect(request, graph) except open_facebook_exceptions.FacebookUnreachable as e: # often triggered when Facebook is slow warning_format = '%s, often caused by Facebook slowdown, error %s' warn_message = warning_format % (type(e), e.message) send_warning(warn_message, e=e) additional_params = dict(fb_error_or_cancel=1) response = backend.post_error(request, additional_params) return response
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: logger.info('trying to connect using facebook') graph = get_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: warn_message = u'Incomplete profile data encountered '\ u'with error %s' % e send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: return user.get_profile().post_facebook_registration( request) else: if 'attempt' in request.GET: return next_redirect( request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) else: logger.info('Facebook authentication needed for connect, ' \ 'raising an error') raise OpenFacebookException('please authenticate') return next_redirect(request)
def connect(request, graph): ''' Exception and validation functionality around the _connect view Separated this out from _connect to preserve readability Don't bother reading this code, skip to _connect for the bit you're interested in :) ''' backend = get_registration_backend() context = RequestContext(request) # validation to ensure the context processor is enabled if not context.get('FACEBOOK_APP_ID'): message = 'Please specify a Facebook app id and ensure the context processor is enabled' logger.info('CO01 Please specify a Facebook app id and ensure the context processor is enabled') raise ValueError(message) try: response = _connect(request, graph) except open_facebook_exceptions.FacebookUnreachable, e: logger.info('CO02 Probably slow FB') # often triggered when Facebook is slow warning_format = u'%s, often caused by Facebook slowdown, error %s' warn_message = warning_format % (type(e), e.message) send_warning(warn_message, e=e) additional_params = dict(fb_error_or_cancel=1) response = backend.post_error(request, additional_params)
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: logger.info('trying to connect using facebook') graph = require_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.id for u in e.users] ids_string = ','.join(map(str, user_ids)) return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect(request, user) #compatability for django registration backends which return tuples instead of a response #alternatively we could wrap django registration backends, but that would be hard to understand response = response if isinstance(response, HttpResponse) else redirect(response) return response
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: require_persistent_graph(request) logger.info('trying to connect using facebook') graph = get_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: warn_message = u'Incomplete profile data encountered '\ u'with error %s' % e.message.decode('utf-8', 'replace') send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: response = backend.post_registration_redirect(request, user) return response else: if 'attempt' in request.GET: return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) else: logger.info('Facebook authentication needed for connect, ' \ 'raising an error') raise OpenFacebookException('please authenticate') return next_redirect(request)
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' #test code time to remove uri = 'http://%s%s?facebook_login=1' % (request.META['HTTP_HOST'], request.path) if request.GET.get('redirect'): return facebook_login_required(uri, scope='read_stream') context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: graph = get_facebook_graph(request) if graph: facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) except facebook_exceptions.IncompleteProfileError, e: warn_message = u'Incomplete profile data encountered '\ 'with error %s' % e logger.warn(warn_message, exc_info=sys.exc_info(), extra={ 'request': request, 'data': { 'username': request.user.username, 'facebook_data': facebook.facebook_profile_data(), 'body': unicode(e), } }) context['facebook_mode'] = True context['form'] = e.form return render_to_response( 'registration/registration_form.html', context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: return user.get_profile().post_facebook_registration(request) else: return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) return next_redirect(request)
def _set_original_url(self, request): self.original_url = '' scheme, netloc = urlparse.urlparse( request.META.get("HTTP_X_ORIGINAL_URL", ""))[:2] if netloc: context = RequestContext(request) proxy_prefix = context.get('PROXY_REWRITE_RULE', '') self.original_url = urlparse.urlunparse( (scheme, netloc, proxy_prefix, '', '', ''))
def render_to_template(request, context=None): """Renders a page directly to it's default template defined, raises 404 if current request is not a valid CMS page or if the related template doesn't define a template for it.""" ctx = RequestContext(request) page = ctx.get("cms") if page is None or page.tpl.TEMPLATE is None: raise Http404("Not found") return render_to_response(page.tpl.TEMPLATE, context or {}, ctx)
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' context = RequestContext(request) assert context.get( 'FACEBOOK_APP_ID' ), 'Please specify a facebook app id and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: facebook = get_facebook_graph(request) if facebook.is_authenticated(): facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) except facebook_exceptions.IncompleteProfileError, e: logger.error(unicode(e), exc_info=sys.exc_info(), extra={ 'request': request, 'data': { 'username': request.user.username, 'facebook_data': facebook.facebook_profile_data(), 'body': unicode(e), } }) context['facebook_mode'] = True context['form'] = e.form return render_to_response( 'registration/registration_form.html', context) if action is CONNECT_ACTIONS.CONNECT: messages.info( request, _("You have connected your account to %s's facebook profile" ) % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: response = user.get_profile().post_facebook_registration() return response else: return next_redirect(request, additional_params=dict(fb_error_or_cancel=1), next_key=['error_next', 'next']) return next_redirect(request)
def connect(request): """ Handles the view logic around connect user - (if authenticated) connect the user - login - register """ context = RequestContext(request) assert context.get("FACEBOOK_APP_ID"), ( "Please specify a facebook app id " "and ensure the context processor is enabled" ) facebook_login = bool(int(request.REQUEST.get("facebook_login", 0))) if facebook_login: # code to redirect if we don't have adequate permissions from django_facebook.utils import test_permissions scope_list = facebook_settings.FACEBOOK_DEFAULT_SCOPE # standardizing the url to prevent things like attempt from being included redirect_uri = request.build_absolute_uri(request.path) + "?facebook_login=1" oauth_url, redirect_uri = get_oauth_url(request, scope_list, redirect_uri=redirect_uri) if not test_permissions(request, scope_list, redirect_uri): return HttpResponseRedirect(oauth_url) graph = get_persistent_graph(request) if graph: facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): facebook_data = facebook.facebook_profile_data() # either, login register or connect the user try: action, user = connect_user(request) logger.info("Django facebook, action was %s", action) except facebook_exceptions.IncompleteProfileError, e: warn_message = u"Incomplete profile data encountered " u"with error %s" % e send_warning(warn_message, e=e, facebook_data=facebook.facebook_profile_data()) context["facebook_mode"] = True context["form"] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context ) if action is CONNECT_ACTIONS.CONNECT: messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data["name"], ) elif action is CONNECT_ACTIONS.REGISTER: return user.get_profile().post_facebook_registration(request) else: return next_redirect(request, next_key=["error_next", "next"], additional_params=dict(fb_error_or_cancel=1)) return next_redirect(request)
def handle_uploaded_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): f = request.FILES['arquivo'] buf = f.read() parser = ParseNFeHtml() mapNfe2 = parser.doParser(buf) markup = float(request.POST['markup']) prodDict = mapNfe2['produtos'] totalVenda = 0 for p in prodDict: p['custo'] = p['valor'] + p['frete'] + p['seguro'] + p['ipi'] - p['desconto'] p['preco'] = p['valor'] * markup / p['qtd'] totalVenda += p['preco'] * p['qtd'] tableProd = NFe2ProdutoTable(prodDict) markupReal = (totalVenda / mapNfe2['valores']['total']) if abs(markupReal - markup) > 0.005: msgError = "Atenção o markup sobre o preço de custo esta diferente!!!! O markup está %.3f e foi pedido %.3f" %( markupReal, markup ) else: msgError = "" return render(request, 'core/detalhesnfe.html', { 'table': tableProd, 'nfe': mapNfe2, 'totalVenda': totalVenda, 'msgError': msgError}) else: return direct_to_template(request, 'core/upload.html', {'form': form}) else: context = RequestContext(request) print request.POST tableProd = context.get('table') if not(tableProd): form = UploadFileForm() return direct_to_template(request, 'core/upload.html', {'form': form}) return render(request, 'core/detalhesnfe.html', {'table': tableProd})
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: facebook = get_facebook_graph(request) if facebook.is_authenticated(): facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) except facebook_exceptions.IncompleteProfileError, e: logger.warn(u'Incomplete profile data encountered with error %s' % e, exc_info=sys.exc_info(), extra={ 'request': request, 'data': { 'username': request.user.username, 'facebook_data': facebook.facebook_profile_data(), 'body': unicode(e), } }) context['facebook_mode'] = True context['form'] = e.form return render_to_response('registration/registration_form.html', context) if action is CONNECT_ACTIONS.CONNECT: messages.info(request, _("You have connected your account to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: response = user.get_profile().post_facebook_registration(request) return response else: return next_redirect(request, additional_params=dict(fb_error_or_cancel=1), next_key=['error_next', 'next']) return next_redirect(request)
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: logger.info('trying to connect using facebook') graph = require_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.id for u in e.users] ids_string = ','.join(map(str, user_ids)) return next_redirect( request, next_key=['error_next', 'next'], additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect( request, user) #compatability for django registration backends which return tuples instead of a response #alternatively we could wrap django registration backends, but that would be hard to understand response = response if isinstance( response, HttpResponse) else redirect(response) return response
def sources_schedules_list_ajax(request, city=None, cinema=None, id=None): kinohod_key = settings.KINOHOD_APIKEY_CLIENT current_site = request.current_site current_language = translation.get_language() user = request.user if request.user.is_authenticated() else None filter = {} film_list = [] country = None alert = None city_name = None cinema_name = None flag = False # если вместо ид (цифры) города передали буквы if city: try: city = int(city) flag = True except (UnicodeEncodeError, ValueError): city = 'error' # если вместо ид (цифры) кинотеатра передали буквы if cinema: try: cinema = int(cinema) except (UnicodeEncodeError, ValueError): cinema = 'error' acc_list = RequestContext(request).get('acc_list') if acc_list: user_country = acc_list.get('country_id') if user_country: country = user_country user_city = acc_list.get('city_id') if not city and city != 'error': city = user_city if current_site.domain == 'kinoafisha.in.ua': country = 43 # если указана страна у юзера if country: filter = {'cinema__cinema__city__country__id': country} today = datetime.date.today() #today = datetime.date(2013, 10, 17) next_month = today + datetime.timedelta(days=30) cities = list( SourceSchedules.objects.filter(dtime__gte=today, dtime__lte=next_month, cinema__cinema__city__name__status=3, cinema__cinema__name__status=1). filter(**filter).exclude(film__source_id=0).values( 'cinema__cinema__city', 'cinema__cinema__city__name__name', 'cinema__cinema', 'cinema__cinema__name__name').distinct('cinema__cinema__city')) cities_dict = {} for i in cities: cin_dic = { 'name': i['cinema__cinema__name__name'], 'id': int(i['cinema__cinema']) } if cities_dict.get(i['cinema__cinema__city']): cities_dict[i['cinema__cinema__city']]['cinema'].append(cin_dic) else: cities_dict[i['cinema__cinema__city']] = { 'name': i['cinema__cinema__city__name__name'], 'id': int(i['cinema__cinema__city']), 'cinema': [cin_dic] } cities = sorted(cities_dict.values(), key=operator.itemgetter('name')) if cities: if city: if city != 'error': city_data = cities_dict.get(int(city)) # указан город и есть в БД if city_data: city = city_data # указан город и нет в БД else: city = None else: city = None else: # в первый раз без города, даю первый город в списке city = cities[0] if city: if not cinema: cinemas = sorted(city['cinema'], key=operator.itemgetter('name')) cinema = cinemas[0]['id'] city = city['id'] if city == 'error': city = None if city: city_name = NameCity.objects.get(city__id=city, status=3) if cinema and cinema != 'error': try: cinema_name = NameCinema.objects.get(cinema__id=cinema, status=1, cinema__city__id=city) except NameCinema.DoesNotExist: pass except NameCinema.MultipleObjectsReturned: cinema_name = NameCinema.objects.filter( cinema__id=cinema, status=1, cinema__city__id=city)[0] film_list = set( list( SourceSchedules.objects.filter( dtime__gte=today, dtime__lte=next_month, cinema__cinema__id=cinema, cinema__cinema__city__id=city).exclude( film__source_id=0).values_list('film__kid', flat=True))) else: cinema_name = '' fnames_dict = {} t = '' uk_films = [] if current_site.domain == 'kinoafisha.in.ua': t = 'kua_' if city: if current_language == 'uk': uk_sources = ('http://www.okino.ua/', 'http://kino-teatr.ua/') film_name = SourceFilms.objects.select_related( 'source_obj').filter(source_obj__url__in=uk_sources, kid__in=film_list) for n in film_name: if n.source_obj.url == 'http://www.okino.ua/' and n.name_alter: if fnames_dict.get(n.kid): fnames_dict[n.kid]['names'].append(n.name_alter) else: fnames_dict[n.kid] = { 'names': [n.name_alter], 'genres': [], 'rate_imdb': [], 'obj': None } if re.findall(ur'[а-яА-Я]', n.name_alter): uk_films.append(n.kid) elif n.source_obj.url == 'http://kino-teatr.ua/': if fnames_dict.get(n.kid): fnames_dict[n.kid]['names'].append(n.name) else: fnames_dict[n.kid] = { 'names': [n.name], 'genres': [], 'rate_imdb': [], 'obj': None } if re.findall(ur'[а-яА-Я]', n.name): uk_films.append(n.kid)
def local_home(request, entity_slug=None, entity_id=None, tags=None, template="qa/question_list.html"): """ A home page for an entity including questions and candidates """ if request.user.is_anonymous() and not tags and not request.GET: ret = cache.get(entity_home_key(entity_id)) if ret: return ret context = RequestContext(request) entity = context.get('entity', None) if not entity or entity.division.index != 3: raise Http404(_("Bad Entity")) if request.user.is_authenticated() and not request.user.profile.locality: messages.error(request,_('Please update your locality in your user profile to use the site')) return HttpResponseRedirect(reverse('edit_profile')) questions = Question.on_site.select_related('author', 'entity').prefetch_related('answers__author').filter(entity=entity, is_deleted=False) only_flagged = request.GET.get('filter', False) == 'flagged' if only_flagged: questions = questions.filter(flags_count__gte = 1) order_opt = False order = 'flags_count' else: order_opt = request.GET.get('order', 'rating') try: order = ORDER_OPTIONS[order_opt] except KeyError: order = ORDER_OPTIONS['rating'] questions = questions.order_by(order) if tags: current_tags = Tag.objects.filter(slug__in=tags.split(',')) questions = questions.filter(tags__in=current_tags) else: current_tags = None if entity: tags = Tag.objects.filter(qa_taggedquestion_items__content_object__entity=entity,\ qa_taggedquestion_items__content_object__is_deleted=False).\ annotate(num_times=Count('qa_taggedquestion_items')).\ order_by("-num_times","slug") need_editors = Profile.objects.need_editors(entity) users_count = entity.profile_set.count() else: users_count = Profile.objects.count() candidate_lists = CandidateList.objects.select_related().filter(entity=entity) candidates = User.objects.filter(candidate__isnull=False).filter(profile__locality=entity) list_id = request.GET.get('list', default='mayor') if list_id == 'mayor': candidate_list = None candidates = candidates.filter(candidate__for_mayor=True) else: try: candidate_list = candidate_lists.get(pk=list_id) except (CandidateList.DoesNotExist, ValueError): messages.error(request, _('No such candidate list: ' + list_id)) return HttpResponseRedirect(request.path) candidates = candidates.filter(candidate__candidate_list=candidate_list) candidates = candidates.annotate(num_answers=models.Count('answers')).\ order_by('-num_answers') candidate_lists = candidate_lists.annotate( \ num_answers=models.Count('candidates__answers')).\ order_by('-num_answers') answers_count = Answer.objects.filter(question__entity=entity, question__is_deleted=False).count() stats = CBS_STATS.get(entity.code, {"totalpopulation": 0, "numofcouncilman": "", "socioeco": "", "voting":""}) context.update({ 'tags': tags, 'questions': questions, 'by_date': order_opt == 'date', 'by_rating': order_opt == 'rating', 'only_flagged': only_flagged, 'current_tags': current_tags, 'need_editors': need_editors, 'candidates': candidates, 'candidate_list': candidate_list, 'candidate_lists': candidate_lists, 'users_count': users_count, 'answers_count': answers_count, 'stats': stats, }) ret = render(request, template, context) if request.user.is_anonymous() and not tags and not request.GET: cache.set('local_home_%s' % entity_id, ret, timeout = 36000) return ret
def connect(request): """ Handles the view logic around connect user - (if authenticated) connect the user - login - register """ backend = get_registration_backend() context = RequestContext(request) assert context.get("FACEBOOK_APP_ID"), ( "Please specify a facebook app id " "and ensure the context processor is enabled" ) facebook_login = bool(int(request.REQUEST.get("facebook_login", 0))) if facebook_login: logger.info("trying to connect using facebook") graph = require_persistent_graph(request) if graph: logger.info("found a graph object") facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info("facebook is authenticated") facebook_data = facebook.facebook_profile_data() # either, login register or connect the user try: action, user = connect_user(request) logger.info("Django facebook performed action: %s", action) except facebook_exceptions.IncompleteProfileError, e: # show them a registration form to add additional data warning_format = u"Incomplete profile data encountered with error %s" warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context["facebook_mode"] = True context["form"] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context ) if action is CONNECT_ACTIONS.CONNECT: # connect means an existing account was attached to facebook messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data["name"], ) elif action is CONNECT_ACTIONS.REGISTER: # hook for tying in specific post registration functionality response = backend.post_registration_redirect(request, user) # compatability for django registration backends which return tuples instead of a response # alternatively we could wrap django registration backends, but that would be hard to understand response = response if isinstance(response, HttpResponse) else redirect(response) return response else: if "attempt" in request.GET: return next_redirect( request, next_key=["error_next", "next"], additional_params=dict(fb_error_or_cancel=1) ) else: logger.info("Facebook authentication needed for connect, " "raising an error") raise OpenFacebookException("please authenticate")
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: require_persistent_graph(request) logger.info('trying to connect using facebook') graph = get_persistent_graph(request) if graph: logger.info('found a graph object') klass = get_facebook_user_converter_class() facebook = klass(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect( request, user) return response else: if 'attempt' in request.GET: return next_redirect( request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) else: logger.info('Facebook authentication needed for connect, ' \ 'raising an error') raise OpenFacebookException('please authenticate') #for CONNECT and LOGIN we simple redirect to the next page return next_redirect( request, default=facebook_settings.FACEBOOK_LOGIN_DEFAULT_REDIRECT)
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: require_persistent_graph(request) logger.info('trying to connect using facebook') graph = get_persistent_graph(request) if graph: logger.info('found a graph object') klass = get_facebook_user_converter_class() facebook = klass(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect(request, user) return response else: if 'attempt' in request.GET: return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) else: logger.info('Facebook authentication needed for connect, ' \ 'raising an error') raise OpenFacebookException('please authenticate') #for CONNECT and LOGIN we simple redirect to the next page return next_redirect(request, default=facebook_settings.FACEBOOK_LOGIN_DEFAULT_REDIRECT)
def local_home(request, entity_slug=None, entity_id=None, tags=None, template="qa/question_list.html"): """ A home page for an entity including questions and candidates """ if request.user.is_anonymous() and not tags and not request.GET: ret = cache.get(entity_home_key(entity_id)) if ret: return ret context = RequestContext(request) entity = context.get('entity', None) if not entity or entity.division.index != 3: raise Http404(_("Bad Entity")) if request.user.is_authenticated() and not request.user.profile.locality: messages.error( request, _('Please update your locality in your user profile to use the site' )) return HttpResponseRedirect(reverse('edit_profile')) questions = Question.on_site.select_related( 'author', 'entity').prefetch_related('answers__author').filter(entity=entity, is_deleted=False) only_flagged = request.GET.get('filter', False) == 'flagged' if only_flagged: questions = questions.filter(flags_count__gte=1) order_opt = False order = 'flags_count' else: order_opt = request.GET.get('order', 'rating') try: order = ORDER_OPTIONS[order_opt] except KeyError: order = ORDER_OPTIONS['rating'] questions = questions.order_by(order) if tags: current_tags = Tag.objects.filter(slug__in=tags.split(',')) questions = questions.filter(tags__in=current_tags) else: current_tags = None if entity: tags = Tag.objects.filter(qa_taggedquestion_items__content_object__entity=entity,\ qa_taggedquestion_items__content_object__is_deleted=False).\ annotate(num_times=Count('qa_taggedquestion_items')).\ order_by("-num_times","slug") need_editors = Profile.objects.need_editors(entity) users_count = entity.profile_set.count() else: users_count = Profile.objects.count() candidate_lists = CandidateList.objects.select_related().filter( entity=entity) candidates = User.objects.filter(candidate__isnull=False).filter( profile__locality=entity) list_id = request.GET.get('list', default='mayor') if list_id == 'mayor': candidate_list = None candidates = candidates.filter(candidate__for_mayor=True) else: try: candidate_list = candidate_lists.get(pk=list_id) except (CandidateList.DoesNotExist, ValueError): messages.error(request, _('No such candidate list: ' + list_id)) return HttpResponseRedirect(request.path) candidates = candidates.filter( candidate__candidate_list=candidate_list) candidates = candidates.annotate(num_answers=models.Count('answers')).\ order_by('-num_answers') candidate_lists = candidate_lists.annotate( \ num_answers=models.Count('candidates__answers')).\ order_by('-num_answers') answers_count = Answer.objects.filter(question__entity=entity, question__is_deleted=False).count() stats = CBS_STATS.get(entity.code, { "totalpopulation": 0, "numofcouncilman": "", "socioeco": "", "voting": "" }) context.update({ 'tags': tags, 'questions': questions, 'by_date': order_opt == 'date', 'by_rating': order_opt == 'rating', 'only_flagged': only_flagged, 'current_tags': current_tags, 'need_editors': need_editors, 'candidates': candidates, 'candidate_list': candidate_list, 'candidate_lists': candidate_lists, 'users_count': users_count, 'answers_count': answers_count, 'stats': stats, }) ret = render(request, template, context) if request.user.is_anonymous() and not tags and not request.GET: cache.set('local_home_%s' % entity_id, ret, timeout=36000) return ret
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: #code to redirect if we don't have adequate permissions from django_facebook.utils import test_permissions scope_list = ['email','user_about_me','user_birthday','user_website'] #standardizing the url to prevent things like attempt from being included redirect_uri = request.build_absolute_uri(request.path) + '?facebook_login=1' oauth_url, redirect_uri = get_oauth_url(request, scope_list, redirect_uri=redirect_uri) if not test_permissions(request, scope_list, redirect_uri): return HttpResponseRedirect(oauth_url) graph = get_persistent_graph(request) if graph: facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) except facebook_exceptions.IncompleteProfileError, e: warn_message = u'Incomplete profile data encountered '\ 'with error %s' % e logger.warn(warn_message, exc_info=sys.exc_info(), extra={ 'request': request, 'data': { 'username': request.user.username, 'facebook_data': facebook.facebook_profile_data(), 'body': unicode(e), } }) context['facebook_mode'] = True context['form'] = e.form return render_to_response( 'registration/registration_form.html', context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: return user.get_profile().post_facebook_registration(request) else: return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) return next_redirect(request)
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: #code to redirect if we don't have adequate permissions from django_facebook.utils import test_permissions scope_list = facebook_settings.FACEBOOK_DEFAULT_SCOPE #standardizing the url to prevent things like attempt from being included redirect_uri = request.build_absolute_uri( request.path) + '?facebook_login=1' oauth_url, redirect_uri = get_oauth_url(request, scope_list, redirect_uri=redirect_uri) if not test_permissions(request, scope_list, redirect_uri): return HttpResponseRedirect(oauth_url) graph = get_persistent_graph(request) if graph: facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook, action was %s', action) except facebook_exceptions.IncompleteProfileError, e: warn_message = u'Incomplete profile data encountered '\ u'with error %s' % e send_warning( warn_message, e=e, facebook_data=facebook.facebook_profile_data()) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: return user.get_profile().post_facebook_registration( request) else: return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) return next_redirect(request)