def show_pad(request, group_name, pad_name): # test if user is in group if not request.user.groups.filter(name=group_name).exists(): return TemplateResponse(request, 'etherpad/forbidden.html', { 'group_name': group_name, }, status=403) ep = Etherpad() try: ep.create_session(request.user, group_name) group_id = ep.get_group_id(group_name) pad_url = '{0}/p/{1}${2}'.format( settings.ETHERPAD_URL, group_id, pad_name) cookie = ep.get_session_cookie(request.user) except URLError: return TemplateResponse(request, 'etherpad/server_error.html', { }, status=500) is_fullscreen = 'fullscreen' in request.GET response = TemplateResponse(request, 'etherpad/pad.html', { 'pad_url': pad_url, 'group_name': group_name, 'pad_name': pad_name, 'fullscreen': is_fullscreen, 'base_template': 'base_raw.html' if is_fullscreen else 'base.html' }) cookie_domain = '.' + request.get_host() response.set_cookie('sessionID', cookie, domain=cookie_domain) response['Access-Control-Allow-Origin'] = "https://ep.mafiasi.de" return response
def post(self, *args, **kwargs): # Get the chosen options ids. post = self.request.POST.copy() try: del post["csrfmiddlewaretoken"] except KeyError: pass choice_ids = map(lambda v: int(v), post.values()) # Create a new answer and add the voter and the choices. voter = get_voter(self.request) answer = Answer.objects.create( gallup_id=self.kwargs["gallup_id"], voter=voter, client_identifier=get_client_identifier(self.request) ) choices = Option.objects.filter(pk__in=choice_ids).all() answer.choices.add(*choices) context = self.get_context_data() context["show_results"] = True context["disabled"] = True context["answered_options"] = choices response = TemplateResponse(self.request, self.template_name, context) response.set_cookie(Voter.VOTER_COOKIE, voter.voter_id) return response
def show_pad(request, group_name, pad_name): # test if user is in group if not request.user.groups.filter(name=group_name).exists(): return TemplateResponse(request, 'etherpad/forbidden-notingroup.html', { 'group_name': group_name, }, status=403) ep = Etherpad() try: ep.create_session(request.user, group_name) group_id = ep.get_group_id(group_name) pad_url = '{0}/p/{1}${2}'.format(settings.ETHERPAD_URL, group_id, pad_name.replace('/', '_')) cookie = ep.get_session_cookie(request.user) except URLError: return TemplateResponse(request, 'etherpad/server_error.html', {}, status=500) is_fullscreen = 'fullscreen' in request.GET response = TemplateResponse( request, 'etherpad/pad.html', { 'pad_url': pad_url, 'group_name': group_name, 'pad_name': pad_name, 'fullscreen': is_fullscreen, 'base_template': 'base_raw.html' if is_fullscreen else 'base.html' }) cookie_domain = '.' + settings.EP_COOKIE_DOMAIN response.set_cookie('sessionID', cookie, domain=cookie_domain) response['Access-Control-Allow-Origin'] = "https://ep.mafiasi.de" return response
def view_cart(request): if 'cart_id' in request.COOKIES: cart_id = request.COOKIES["cart_id"] cart, created = Cart.objects.get_or_create(id=cart_id) else: if request.user.is_authenticated(): cart, object = Cart.objects.get_or_create(user=request.user) else: cart = Cart.objects.create(user=None) if request.is_ajax(): ret_dict = {} ret_dict['success'] = True ret_dict['item_type_count'] = cart.cart_products.all().count() from shopcart.serializer import serializer # serialized_cart = serializer(cart,datetime_format='string',output_type='dict',many=True) # 先不返回购物车中商品信息 serialized_cart = serializer(cart, datetime_format='string', output_type='dict', many=False) # logger.debug(serialized_cart) ret_dict['cart'] = serialized_cart return JsonResponse(ret_dict) else: ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Cart' if request.method == 'GET': ctx['cart'] = cart response = TemplateResponse(request, System_Config.get_template_name() + '/cart_detail.html', ctx) response.set_cookie('cart_id', cart.id, max_age=3600 * 24 * 365) return response
def orders(request): if request.user.is_authenticated and request.user.is_staff: context = {} context['site_url'] = '/' response = TemplateResponse(request, "admin/orders.html", context) response.set_cookie('user_id', request.user.id) return response else: return HttpResponseRedirect("/admin/login/?next=/admin/")
def view_quote_cart(request): if 'cart_id' in request.COOKIES: cart_id = request.COOKIES["cart_id"] cart, created = Cart.objects.get_or_create(id=cart_id) else: if request.user.is_authenticated(): cart, object = Cart.objects.get_or_create(user=request.user) else: cart = Cart.objects.create(user=None) if request.is_ajax(): ret_dict = {} ret_dict['success'] = True ret_dict['item_type_count'] = cart.cart_products.all().count() from shopcart.serializer import serializer # serialized_cart = serializer(cart,datetime_format='string',output_type='dict',many=True) # 先不返回购物车中商品信息 serialized_cart = serializer(cart, datetime_format='string', output_type='dict', many=False) # logger.debug(serialized_cart) ret_dict['cart'] = serialized_cart return JsonResponse(ret_dict) else: ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Cart' if request.method == 'GET': ctx['cart'] = cart response = TemplateResponse( request, System_Config.get_template_name() + '/quote.html', ctx) response.set_cookie('cart_id', cart.id, max_age=3600 * 24 * 365) def get_all_top_menu(): top_menu_list = Menu.objects.filter(parent=None) return top_menu_list top_menu_list = get_all_top_menu() ctx['menu_list'] = top_menu_list return response
def home(request): duoshuo_jwt_token = None ctx = { 'settings': settings, } if request.user.is_authenticated(): ctx['profile'] = UserProfile.objects.get(user_id=request.user.id) #django 1.7没有get_profile # 实现JWT登录,参看:http://dev.duoshuo.com/docs/501e6ce1cff715f71800000d token = { "short_name": settings.DUOSHUO_SHORT_NAME, "user_key": request.user.id, "name": request.user.username } ctx['duoshuo_jwt_token'] = duoshuo_jwt_token = jwt.encode(token, settings.DUOSHUO_SECRET) response = TemplateResponse(request, 'home.html', ctx) response.set_cookie('duoshuo_token', duoshuo_jwt_token) return response
def get(self, request, *args, **kwargs): print(request.COOKIES, 3500) response = TemplateResponse(request, self.template_name, {}, status=HTTP_200_OK) response.set_cookie("csrftokensdf", "8888888888888888888") response.set_cookie("midsdf", "333333333333333333333333333") response.set_cookie("rursdf", "Alex-4000") return response
def town_square(request): SHOW_DRESSING = request.GET.get('dressing', False) tab = request.GET.get('tab', request.COOKIES.get('tab', 'connect')) title, desc, page_seo_text_insert, avatar_url, is_direct_link, admin_link = get_param_metadata( request, tab) max_length_offset = abs( ((request.user.profile.created_on if request.user.is_authenticated else timezone.now()) - timezone.now()).days) max_length = 280 + max_length_offset if not SHOW_DRESSING: is_search = "activity:" in tab or "search-" in tab trending_only = int(request.GET.get('trending', 0)) context = { 'title': title, 'card_desc': desc, 'avatar_url': avatar_url, 'use_pic_card': True, 'is_search': is_search, 'is_direct_link': is_direct_link, 'page_seo_text_insert': page_seo_text_insert, 'nav': 'home', 'target': f'/activity?what={tab}&trending_only={trending_only}', 'tab': tab, 'tags': tags, 'max_length': max_length, 'max_length_offset': max_length_offset, 'admin_link': admin_link, 'now': timezone.now(), 'is_townsquare': True, 'trending_only': bool(trending_only), } return TemplateResponse(request, 'townsquare/index.html', context) tabs, tab, is_search, search, hackathon_tabs = get_sidebar_tabs(request) offers_by_category = get_offers(request) matching_leaderboard, current_match_round = get_miniclr_info(request) is_subscribed = get_subscription_info(request) announcements = Announcement.objects.current().filter(key='townsquare') view_tags = get_tags(request) following_tribes = get_following_tribes(request) suggested_tribes = get_suggested_tribes(request) # render page context trending_only = int(request.GET.get('trending', 0)) context = { 'title': title, 'card_desc': desc, 'avatar_url': avatar_url, 'use_pic_card': True, 'is_search': is_search, 'is_direct_link': is_direct_link, 'page_seo_text_insert': page_seo_text_insert, 'nav': 'home', 'target': f'/activity?what={tab}&trending_only={trending_only}', 'tab': tab, 'tabs': tabs, 'max_length': max_length, 'max_length_offset': max_length_offset, 'SHOW_DRESSING': SHOW_DRESSING, 'hackathon_tabs': hackathon_tabs, 'REFER_LINK': f'https://gitcoin.co/townsquare/?cb=ref:{request.user.profile.ref_code}' if request.user.is_authenticated else None, 'matching_leaderboard': matching_leaderboard, 'current_match_round': current_match_round, 'admin_link': admin_link, 'now': timezone.now(), 'is_townsquare': True, 'trending_only': bool(trending_only), 'search': search, 'tags': view_tags, 'suggested_actions': SuggestedAction.objects.filter(active=True).order_by('-rank'), 'announcements': announcements, 'is_subscribed': is_subscribed, 'offers_by_category': offers_by_category, 'following_tribes': following_tribes, 'suggested_tribes': suggested_tribes, } if 'tribe:' in tab: key = tab.split(':')[1] profile = Profile.objects.get(handle=key.lower()) if profile.is_org: context['tribe'] = profile response = TemplateResponse(request, 'townsquare/index.html', context) if request.GET.get('tab'): if ":" not in request.GET.get('tab'): response.set_cookie('tab', request.GET.get('tab')) return response
def town_square(request): try: audience = redis.get(f"townsquare:audience") audience = str(audience.decode('utf-8')) if audience else '39102' except KeyError: data_results = JSONStore.objects.filter(view='results', key=None).first() if data_results: audience = data_results.data['audience'] redis.set('townsquare:audience', audience) SHOW_DRESSING = request.GET.get('dressing', False) tab = request.GET.get('tab', request.COOKIES.get('tab', 'connect')) try: pinned = PinnedPost.objects.get(what=tab) except PinnedPost.DoesNotExist: pinned = None title, desc, page_seo_text_insert, avatar_url, is_direct_link, admin_link = get_param_metadata( request, tab) if not SHOW_DRESSING: is_search = "activity:" in tab or "search-" in tab trending_only = int(request.GET.get('trending', 0)) context = { 'title': title, 'card_desc': desc, 'avatar_url': avatar_url, 'use_pic_card': True, 'is_search': is_search, 'is_direct_link': is_direct_link, 'page_seo_text_insert': page_seo_text_insert, 'nav': 'home', 'what': tab, 'can_pin': can_pin(request, tab), 'pinned': pinned, 'target': f'/activity?what={tab}&trending_only={trending_only}', 'tab': tab, 'tags': tags, 'admin_link': admin_link, 'now': timezone.now(), 'is_townsquare': True, 'trending_only': bool(trending_only), 'audience': audience } return TemplateResponse(request, 'townsquare/index.html', context) tabs, tab, is_search, search, hackathon_tabs = get_sidebar_tabs(request) offers_by_category = get_offers(request) matching_leaderboard, current_match_round = get_miniclr_info(request) is_subscribed = get_subscription_info(request) announcements = Announcement.objects.current().filter(key='townsquare') view_tags = get_tags(request) following_tribes = get_following_tribes(request) suggested_tribes = get_suggested_tribes(request) # render page context trending_only = int(request.GET.get('trending', 0)) context = { 'title': title, 'card_desc': desc, 'avatar_url': avatar_url, 'use_pic_card': True, 'is_search': is_search, 'is_direct_link': is_direct_link, 'page_seo_text_insert': page_seo_text_insert, 'nav': 'home', 'target': f'/activity?what={tab}&trending_only={trending_only}', 'tab': tab, 'what': tab, 'can_pin': can_pin(request, tab), 'tabs': tabs, 'pinned': pinned, 'SHOW_DRESSING': SHOW_DRESSING, 'hackathon_tabs': hackathon_tabs, 'REFER_LINK': f'https://gitcoin.co/townsquare/?cb=ref:{request.user.profile.ref_code}' if request.user.is_authenticated else None, 'matching_leaderboard': matching_leaderboard, 'current_match_round': current_match_round, 'admin_link': admin_link, 'now': timezone.now(), 'is_townsquare': True, 'trending_only': bool(trending_only), 'search': search, 'tags': view_tags, 'suggested_actions': SuggestedAction.objects.filter(active=True).order_by('-rank'), 'announcements': announcements, 'is_subscribed': is_subscribed, 'offers_by_category': offers_by_category, 'TOKENS': request.user.profile.token_approvals.all() if request.user.is_authenticated else [], 'following_tribes': following_tribes, 'suggested_tribes': suggested_tribes, 'audience': audience } if 'tribe:' in tab: key = tab.split(':')[1] profile = Profile.objects.get(handle=key.lower()) if profile.is_org: context['tribe'] = profile response = TemplateResponse(request, 'townsquare/index.html', context) if request.GET.get('tab'): if ":" not in request.GET.get('tab'): response.set_cookie('tab', request.GET.get('tab')) return response
def town_square(request): # setup tabas tabs = [{ 'title': "Everywhere", 'slug': 'everywhere', 'helper_text': 'Activity everywhere in the Gitcoin network', }] default_tab = 'everywhere' if request.user.is_authenticated: num_business_relationships = len( set(get_my_earnings_counter_profiles(request.user.profile.pk))) if num_business_relationships: new_tab = { 'title': f"Relationships ({num_business_relationships})", 'slug': 'my_tribes', 'helper_text': f'Activity from the {num_business_relationships} users who you\'ve done business with Gitcoin', } tabs = [new_tab] + tabs default_tab = 'my_tribes' num_grants_relationships = len(set(get_my_grants( request.user.profile))) if num_grants_relationships: new_tab = { 'title': f'Grants ({num_grants_relationships})', 'slug': f'grants', 'helper_text': f'Activity on the {num_grants_relationships} Grants you\'ve created or funded.', } tabs = [new_tab] + tabs default_tab = 'grants' connect_last_24_hours = Activity.objects.filter( activity_type='status_update', created_on__gt=timezone.now() - timezone.timedelta(hours=24)).count() if connect_last_24_hours: default_tab = 'connect' connect = { 'title': f"Connect ({connect_last_24_hours})", 'slug': f'connect', 'helper_text': f'The {connect_last_24_hours} announcements, requests for help, jobs, mentorship, or other connective requests on Gitcoin in the last 24 hours.', } tabs = [connect] + tabs if request.user.is_authenticated: hackathons = HackathonEvent.objects.filter( start_date__lt=timezone.now(), end_date__gt=timezone.now()) if hackathons.count(): user_registered_hackathon = request.user.profile.hackathon_registration.filter( registrant=request.user.profile, hackathon__in=hackathons).first() if user_registered_hackathon: default_tab = f'hackathon:{user_registered_hackathon.hackathon.pk}' connect = { 'title': user_registered_hackathon.hackathon.name, 'slug': default_tab, 'helper_text': f'Activity from the {user_registered_hackathon.hackathon.name} Hackathon.', } tabs = [connect] + tabs # set tab if request.COOKIES.get('tab'): all_tabs = [tab.get('slug') for tab in tabs] if request.COOKIES.get('tab') in all_tabs: default_tab = request.COOKIES.get('tab') tab = request.GET.get('tab', default_tab) is_search = "activity:" in tab or "search-" in tab if is_search: tabs.append({ 'title': "Search", 'slug': tab, }) search = '' if "search-" in tab: search = tab.split('-')[1] # get offers offer_pks = [] offers_by_category = {} for key in ['secret', 'random', 'daily', 'weekly', 'monthly']: next_time_available = get_next_time_available(key) offer = Offer.objects.current().filter(key=key).order_by('-pk').first() if offer: offer_pks.append(offer.pk) if request.user.is_authenticated: if request.user.profile.offeractions.filter(what='click', offer=offer): offer = None offers_by_category[key] = { 'offer': offer, 'time': next_time_available.strftime('%Y-%m-%dT%H:%M:%SZ'), } increment_offer_view_counts.delay(offer_pks) # subscriber info is_subscribed = False if request.user.is_authenticated: email_subscriber = request.user.profile.email_subscriptions.first() if email_subscriber: is_subscribed = email_subscriber.should_send_email_type_to( 'new_bounty_notifications') # announcements announcements = Announcement.objects.current() # title title = 'Home' desc = 'View the recent activity on the Gitcoin network' page_seo_text_insert = '' avatar_url = '' if "activity:" in tab: try: pk = int(tab.split(':')[1]) activity = Activity.objects.get(pk=pk) title = f"@{activity.profile.handle}'s comment on Gitcoin " desc = f"{activity.text}" comments_count = activity.comments.count() if comments_count: title += f"(+ {comments_count} comments)" avatar_url = activity.profile.avatar_url page_seo_text_insert = desc except: pass # render page context trending_only = int(request.GET.get('trending', 0)) context = { 'title': title, 'card_desc': desc, 'avatar_url': avatar_url, 'page_seo_text_insert': page_seo_text_insert, 'nav': 'home', 'target': f'/activity?what={tab}&trending_only={trending_only}', 'tab': tab, 'tabs': tabs, 'now': timezone.now(), 'trending_only': bool(trending_only), 'search': search, 'tags': [ ('#announce', 'bullhorn'), ('#mentor', 'terminal'), ('#jobs', 'code'), ('#help', 'laptop-code'), ('#other', 'briefcase'), ], 'announcements': announcements, 'is_subscribed': is_subscribed, 'offers_by_category': offers_by_category, } response = TemplateResponse(request, 'townsquare/index.html', context) if request.GET.get('tab'): response.set_cookie('tab', request.GET.get('tab')) return response
def search(request): search_query = request.GET.get('query', None).strip() page_num = request.GET.get('page', 1) # Search 分词: 按空格 & | ~ condition = None for word in search_query.split(' '): if condition is None: condition = Q(custom_title__icontains=word) | Q(intro__icontains=word) | Q(content__icontains=word) else: condition = condition | Q(custom_title__icontains=word) | Q(intro__icontains=word) | Q(content__icontains=word) search_results = [] if condition is not None: # 筛选:搜索 search_results = BlogDetailPage.objects.live().filter(condition).order_by('-first_published_at') '''if search_query: #search_results = BlogDetailPage.objects.live().search(search_query, operator='or') search_results = BlogDetailPage.objects.live().filter( Q(custom_title_icontains = search_query) | Q(intro_icontains = search_query) | Q(content_icontains = search_query) | Q(tags_icontains = search_query) ) ''' query = Query.get(search_query) print(search_results) # Record hit query.add_hit() else: search_results = BlogDetailPage.objects.none() # Pagination paginator = Paginator(search_results, 12) try: search_results = paginator.page(page_num) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) page_range = list(range(max(int(page_num)-2, 1), int(page_num))) + \ list(range(int(page_num), min(int(page_num)+2, paginator.num_pages)+1)) if page_range[0]-1 > 1: page_range.insert(0,'...') page_range.insert(0,1) elif page_range[0]-1 == 1: page_range.insert(0,1) if paginator.num_pages - page_range[-1] > 1: page_range.append('...') page_range.append(paginator.num_pages) elif paginator.num_pages - page_range[-1] == 1: page_range.append(paginator.num_pages) data = count_visits(request, BlogDetailPage.objects.all()[0]) context = {} context['client_ip'] = data['client_ip'] context['location'] = data['location'] context['total_hits'] = data['total_hits'] context['total_visitors'] =data['total_vistors'] context['cookie'] = data['cookie'] context['search_query'] = search_query context['search_results'] = search_results context['page_range'] = page_range response = TemplateResponse(request, 'search/search_result.html', context) response.set_cookie(context['cookie'], 'true', max_age=300) return response
def town_square(request): tabs, tab, is_search, search, hackathon_tabs = get_sidebar_tabs(request) offers_by_category = get_offers(request) matching_leaderboard, current_match_round = get_miniclr_info(request) is_subscribed = get_subscription_info(request) announcements = Announcement.objects.current().filter(key='townsquare') view_tags = get_tags(request) title, desc, page_seo_text_insert, avatar_url, is_direct_link, admin_link = get_param_metadata( request, tab) following_tribes = get_following_tribes(request) # render page context trending_only = int(request.GET.get('trending', 0)) context = { 'title': title, 'card_desc': desc, 'avatar_url': avatar_url, 'use_pic_card': True, 'is_search': is_search, 'is_direct_link': is_direct_link, 'page_seo_text_insert': page_seo_text_insert, 'nav': 'home', 'target': f'/activity?what={tab}&trending_only={trending_only}', 'tab': tab, 'tabs': tabs, 'hackathon_tabs': hackathon_tabs, 'REFER_LINK': f'https://gitcoin.co/townsquare/?cb=ref:{request.user.profile.ref_code}' if request.user.is_authenticated else None, 'matching_leaderboard': matching_leaderboard, 'current_match_round': current_match_round, 'admin_link': admin_link, 'now': timezone.now(), 'is_townsquare': True, 'trending_only': bool(trending_only), 'search': search, 'tags': view_tags, 'suggested_actions': SuggestedAction.objects.filter(active=True).order_by('-rank'), 'announcements': announcements, 'is_subscribed': is_subscribed, 'offers_by_category': offers_by_category, 'following_tribes': following_tribes } response = TemplateResponse(request, 'townsquare/index.html', context) if request.GET.get('tab'): if ":" not in request.GET.get('tab'): response.set_cookie('tab', request.GET.get('tab')) return response
def town_square(request): # setup tabas hours = 24 if not settings.DEBUG else 1000 posts_last_24_hours = lazy_round_number( Activity.objects.filter(created_on__gt=timezone.now() - timezone.timedelta(hours=hours)).count()) tabs = [{ 'title': f"Everywhere", 'slug': 'everywhere', 'helper_text': f'The {posts_last_24_hours} activity feed items everywhere in the Gitcoin network', 'badge': posts_last_24_hours }] default_tab = 'everywhere' if request.user.is_authenticated: num_business_relationships = lazy_round_number( len(set(get_my_earnings_counter_profiles( request.user.profile.pk)))) if num_business_relationships: new_tab = { 'title': f"Relationships", 'slug': 'my_tribes', 'helper_text': f'Activity from the {num_business_relationships} users who you\'ve done business with Gitcoin', 'badge': num_business_relationships } tabs = [new_tab] + tabs default_tab = 'my_tribes' num_grants_relationships = lazy_round_number( len(set(get_my_grants(request.user.profile)))) if num_grants_relationships: new_tab = { 'title': f'Grants', 'slug': f'grants', 'helper_text': f'Activity on the {num_grants_relationships} Grants you\'ve created or funded.', 'badge': num_grants_relationships } tabs = [new_tab] + tabs default_tab = 'grants' hours = 24 if not settings.DEBUG else 1000 if request.user.is_authenticated: threads_last_24_hours = lazy_round_number( request.user.profile.subscribed_threads.filter( created_on__gt=timezone.now() - timezone.timedelta(hours=hours)).count()) threads = { 'title': f"My Threads", 'slug': f'my_threads', 'helper_text': f'The threads that you\'ve liked, commented on, or sent a tip upon on Gitcoin in the last 24 hours.', 'badge': threads_last_24_hours } tabs = [threads] + tabs threads = { 'title': f"My Feed", 'slug': f'my_feed', 'helper_text': f'The threads that you\'ve posted, liked, commented on, or sent a tip upon on Gitcoin.', } tabs = [threads] + tabs connect_last_24_hours = lazy_round_number( Activity.objects.filter( activity_type__in=['status_update', 'wall_post'], created_on__gt=timezone.now() - timezone.timedelta(hours=hours)).count()) if connect_last_24_hours: default_tab = 'connect' connect = { 'title': f"Connect", 'slug': f'connect', 'helper_text': f'The announcements, requests for help, kudos jobs, mentorship, or other connective requests on Gitcoin in the last 24 hours.', 'badge': connect_last_24_hours } tabs = [connect] + tabs kudos_last_24_hours = lazy_round_number( Activity.objects.filter( activity_type__in=['new_kudos', 'receive_kudos'], created_on__gt=timezone.now() - timezone.timedelta(hours=hours)).count()) if kudos_last_24_hours: connect = { 'title': f"Kudos", 'slug': f'kudos', 'helper_text': f'The {kudos_last_24_hours} Kudos that have been sent by Gitcoin community members, to show appreciation for one aother.', 'badge': kudos_last_24_hours } tabs = tabs + [connect] if request.user.is_authenticated: hackathons = HackathonEvent.objects.filter( start_date__lt=timezone.now(), end_date__gt=timezone.now()) if hackathons.count(): user_registered_hackathon = request.user.profile.hackathon_registration.filter( registrant=request.user.profile, hackathon__in=hackathons).first() if user_registered_hackathon: default_tab = f'hackathon:{user_registered_hackathon.hackathon.pk}' connect = { 'title': user_registered_hackathon.hackathon.name, 'slug': default_tab, 'helper_text': f'Activity from the {user_registered_hackathon.hackathon.name} Hackathon.', } tabs = [connect] + tabs # set tab if request.COOKIES.get('tab'): all_tabs = [tab.get('slug') for tab in tabs] if request.COOKIES.get('tab') in all_tabs: default_tab = request.COOKIES.get('tab') tab = request.GET.get('tab', default_tab) is_search = "activity:" in tab or "search-" in tab if is_search: tabs.append({ 'title': "Search", 'slug': tab, }) search = '' if "search-" in tab: search = tab.split('-')[1] # get offers offer_pks = [] offers_by_category = {} available_offers = Offer.objects.current() if request.user.is_authenticated: available_offers = available_offers.exclude( actions__profile=request.user.profile, actions__what__in=['click', 'decline', 'go']) for key in ['top', 'secret', 'random', 'daily', 'weekly', 'monthly']: next_time_available = get_next_time_available(key) offers = available_offers.filter(key=key).order_by('-pk') offer = offers.first() for offer in offers: offer_pks.append(offer.pk) offers_by_category[key] = { 'offer': offer, 'offers': offers, 'time': next_time_available, } increment_offer_view_counts.delay(offer_pks) # subscriber info is_subscribed = False if request.user.is_authenticated: email_subscriber = request.user.profile.email_subscriptions.first() if email_subscriber: is_subscribed = email_subscriber.should_send_email_type_to( 'new_bounty_notifications') # announcements announcements = Announcement.objects.current().filter(key='townsquare') # title title = 'Home' desc = 'View the recent activity on the Gitcoin network' page_seo_text_insert = '' avatar_url = '' admin_link = '' if "activity:" in tab: try: pk = int(tab.split(':')[1]) activity = Activity.objects.get(pk=pk) title = f"@{activity.profile.handle}'s post on Gitcoin " desc = f"{activity.text}" comments_count = activity.comments.count() admin_link = activity.admin_url if comments_count: title += f"(+ {comments_count} comments)" avatar_url = activity.profile.avatar_url page_seo_text_insert = desc except Exception as e: print(e) # matching leaderboard current_match_round = MatchRound.objects.current().first() num_to_show = 10 current_match_rankings = MatchRanking.objects.filter( round=current_match_round, number__lt=(num_to_show + 1)) matching_leaderboard = [{ 'i': obj.number, 'following': request.user.profile == obj.profile or request.user.profile.follower.filter(org=obj.profile) if request.user.is_authenticated else False, 'handle': obj.profile.handle, 'contributions': obj.contributions, 'default_match_estimate': obj.default_match_estimate, 'match_curve': obj.sorted_match_curve, 'contributors': obj.contributors, 'amount': f"{int(obj.contributions_total/1000)}k" if obj.contributions_total > 1000 else round(obj.contributions_total, 2), 'match_amount': obj.match_total, 'you': obj.profile.pk == request.user.profile.pk if request.user.is_authenticated else False, } for obj in current_match_rankings[0:num_to_show]] following_tribes = [] if request.user.is_authenticated: tribe_relations = request.user.profile.tribe_members for tribe_relation in tribe_relations: followed_profile = tribe_relation.org if followed_profile.is_org: last_24_hours_activity = lazy_round_number( Activity.objects.filter( hidden=False, created_on__gt=timezone.now() - timezone.timedelta( hours=24)).related_to(followed_profile).count()) tribe = { 'title': followed_profile.handle, 'slug': followed_profile.handle, 'helper_text': f'Activities from {followed_profile.handle} in the last 24 hours', 'badge': last_24_hours_activity, 'avatar_url': followed_profile.avatar_url } following_tribes = [tribe] + following_tribes # render page context trending_only = int(request.GET.get('trending', 0)) context = { 'title': title, 'card_desc': desc, 'avatar_url': avatar_url, 'use_pic_card': True, 'page_seo_text_insert': page_seo_text_insert, 'nav': 'home', 'target': f'/activity?what={tab}&trending_only={trending_only}', 'tab': tab, 'tabs': tabs, 'REFER_LINK': f'https://gitcoin.co/townsquare/?cb=ref:{request.user.profile.ref_code}' if request.user.is_authenticated else None, 'matching_leaderboard': matching_leaderboard, 'current_match_round': current_match_round, 'admin_link': admin_link, 'now': timezone.now(), 'is_townsquare': True, 'trending_only': bool(trending_only), 'search': search, 'tags': [ ('#announce', 'bullhorn'), ('#mentor', 'terminal'), ('#jobs', 'code'), ('#help', 'laptop-code'), ('#other', 'briefcase'), ], 'announcements': announcements, 'is_subscribed': is_subscribed, 'offers_by_category': offers_by_category, 'following_tribes': following_tribes } response = TemplateResponse(request, 'townsquare/index.html', context) if request.GET.get('tab'): if ":" not in request.GET.get('tab'): response.set_cookie('tab', request.GET.get('tab')) return response