def about(request): return Http404()
def dispatch(self, *args, **kwargs): if not settings.FEATURE_FLAGS['NEW_ACCOUNT_JOURNEY_ON']: raise Http404() return super().dispatch(*args, **kwargs)
def get_object(self, queryset=None): comment = super(CommentRevisionAjax, self).get_object(queryset) if comment.hidden and not self.request.user.has_perm( 'judge.change_comment'): raise Http404() return comment
def quiz_page(request, pk, section_pk, quiz_pk): """ Renders quiz page and handles submission requests """ # get objects course = get_object_or_404(Course, pk=pk) section = get_object_or_404(Section, pk=section_pk) quiz = get_object_or_404(Quiz, pk=quiz_pk) # set session variable to indicate that the user has # not completed the quiz request.session["quiz_complete"] = False if quiz.published: # check if the quiz has a related video and if it has been published if quiz.video: if not quiz.video.published: raise Http404( "The video this quiz is related to is not published.") else: pass # check if quiz has a requirement and if it should be enabled (quiz_enabled, temp) = quiz_enable_check(request.user, quiz) if quiz_enabled: if request.method == "POST": quiz_submission(request, quiz, course, section) # if flag: return HttpResponseRedirect( reverse("quiz_result", args=[pk, section.pk, quiz.pk])) else: # get latest user attempt number (if it exists) try: latest_attempt_number = (QuestionAttempt.objects.filter( quiz=quiz, student=request.user).latest( "attempt_number").attempt_number) except QuestionAttempt.DoesNotExist: latest_attempt_number = 0 # check if user reached the maximum number of attempts # check if user has reached the limit of attempts if latest_attempt_number < quiz.attempts_max_number: attempts_limit_reached = False else: attempts_limit_reached = True # if the max number of attempts has been reached, redirect back to quiz list if attempts_limit_reached: messages.error( request, _("You have already reached the maximum number of attempts." ), ) return HttpResponseRedirect( reverse("section", args=[pk, section.pk])) else: return render( request, "quiz.html", { "course": course, "section": section, "quiz": quiz }, ) else: messages.error( request, _("Access denied."), ) return HttpResponseRedirect( reverse("section", args=[pk, section.pk])) else: raise Http404("This quiz is not published.")
def edit_event_winners(request, event_id): # Get the event, teams, and winner event = get_object_or_404(Event, pk=event_id) teams = Team.objects.filter(event_id=event_id).exclude(is_disqualified=True) winners = teams.filter(is_winner=True).values('id') # If there is no winning team if not winners: return redirect('edit_event', event_id) # POST request if request.method == "POST": # Check the form data form = EventWinnerForm(data=request.POST, files=request.FILES) # POST data valid if form.is_valid(): team_id = form.cleaned_data["team_id"] photo = form.cleaned_data["photo"] # If the team does not exist if team_id not in list(teams.values_list('id', flat=True)): raise Http404() # Set the previous winning team back to non-winners old_winner = teams.get(is_winner=True) old_winner.is_winner = False old_winner.save() # Declare the selected new winning team as winners new_winner = teams.get(pk=team_id) new_winner.is_winner = True new_winner.save() # Save the new photo event.winner_photo = photo event.save() return render(request, 'webapp/admin/event_winners.html', {'new_entry': True, 'is_valid': True, 'edit': True, 'event': event}) # POST data invalid else: return render(request, 'webapp/admin/event_winners.html', {'new_entry': True, 'is_valid': False}) # GET request else: # Construct teams team_composition = [] for team in teams: # Get team composition team_members = UserTeam.objects.filter(team_id=team.pk) users = User.objects.filter(pk__in=team_members.values_list('user_id')).order_by('last_name') data = dict(team=team, members=users) team_composition.append(data) photo = event.winner_photo return render(request, 'webapp/admin/event_winners.html', {'edit': True, 'team_composition': team_composition, 'photo': photo, 'winners': winners})
def download_pve(request, pk): if request.user.type_user != "B": if not Project.objects.filter( id=pk, permitted__username__contains=request.user.username).exists(): raise Http404("404") project = get_object_or_404(Project, id=pk) versie = project.pve_versie basic_PVE = (models.PVEItem.objects.select_related( "hoofdstuk").select_related("paragraaf").filter( projects__id__contains=pk).order_by("id")) # make pdf parameters = [] parameters += (f"Project: {project.naam}", ) date = datetime.datetime.now() fileExt = "%s%s%s%s%s%s" % ( date.strftime("%H"), date.strftime("%M"), date.strftime("%S"), date.strftime("%d"), date.strftime("%m"), date.strftime("%Y"), ) filename = f"PvE-{fileExt}" zipFilename = f"PvE_Compleet-{fileExt}" # Opmerkingen in kleur naast de regels opmerkingen = {} bijlagen = {} reacties = {} reactiebijlagen = {} kostenverschil = 0 comments = (PVEItemAnnotation.objects.select_related( "item").select_related("status").select_related("gebruiker").filter( project=project)) for opmerking in comments: opmerkingen[opmerking.item.id] = opmerking if opmerking.kostenConsequenties: kostenverschil += opmerking.kostenConsequenties if opmerking.bijlage: bijlage = BijlageToAnnotation.objects.get(ann=opmerking) bijlagen[opmerking.item.id] = bijlage replies = (CommentReply.objects.select_related("gebruiker").select_related( "onComment").select_related("onComment__item").filter( commentphase__project=project)) for reply in replies: if reply.onComment.item.id in reacties.keys(): reacties[reply.onComment.item.id].append(reply) else: reacties[reply.onComment.item.id] = [reply] if reply.bijlage: bijlage = BijlageToReply.objects.get(reply=reply) reactiebijlagen[reply.id] = bijlage geaccepteerde_regels_ids = [] if project.frozenLevel > 0: commentphase = FrozenComments.objects.filter( project=project, level=project.frozenLevel).first() geaccepteerde_regels_ids = [ accepted_id.id for accepted_id in commentphase.accepted_comments.all() ] pdfmaker = writePdf.PDFMaker(versie.versie) # verander CONCEPT naar DEFINITIEF als het project volbevroren is. if project.fullyFrozen: pdfmaker.Topright = "DEFINITIEF" else: pdfmaker.Topright = f"CONCEPT SNAPSHOT {date.strftime('%d')}-{date.strftime('%m')}-{date.strftime('%Y')}" pdfmaker.TopRightPadding = 75 pdfmaker.kostenverschil = kostenverschil pdfmaker.makepdf( filename, basic_PVE, versie.id, opmerkingen, bijlagen, reacties, reactiebijlagen, parameters, geaccepteerde_regels_ids, ) # get bijlagen bijlagen_models = models.ItemBijlages.objects.all() bijlagen = [] for bijlage_model in bijlagen_models: for item in bijlage_model.items.all(): if item in basic_PVE: bijlagen.append(bijlage_model) bijlagen = list(set(bijlagen)) if BijlageToAnnotation.objects.filter(ann__project=project).exists(): bijlagen_ann = BijlageToAnnotation.objects.filter(ann__project=project) for item in bijlagen_ann: bijlagen.append(item) if BijlageToReply.objects.filter( reply__onComment__project=project).exists(): replybijlagen = BijlageToReply.objects.filter( reply__onComment__project=project) for bijlage in replybijlagen: bijlagen.append(bijlage) if bijlagen: zipmaker = createBijlageZip.ZipMaker() zipmaker.makeZip(zipFilename, filename, bijlagen) else: zipFilename = False # and render the result page context = {} context["itemsPVE"] = basic_PVE context["filename"] = filename context["zipFilename"] = zipFilename context["project"] = project return render(request, "PVEResult_syn.html", context)
provider_class = AUTH_PROVIDERS[provider].consumer try: request_url = provider_class.prepare_authentication_request( request, reverse('auth_provider_done', kwargs={'provider': provider})) return HttpResponseRedirect(request_url) except NotImplementedError, e: return process_provider_signin(request, provider) except InvalidAuthentication, e: request.session['auth_error'] = e.message return HttpResponseRedirect(reverse('auth_signin')) else: raise Http404() def process_provider_signin(request, provider): if provider in AUTH_PROVIDERS: provider_class = AUTH_PROVIDERS[provider].consumer try: assoc_key = provider_class.process_authentication_request(request) except InvalidAuthentication, e: request.session['auth_error'] = e.message return HttpResponseRedirect(reverse('auth_signin')) if request.user.is_authenticated(): if isinstance(assoc_key, (type, User)): if request.user != assoc_key:
def dispatch(self, request, *args, **kwargs): if not settings.DMOJ_USER_DATA_DOWNLOAD or self.request.profile.mute: raise Http404() return super().dispatch(request, *args, **kwargs)
def edit_profile(request): if request.profile.mute: raise Http404() if request.method == 'POST': form = ProfileForm(request.POST, instance=request.profile, user=request.user) if form.is_valid(): with transaction.atomic(), revisions.create_revision(): form.save() revisions.set_user(request.user) revisions.set_comment(_('Updated on site')) if newsletter_id is not None: try: subscription = Subscription.objects.get( user=request.user, newsletter_id=newsletter_id) except Subscription.DoesNotExist: if form.cleaned_data['newsletter']: Subscription(user=request.user, newsletter_id=newsletter_id, subscribed=True).save() else: if subscription.subscribed != form.cleaned_data[ 'newsletter']: subscription.update( ('unsubscribe', 'subscribe')[form.cleaned_data['newsletter']]) request.profile.preferred_icon = request.POST.get('icon') request.profile.preferred_theme = request.POST.get('theme') request.profile.preferred_font = request.POST.get('font') request.profile.user_color = request.POST.get('color') request.profile.save() perm = Permission.objects.get( codename='test_site', content_type=ContentType.objects.get_for_model(Profile)) if form.cleaned_data['test_site']: request.user.user_permissions.add(perm) else: request.user.user_permissions.remove(perm) return HttpResponseRedirect(request.path) else: form = ProfileForm(instance=request.profile, user=request.user) if newsletter_id is not None: try: subscription = Subscription.objects.get( user=request.user, newsletter_id=newsletter_id) except Subscription.DoesNotExist: form.fields['newsletter'].initial = False else: form.fields['newsletter'].initial = subscription.subscribed form.fields['test_site'].initial = request.user.has_perm( 'judge.test_site') tzmap = settings.TIMEZONE_MAP return render( request, 'user/edit-profile.html', { 'require_staff_2fa': settings.DMOJ_REQUIRE_STAFF_2FA, 'form': form, 'title': _('Edit profile'), 'profile': request.profile, 'can_download_data': bool(settings.DMOJ_USER_DATA_DOWNLOAD), 'has_math_config': bool(settings.MATHOID_URL), 'TIMEZONE_MAP': tzmap or 'http://momentjs.com/static/img/world.png', 'TIMEZONE_BG': settings.TIMEZONE_BG if tzmap else '#4E7CAD', 'stickers': request.profile.achievements.filter( category=1).order_by('name').distinct(), 'icons': request.profile.achievements.filter( category=2).order_by('name').distinct(), 'colors': request.profile.achievements.filter( category=3).order_by('name').distinct(), 'themes': request.profile.achievements.filter( category=4).order_by('name').distinct(), 'fonts': request.profile.achievements.filter( category=5).order_by('name').distinct(), })
def daily_digest(request, user_slug): user = get_object_or_404(User, slug=user_slug) end_date = datetime.utcnow() start_date = end_date - timedelta(days=1) if end_date.weekday() == 1: # we don't have daily on sundays and mondays, we need to include all these posts at tuesday start_date = end_date - timedelta(days=3) if settings.DEBUG: start_date = end_date - timedelta(days=1000) created_at_condition = dict(created_at__gte=start_date, created_at__lte=end_date) published_at_condition = dict(published_at__gte=start_date, published_at__lte=end_date) # Moon moon_phase = parse_horoscope() # New actions subscription_comments = Comment.visible_objects()\ .filter( post__subscriptions__user=user, **created_at_condition )\ .values("post__type", "post__slug", "post__title", "post__author_id")\ .annotate(count=Count("id"))\ .order_by() replies = Comment.visible_objects()\ .filter( reply_to__author=user, **created_at_condition )\ .values("post__type", "post__slug", "post__title")\ .annotate(count=Count("reply_to_id"))\ .order_by() new_events = [ { "type": "my_post_comment", "post_url": reverse("show_post", kwargs={"post_type": e["post__type"], "post_slug": e["post__slug"]}), "post_title": e["post__title"], "count": e["count"], } for e in subscription_comments if e["post__author_id"] == user.id ] + [ { "type": "subscribed_post_comment", "post_url": reverse("show_post", kwargs={"post_type": e["post__type"], "post_slug": e["post__slug"]}), "post_title": e["post__title"], "count": e["count"], } for e in subscription_comments if e["post__author_id"] != user.id ] + [ { "type": "reply", "post_url": reverse("show_post", kwargs={"post_type": e["post__type"], "post_slug": e["post__slug"]}), "post_title": e["post__title"], "count": e["count"], } for e in replies ] upvotes = PostVote.objects.filter(post__author=user, **created_at_condition).count() \ + CommentVote.objects.filter(comment__author=user, **created_at_condition).count() if upvotes: new_events = [ { "type": "upvotes", "count": upvotes, } ] + new_events # Mentions mentions = Comment.visible_objects() \ .filter(**created_at_condition) \ .filter(text__regex=fr"@\y{user.slug}\y", is_deleted=False)\ .exclude(reply_to__author=user)\ .order_by("-upvotes")[:5] # Best posts posts = Post.visible_objects()\ .filter(is_approved_by_moderator=True, **published_at_condition)\ .exclude(type__in=[Post.TYPE_INTRO, Post.TYPE_WEEKLY_DIGEST])\ .exclude(is_shadow_banned=True)\ .order_by("-upvotes")[:100] # New joiners intros = Post.visible_objects()\ .filter(type=Post.TYPE_INTRO, **published_at_condition)\ .order_by("-upvotes") if not posts and not mentions and not intros: raise Http404() return render(request, "emails/daily.html", { "user": user, "events": new_events, "intros": intros, "posts": posts, "mentions": mentions, "date": end_date, "moon_phase": moon_phase, })
def dispatch(self, request, *args, **kwargs): raise Http404()
def weekly_digest(request): end_date = datetime.utcnow() start_date = end_date - timedelta(days=8) # make 8, not 7, to include marginal users if settings.DEBUG: start_date = end_date - timedelta(days=1000) created_at_condition = dict(created_at__gte=start_date, created_at__lte=end_date) published_at_condition = dict(published_at__gte=start_date, published_at__lte=end_date) # New users intros = Post.visible_objects()\ .filter(type=Post.TYPE_INTRO, **published_at_condition)\ .order_by("-upvotes") newbie_count = User.objects\ .filter( moderation_status=User.MODERATION_STATUS_APPROVED, **created_at_condition )\ .count() # Best posts featured_post = Post.visible_objects()\ .exclude(type=Post.TYPE_INTRO)\ .filter( label__isnull=False, label__code="top_week", **published_at_condition )\ .order_by("-upvotes")\ .first() posts = Post.visible_objects()\ .filter(is_approved_by_moderator=True, **published_at_condition)\ .exclude(type__in=[Post.TYPE_INTRO, Post.TYPE_WEEKLY_DIGEST])\ .exclude(id=featured_post.id if featured_post else None)\ .exclude(label__isnull=False, label__code="ad")\ .exclude(is_shadow_banned=True)\ .order_by("-upvotes") post_count = posts.count() posts = posts[:12] # Video of the week top_video_comment = Comment.visible_objects() \ .filter(**created_at_condition) \ .filter(is_deleted=False)\ .filter(upvotes__gte=3)\ .filter(Q(text__contains="https://youtu.be/") | Q(text__contains="youtube.com/watch"))\ .order_by("-upvotes")\ .first() top_video_post = None if not top_video_comment: top_video_post = Post.visible_objects() \ .filter(type=Post.TYPE_LINK, upvotes__gte=3) \ .filter(**published_at_condition) \ .filter(Q(url__contains="https://youtu.be/") | Q(url__contains="youtube.com/watch")) \ .order_by("-upvotes") \ .first() # Best comments comments = Comment.visible_objects() \ .filter(**created_at_condition) \ .filter(is_deleted=False)\ .exclude(post__type=Post.TYPE_BATTLE)\ .exclude(id=top_video_comment.id if top_video_comment else None)\ .order_by("-upvotes")[:3] # Intro from author author_intro = GodSettings.objects.first().digest_intro if not author_intro and not posts and not comments: raise Http404() # New achievements achievements = UserAchievement.objects\ .filter(**created_at_condition)\ .select_related("user", "achievement")\ .order_by("achievement") # required for grouping # Exclude footer for archive is_footer_excluded = "no_footer" in request.GET return render(request, "emails/weekly.html", { "posts": posts, "comments": comments, "intros": intros, "achievements": achievements, "newbie_count": newbie_count, "post_count": post_count, "top_video_comment": top_video_comment, "top_video_post": top_video_post, "featured_post": featured_post, "author_intro": author_intro, "issue_number": (end_date - settings.LAUNCH_DATE).days // 7, "is_footer_excluded": is_footer_excluded })
def review_app_help_view(request): try: if settings.HEROKU_APP_NAME: return render(request, 'reviewapp-help.html') except AttributeError: raise Http404()
def get_object(self): try: order = Order.objects.get(user=self.request.user, ordered=False) return order except ObjectDoesNotExist: raise Http404("You do not have an active order")
def get_context_data(self, **kwargs): context = super(OrganizationMixinBase, self).get_context_data(**kwargs) organization = self.organization if not organization: # If we don't even have a broker/provider for a site. raise Http404( _("It seems a broker was not defined, or defined incorrectly.") ) context.update({'organization': organization}) # XXX These might be moved to a higher-level urls = { 'api_cart': reverse('saas_api_cart'), 'api_redeem': reverse('saas_api_redeem_coupon'), 'organization_create': reverse('saas_organization_create') } # URLs for both sides (subscriber and provider). urls.update({ 'profile_base': reverse('saas_profile'), 'organization': { 'api_base': reverse('saas_api_organization', args=(organization, )), 'api_card': reverse('saas_api_card', args=(organization, )), 'api_import': reverse('saas_api_import_transactions', args=(organization, )), 'api_profile_base': reverse('saas_api_profile'), 'api_subscriptions': reverse('saas_api_subscription_list', args=(organization, )), 'billing_base': reverse('saas_billing_base'), 'profile': reverse('saas_organization_profile', args=(organization, )), } }) # The following `attached_user` will trigger a db query # even when `request.user` is anonymous. if organization.attached_user(): try: urls['organization'].update({ 'password_change': reverse('password_change', args=(organization, )) }) except NoReverseMatch: # With django.contrib.auth we cannot trigger password_change # for a different user than the one associated to the request. # It is OK. We will just not resolve the link. pass else: urls['organization']['roles'] = OrderedDict() for role_descr in organization.get_role_descriptions(): urls['organization']['roles'].update({ role_descr.title: reverse('saas_role_detail', args=(organization, role_descr.slug)), }) if (organization.is_provider and is_authenticated(self.request) and organization.accessible_by(self.request.user)): provider = organization urls.update({ 'provider': { 'api_bank': reverse('saas_api_bank', args=(provider, )), 'api_coupons': reverse('saas_api_coupon_list', args=(provider, )), 'api_metrics_plans': reverse('saas_api_metrics_plans', args=(provider, )), 'api_plans': reverse('saas_api_plans', args=(provider, )), 'api_receivables': reverse('saas_api_receivables', args=(provider, )), 'api_revenue': reverse('saas_api_revenue', args=(self.organization, )), 'api_subscribers_active': reverse('saas_api_subscribed', args=(provider, )), 'api_subscribers_churned': reverse('saas_api_churned', args=(provider, )), 'coupons': reverse('saas_coupon_list', args=(provider, )), 'dashboard': reverse('saas_dashboard', args=(provider, )), 'metrics_coupons': reverse('saas_metrics_coupons', args=(provider, )), 'metrics_plans': reverse('saas_metrics_plans', args=(provider, )), 'plans': reverse('saas_plan_base', args=(provider, )), 'metrics_sales': reverse('saas_metrics_summary', args=(provider, )), 'profile': reverse('saas_provider_profile'), 'subscribers': reverse('saas_subscriber_list', args=(provider, )), 'transfers': reverse('saas_transfer_info', args=(provider, )), } }) # These might lead to 403 if provider is not broker. urls.update({ 'broker': { 'api_users_registered': reverse('saas_api_registered'), 'charges': reverse('saas_charges'), } }) urls['organization'].update({ 'role_description': reverse('saas_role_list', args=(provider, )), }) if is_authenticated(self.request): urls.update({ 'profiles': [{ 'location': reverse('saas_organization_profile', args=(account, )), 'printable_name': account.printable_name } for account in get_organization_model().objects.accessible_by( self.request.user)] }) self.update_context_urls(context, urls) self.update_context_urls( context, {'profile_redirect': reverse('accounts_profile')}) if not is_broker(organization): # A broker does not have subscriptions. self.update_context_urls( context, { 'organization': { 'billing': reverse('saas_billing_info', args=(organization, )), 'subscriptions': reverse('saas_subscription_list', args=(organization, )), } }) return context
def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question})
def pdf_index(request, course_id, book_index, chapter=None, page=None): """ Display a PDF textbook. course_id: course for which to display text. The course should have "pdf_textbooks" property defined. book index: zero-based index of which PDF textbook to display. chapter: (optional) one-based index into the chapter array of textbook PDFs to display. Defaults to first chapter. Specifying this assumes that there are separate PDFs for each chapter in a textbook. page: (optional) one-based page number to display within the PDF. Defaults to first page. """ course_key = CourseKey.from_string(course_id) course = get_course_with_access(request.user, 'load', course_key) staff_access = bool(has_access(request.user, 'staff', course)) book_index = int(book_index) if book_index < 0 or book_index >= len(course.pdf_textbooks): raise Http404(u"Invalid book index value: {0}".format(book_index)) textbook = course.pdf_textbooks[book_index] viewer_params = '&file=' current_url = '' if 'url' in textbook: textbook['url'] = remap_static_url(textbook['url'], course) viewer_params += textbook['url'] current_url = textbook['url'] # then remap all the chapter URLs as well, if they are provided. current_chapter = None if 'chapters' in textbook: for entry in textbook['chapters']: entry['url'] = remap_static_url(entry['url'], course) if chapter is not None and int(chapter) <= (len(textbook['chapters'])): current_chapter = textbook['chapters'][int(chapter) - 1] else: current_chapter = textbook['chapters'][0] viewer_params += current_chapter['url'] current_url = current_chapter['url'] viewer_params += '#zoom=page-fit&disableRange=true' if page is not None: viewer_params += '&page={}'.format(page) if request.GET.get('viewer', '') == 'true': template = 'pdf_viewer.html' else: template = 'static_pdfbook.html' return render_to_response( template, { 'book_index': book_index, 'course': course, 'textbook': textbook, 'chapter': chapter, 'page': page, 'viewer_params': viewer_params, 'current_chapter': current_chapter, 'staff_access': staff_access, 'current_url': current_url, }, )
def post_detalhes(request, post_id): try: post = Posts.objects.get(pk=post_id) except Posts.DoesNotExist: raise Http404('Post não encontrado') return render(request, 'app_blog/detalhes_post.html', {'post':post})