Beispiel #1
0
def homepage(request):
    if request.session.get('user_type', None):
        this_logger.debug('主页获取用户类型:' + request.session['user_type'])
        return HttpResponseRedirect('/manage/weeks_timetable')
    return HttpResponseRedirect('/browse/login')
Beispiel #2
0
def redirect_profile(page=''):
    url = reverse('profile')
    if page and page.startswith('#'):
        url = url + page
    return HttpResponseRedirect(url)
Beispiel #3
0
def solution_list(request, task_id, user_id=None):
    if (user_id and not request.user.is_trainer
            and not request.user.is_superuser):
        return access_denied(request)

    task = get_object_or_404(Task, pk=task_id)
    author = get_object_or_404(User, pk=user_id) if user_id else request.user
    solutions = task.solution_set.filter(author=author).order_by('-id')
    final_solution = task.final_solution(author)

    if task.publication_date >= datetime.now() and not request.user.is_trainer:
        raise Http404

    if request.method == "POST":
        if task.expired() and not request.user.is_trainer:
            return access_denied(request)

        solution = Solution(task=task, author=author)
        formset = SolutionFormSet(request.POST,
                                  request.FILES,
                                  instance=solution)
        if formset.is_valid():
            solution.save()
            formset.save()
            run_all_checker = bool(
                User.objects.filter(id=user_id,
                                    tutorial__tutors__pk=request.user.id)
                or request.user.is_trainer)
            solution.check_solution(run_all_checker)

            if solution.accepted:
                # Send submission confirmation email
                t = loader.get_template(
                    'solutions/submission_confirmation_email.html')
                c = {
                    'protocol': request.is_secure() and "https" or "http",
                    'domain': RequestSite(request).domain,
                    'site_name': settings.SITE_NAME,
                    'solution': solution,
                }
                if user_id:
                    # in case someone else uploaded the solution, add this to the email
                    c['uploader'] = request.user
                with tempfile.NamedTemporaryFile(mode='w+') as tmp:
                    tmp.write("Content-Type: text/plain; charset=utf-8\n")
                    tmp.write(
                        "Content-Transfer-Encoding: quoted-printable\n\n")
                    tmp.write(t.render(c))
                    tmp.seek(0)
                    [signed_mail, __, __, __,
                     __] = execute_arglist([
                         "openssl", "smime", "-sign", "-signer",
                         settings.CERTIFICATE, "-inkey", settings.PRIVATE_KEY,
                         "-in", tmp.name
                     ],
                                           ".",
                                           unsafe=True)
                connection = get_connection()
                message = ConfirmationMessage(_("%s submission confirmation") %
                                              settings.SITE_NAME,
                                              signed_mail,
                                              None, [solution.author.email],
                                              connection=connection)
                if solution.author.email:
                    message.send()

            if solution.accepted or get_settings().accept_all_solutions:
                solution.final = True
                solution.save()

            return HttpResponseRedirect(
                reverse('solution_detail', args=[solution.id]))
    else:
        formset = SolutionFormSet()

    attestations = Attestation.objects.filter(
        solution__task=task, author__tutored_tutorials=request.user.tutorial)
    attestationsPublished = attestations[0].published if attestations else False

    return render(
        request, "solutions/solution_list.html", {
            "formset": formset,
            "task": task,
            "solutions": solutions,
            "final_solution": final_solution,
            "attestationsPublished": attestationsPublished,
            "author": author,
            "invisible_attestor": get_settings().invisible_attestor
        })
Beispiel #4
0
def student_approve_leave(request, leave_id):
    leave = LeaveReportStudent.objects.get(id=leave_id)
    leave.leave_status = 1
    leave.save()
    return HttpResponseRedirect(reverse("student_leave_view"))
Beispiel #5
0
 def dispatch(self, request, *args, **kwargs):
     if self.account.date_confirmed_extra_charges is not None:
         return HttpResponseRedirect(reverse(MobileWorkerListView.urlname, args=[self.domain]))
     return super(ConfirmBillingAccountForExtraUsersView, self).dispatch(request, *args, **kwargs)
Beispiel #6
0
def export_personal_info_request(request):
    """
    Страница выгрузки данных
    """
    # кнопка вернуться
    if 'prev' in request.POST:
        return HttpResponseRedirect('../')

    elif 'apply' in request.POST:
        id_ans = request.POST.get('group')
        id_what = request.POST.get('what')
        if id_what == "0":  # Выгрузка перс. данных
            if id_ans == "0":
                return export_request(
                    request,
                    'all',
                    func_for_get_data_all=export_personal_info,
                    func_for_woorksheet=save_personal_info_to_woorksheet,
                    namefile='Перс. данные',
                    dop_name="Личная информация")
            else:
                name_commission = dict_commission[id_ans]
                commission = CustomGroup.objects.get(group=Group.objects.get(
                    name=name_commission))
                return export_request(
                    request,
                    commission,
                    func_for_get_data_all=export_personal_info,
                    func_for_woorksheet=save_personal_info_to_woorksheet,
                    namefile='Перс. данные',
                    dop_name="Личная информация")
        elif id_what == "1":  # Распределение экспертов по заявкам # TODO
            if id_ans == "0":
                return export_request(
                    request,
                    'all',
                    func_for_get_data_all=export_relation,
                    func_for_woorksheet=save_relation_s_to_woorksheet,
                    namefile='Распределение',
                    dop_name="Распределение экспертов")
            else:
                name_commission = dict_commission[id_ans]
                commission = CustomGroup.objects.get(group=Group.objects.get(
                    name=name_commission))
                return export_request(
                    request,
                    commission,
                    func_for_get_data_all=export_relation,
                    func_for_woorksheet=save_relation_s_to_woorksheet,
                    namefile='Распределение',
                    dop_name="Распределение экспертов")
        elif id_what == "2":  # Просто результаты по комиссиям
            if id_ans == "0":
                return export_request(
                    request,
                    'all',
                    func_for_get_data_all=export_all_scores,
                    func_for_woorksheet=save_scores_to_woorksheet,
                    namefile='Рейтинг',
                    dop_name="Рейтинг заявок")
            else:
                name_commission = dict_commission[id_ans]
                commission = CustomGroup.objects.get(group=Group.objects.get(
                    name=name_commission))
                return export_request(
                    request,
                    commission,
                    func_for_get_data_all=export_all_scores,
                    func_for_woorksheet=save_scores_to_woorksheet,
                    namefile='Рейтинг',
                    dop_name="Рейтинг заявок")
        elif id_what == "3":  # Подробные результаты
            if id_ans == "0":
                return export_request(
                    request,
                    'all',
                    func_for_get_data_all=export_detailed_all_scores,
                    func_for_woorksheet=save_detailed_scores_to_woorksheet,
                    namefile='Подробный рейтинг.',
                    dop_name="Подробный рейтинг")
            else:
                name_commission = dict_commission[id_ans]
                commission = CustomGroup.objects.get(group=Group.objects.get(
                    name=name_commission))
                return export_request(
                    request,
                    commission,
                    func_for_get_data_all=export_detailed_all_scores,
                    func_for_woorksheet=save_detailed_scores_to_woorksheet,
                    namefile='Подробный рейтинг.',
                    dop_name="Подробный рейтинг")
        elif id_what == "4":  # Итоговые результаты # TODO
            if id_ans == "0":
                return export_request(
                    request,
                    'all',
                    func_for_get_data_all=export_itog_all_scores,
                    func_for_woorksheet=save_itog_scores_to_woorksheet,
                    namefile='Итоговый рейтинг.',
                    dop_name="Итоговый рейтинг")
            else:
                name_commission = dict_commission[id_ans]
                commission = CustomGroup.objects.get(group=Group.objects.get(
                    name=name_commission))
                if commission.common_commission:
                    messages.success(
                        request,
                        "Нельзя скачать итоговый рейтинг общей комиссии")
                    return HttpResponseRedirect("/admin/export_users/")
                else:
                    return export_request(
                        request,
                        commission,
                        func_for_get_data_all=export_itog_all_scores,
                        func_for_woorksheet=save_itog_scores_to_woorksheet,
                        namefile='Итоговый рейтинг.',
                        dop_name="Итоговый рейтинг")

        elif id_what == "5":  # Выгрузка сводных таблиц
            if id_ans == "0":
                return export_request(
                    request,
                    'all',
                    func_for_get_data_all=export_svod,
                    func_for_woorksheet=save_svod_to_woorksheet,
                    namefile='Сводная таблица',
                    dop_name="Сводная таблица готовности работы экспертов",
                    all_in_one_wheet=True)
            else:
                name_commission = dict_commission[id_ans]
                commission = CustomGroup.objects.get(group=Group.objects.get(
                    name=name_commission))
                if commission.common_commission:
                    messages.success(
                        request,
                        "Нельзя скачать итоговый рейтинг общей комиссии")
                    return HttpResponseRedirect("/admin/export_users/")
                else:
                    return export_request(
                        request,
                        commission,
                        func_for_get_data_all=export_svod,
                        func_for_woorksheet=save_svod_to_woorksheet,
                        namefile='Сводная таблица',
                        dop_name="Сводная таблица готовности работы экспертов",
                        all_in_one_wheet=True)
    else:
        return render(request, 'admin/export_by_commission.html', {
            'title': u'Скачивание',
        })
Beispiel #7
0
def logout_view(request):
    """Log the user out."""
    logout(request)
    return HttpResponseRedirect(reverse('learning_logs:index'))
Beispiel #8
0
def cadastro(request):
    c_errors = ''
    if request.method == 'POST':
        form = form_credor(request.POST)
        form_user = form_credor_user(request.POST)
        if form.is_valid() and form_user.is_valid():
            cnpj_c = form.cleaned_data['cnpj'].replace('/', '').replace('-', '').replace('.', '')
            cpf = CPF(cnpj_c)
            if Cnpj().validate(cnpj_c) or cpf.isValid():
                email = form_user.cleaned_data['email']
                pwd = form_user.cleaned_data['password']
                pwd_check = form_user.cleaned_data['password_check']
                nome = form.cleaned_data['nome']
                snome = form.cleaned_data['sobrenome']
                new_user = form.save(commit=False)
                if pwd == pwd_check:
                    try:
                        user = User.objects.create_user(
                            username=email,
                            password=pwd,
                            first_name=nome,
                            last_name=snome
                        )
                        user.save()
                        new_user.email = user
                    except IntegrityError as e:
                        c_errors = 'email'
                        return render(request, 'posto/cadastro.html', {
                            'form': form,
                            'form_user': form_user,
                            'c_errors': c_errors
                        })
                    new_user.cnpj = cnpj_c
                    new_user.data_add = datetime.now()
                    new_user.ip_user = get_ip(request)
                    new_user.save()
                    logout(request)
                    user = authenticate(username=email, password=pwd)
                    if user is not None:
                        if user.is_active:
                            login(request, user)
                            return HttpResponseRedirect('/')
                    else:
                        return HttpResponseRedirect('/logon_fail')
                    return HttpResponseRedirect('/')
                else:
                    c_errors = 'password_not_match'
                    form = form_credor()
                    form_user = form_credor_user()
            else:
                c_errors = 'cnpj'
                form = form_credor()
                form_user = form_credor_user()
    else:
        form = form_credor()
        form_user = form_credor_user()
    return render(request,
                  'posto/cadastro.html',
                  {
                      'form': form,
                      'form_user': form_user,
                      'c_errors': c_errors
                  })
Beispiel #9
0
def form_add(request):
    """Page with form to add a script."""
    if request.method == 'POST':
        form = ScriptFormAdd(request.POST, request.FILES)
        if form.is_valid():
            scriptfile = request.FILES['file']

            # add script in database
            now = datetime.now()
            script = Script(approved=False,
                            popularity=0,
                            name=form.cleaned_data['name'],
                            version=form.cleaned_data['version'],
                            url='',
                            language=form.cleaned_data['language'],
                            license=form.cleaned_data['license'],
                            desc_en=form.cleaned_data['description'],
                            requirements=form.cleaned_data['requirements'],
                            min_weechat=form.cleaned_data['min_weechat'],
                            author=form.cleaned_data['author'],
                            mail=form.cleaned_data['mail'],
                            added=now,
                            updated=now)

            # write script in pending directory
            filename = files_path_join('scripts', 'pending1',
                                       script.name_with_extension())
            with open(filename, 'w') as _file:
                _file.write(get_script_content(scriptfile))

            # send e-mail
            try:
                subject = ('WeeChat: new script %s' %
                           script.name_with_extension())
                body = (
                    ''
                    'Script      : %s\n'
                    'Version     : %s\n'
                    'Language    : %s\n'
                    'License     : %s\n'
                    'Description : %s\n'
                    'Requirements: %s\n'
                    'Min WeeChat : %s\n'
                    'Author      : %s <%s>\n'
                    '\n'
                    'Comment:\n%s\n' %
                    (form.cleaned_data['name'], form.cleaned_data['version'],
                     form.cleaned_data['language'],
                     form.cleaned_data['license'],
                     form.cleaned_data['description'],
                     form.cleaned_data['requirements'],
                     form.cleaned_data['min_weechat'],
                     form.cleaned_data['author'], form.cleaned_data['mail'],
                     form.cleaned_data['comment']))
                sender = '%s <%s>' % (form.cleaned_data['author'],
                                      form.cleaned_data['mail'])
                email = EmailMessage(subject, body, sender,
                                     settings.SCRIPTS_MAILTO)
                email.attach_file(filename)
                email.send()
            except:  # noqa: E722
                return HttpResponseRedirect('/scripts/adderror/')

            # save script in database
            script.save()

            return HttpResponseRedirect('/scripts/addok/')
    else:
        form = ScriptFormAdd()
    return render(
        request,
        'scripts/add.html',
        {
            'form': form,
        },
    )
Beispiel #10
0
 def get(self,request):
     logout(request)
     return HttpResponseRedirect(reverse('index'))
Beispiel #11
0
 def form_valid(self, form):
     model_instance = form.save(commit=False)
     model_instance.user_id = self.request.user
     model_instance.save()
     return HttpResponseRedirect(reverse_lazy('my_all_stars'))
def view_engineer(request, eid):
    user = get_object_or_404(Dojo_User, pk=eid)
    if not (request.user.is_superuser
            or request.user.username == 'root'
            or request.user.username == user.username):
        return HttpResponseRedirect(reverse('engineer_metrics'))
    now = timezone.now()

    findings = Finding.objects.filter(reporter=user, verified=True)
    closed_findings = Finding.objects.filter(mitigated_by=user)
    open_findings = findings.exclude(mitigated__isnull=False)
    open_month = findings.filter(date__year=now.year, date__month=now.month)
    accepted_month = [finding for ra in Risk_Acceptance.objects.filter(
        created__range=[datetime(now.year,
                                 now.month, 1,
                                 tzinfo=timezone.get_current_timezone()),
                        datetime(now.year,
                                 now.month,
                                 monthrange(now.year,
                                            now.month)[1],
                                 tzinfo=timezone.get_current_timezone())],
        reporter=user)
                      for finding in ra.accepted_findings.all()]
    closed_month = []
    for f in closed_findings:
        if f.mitigated and f.mitigated.year == now.year and f.mitigated.month == now.month:
            closed_month.append(f)

    o_dict, open_count = count_findings(open_month)
    c_dict, closed_count = count_findings(closed_month)
    a_dict, accepted_count = count_findings(accepted_month)
    day_list = [now - relativedelta(weeks=1,
                                    weekday=x,
                                    hour=0,
                                    minute=0,
                                    second=0)
                for x in range(now.weekday())]
    day_list.append(now)

    q_objects = (Q(date=d) for d in day_list)
    closed_week = []
    open_week = findings.filter(reduce(operator.or_, q_objects))

    accepted_week = [finding for ra in Risk_Acceptance.objects.filter(
        reporter=user, created__range=[day_list[0], day_list[-1]])
                     for finding in ra.accepted_findings.all()]

    q_objects = (Q(mitigated=d) for d in day_list)
    # closed_week= findings.filter(reduce(operator.or_, q_objects))
    for f in closed_findings:
        if f.mitigated and f.mitigated >= day_list[0]:
            closed_week.append(f)

    o_week_dict, open_week_count = count_findings(open_week)
    c_week_dict, closed_week_count = count_findings(closed_week)
    a_week_dict, accepted_week_count = count_findings(accepted_week)

    stuff = []
    o_stuff = []
    a_stuff = []
    findings_this_period(findings, 1, stuff, o_stuff, a_stuff)
    # findings_this_period no longer fits the need for accepted findings
    # however will use its week finding output to use here
    for month in a_stuff:
        month_start = datetime.strptime(
            month[0].strip(), "%b %Y")
        month_end = datetime(month_start.year,
                             month_start.month,
                             monthrange(
                                 month_start.year,
                                 month_start.month)[1],
                             tzinfo=timezone.get_current_timezone())
        for finding in [finding for ra in Risk_Acceptance.objects.filter(
                created__range=[month_start, month_end], reporter=user)
                        for finding in ra.accepted_findings.all()]:
            if finding.severity == 'Critical':
                month[1] += 1
            if finding.severity == 'High':
                month[2] += 1
            if finding.severity == 'Medium':
                month[3] += 1
            if finding.severity == 'Low':
                month[4] += 1

        month[5] = sum(month[1:])
    week_stuff = []
    week_o_stuff = []
    week_a_stuff = []
    findings_this_period(findings, 0, week_stuff, week_o_stuff, week_a_stuff)

    # findings_this_period no longer fits the need for accepted findings
    # however will use its week finding output to use here
    for week in week_a_stuff:
        wk_range = week[0].split('-')
        week_start = datetime.strptime(
            wk_range[0].strip() + " " + str(now.year), "%b %d %Y")
        week_end = datetime.strptime(
            wk_range[1].strip() + " " + str(now.year), "%b %d %Y")

        for finding in [finding for ra in Risk_Acceptance.objects.filter(
                created__range=[week_start, week_end], reporter=user)
                        for finding in ra.accepted_findings.all()]:
            if finding.severity == 'Critical':
                week[1] += 1
            if finding.severity == 'High':
                week[2] += 1
            if finding.severity == 'Medium':
                week[3] += 1
            if finding.severity == 'Low':
                week[4] += 1

        week[5] = sum(week[1:])

    products = Product.objects.all()
    vulns = {}
    for product in products:
        f_count = 0
        engs = Engagement.objects.filter(product=product)
        for eng in engs:
            tests = Test.objects.filter(engagement=eng)
            for test in tests:
                f_count += findings.filter(test=test,
                                           mitigated__isnull=True,
                                           active=True).count()
        vulns[product.id] = f_count
    od = OrderedDict(sorted(vulns.items(), key=itemgetter(1)))
    items = od.items()
    items.reverse()
    top = items[: 10]
    update = []
    for t in top:
        product = t[0]
        z_count = 0
        o_count = 0
        t_count = 0
        h_count = 0
        engs = Engagement.objects.filter(
            product=Product.objects.get(id=product))
        for eng in engs:
            tests = Test.objects.filter(engagement=eng)
            for test in tests:
                z_count += findings.filter(
                    test=test,
                    mitigated__isnull=True,
                    severity='Critical'
                ).count()
                o_count += findings.filter(
                    test=test,
                    mitigated__isnull=True,
                    severity='High'
                ).count()
                t_count += findings.filter(
                    test=test,
                    mitigated__isnull=True,
                    severity='Medium'
                ).count()
                h_count += findings.filter(
                    test=test,
                    mitigated__isnull=True,
                    severity='Low'
                ).count()
        prod = Product.objects.get(id=product)
        all_findings_link = "<a href='%s'>%s</a>" % (
            reverse('view_product_findings', args=(prod.id,)), escape(prod.name))
        update.append([all_findings_link, z_count, o_count, t_count, h_count,
                       z_count + o_count + t_count + h_count])
    total_update = []
    for i in items:
        product = i[0]
        z_count = 0
        o_count = 0
        t_count = 0
        h_count = 0
        engs = Engagement.objects.filter(
            product=Product.objects.get(id=product))
        for eng in engs:
            tests = Test.objects.filter(engagement=eng)
            for test in tests:
                z_count += findings.filter(
                    test=test,
                    mitigated__isnull=True,
                    severity='Critical').count()
                o_count += findings.filter(
                    test=test,
                    mitigated__isnull=True,
                    severity='High').count()
                t_count += findings.filter(
                    test=test,
                    mitigated__isnull=True,
                    severity='Medium').count()
                h_count += findings.filter(
                    test=test,
                    mitigated__isnull=True,
                    severity='Low').count()
        prod = Product.objects.get(id=product)
        all_findings_link = "<a href='%s'>%s</a>" % (
            reverse('view_product_findings', args=(prod.id,)), escape(prod.name))
        total_update.append([all_findings_link, z_count, o_count, t_count,
                             h_count, z_count + o_count + t_count + h_count])

    neg_length = len(stuff)
    findz = findings.filter(mitigated__isnull=True, active=True,
                            test__engagement__risk_acceptance=None)
    findz = findz.filter(Q(severity="Critical") | Q(severity="High"))
    less_thirty = 0
    less_sixty = 0
    less_nine = 0
    more_nine = 0
    for finding in findz:
        elapsed = date.today() - finding.date
        if elapsed <= timedelta(days=30):
            less_thirty += 1
        elif elapsed <= timedelta(days=60):
            less_sixty += 1
        elif elapsed <= timedelta(days=90):
            less_nine += 1
        else:
            more_nine += 1

    # Data for the monthly charts
    chart_data = [['Date', 'S0', 'S1', 'S2', 'S3', 'Total']]
    for thing in o_stuff:
        chart_data.insert(1, thing)

    a_chart_data = [['Date', 'S0', 'S1', 'S2', 'S3', 'Total']]
    for thing in a_stuff:
        a_chart_data.insert(1, thing)

    # Data for the weekly charts
    week_chart_data = [['Date', 'S0', 'S1', 'S2', 'S3', 'Total']]
    for thing in week_o_stuff:
        week_chart_data.insert(1, thing)

    week_a_chart_data = [['Date', 'S0', 'S1', 'S2', 'S3', 'Total']]
    for thing in week_a_stuff:
        week_a_chart_data.insert(1, thing)

    details = []
    for find in open_findings:
        team = find.test.engagement.product.customer.name
        name = find.test.engagement.product.name
        severity = find.severity
        description = find.title
        life = date.today() - find.date
        life = life.days
        status = 'Active'
        if len(find.risk_acceptance_set.all()) > 0:
            status = 'Accepted'
        detail = [team, name, severity, description, life, status, find.reporter]
        details.append(detail)

    details = sorted(details, key=lambda x: x[2])

    add_breadcrumb(title="%s Metrics" % user.get_full_name(), top_level=False, request=request)

    return render(request, 'dojo/view_engineer.html', {
        'open_month': open_month,
        'a_month': accepted_month,
        'low_a_month': accepted_count["low"],
        'medium_a_month': accepted_count["med"],
        'high_a_month': accepted_count["high"],
        'critical_a_month': accepted_count["crit"],
        'closed_month': closed_month,
        'low_open_month': open_count["low"],
        'medium_open_month': open_count["med"],
        'high_open_month': open_count["high"],
        'critical_open_month': open_count["crit"],
        'low_c_month': closed_count["low"],
        'medium_c_month': closed_count["med"],
        'high_c_month': closed_count["high"],
        'critical_c_month': closed_count["crit"],
        'week_stuff': week_stuff,
        'week_a_stuff': week_a_stuff,
        'a_total': a_stuff,
        'total': stuff,
        'sub': neg_length,
        'update': update,
        'lt': less_thirty,
        'ls': less_sixty,
        'ln': less_nine,
        'mn': more_nine,
        'chart_data': chart_data,
        'a_chart_data': a_chart_data,
        'week_chart_data': week_chart_data,
        'week_a_chart_data': week_a_chart_data,
        'name': '%s Metrics' % user.get_full_name(),
        'metric': True,
        'total_update': total_update,
        'details': details,
        'open_week': open_week,
        'closed_week': closed_week,
        'accepted_week': accepted_week,
        'a_dict': a_dict,
        'o_dict': o_dict,
        'c_dict': c_dict,
        'o_week_dict': o_week_dict,
        'a_week_dict': a_week_dict,
        'c_week_dict': c_week_dict,
        'open_week_count': open_week_count,
        'accepted_week_count': accepted_week_count,
        'closed_week_count': closed_week_count,
        'user': request.user,
    })
Beispiel #13
0
def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('blog'))
Beispiel #14
0
def logout_view(request):
    logout(request)
    return HttpResponseRedirect('/browse/login')
Beispiel #15
0
def splash(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('/index')
    else:
        return render(request, "splash.html")
Beispiel #16
0
    def form_valid(self, form):
        """
        If the form is valid, save the associated model.
        """
        self.object = form.save(commit=False)
        self.object.owner = self.request.user
        # by default, if RESOURCE_PUBLISHING=True then document.is_published
        # must be set to False
        # RESOURCE_PUBLISHING works in similar way as ADMIN_MODERATE_UPLOADS,
        # but is applied to documents only. ADMIN_MODERATE_UPLOADS has wider
        # usage
        is_published = not (
            settings.RESOURCE_PUBLISHING or settings.ADMIN_MODERATE_UPLOADS)
        self.object.is_published = is_published
        self.object.save()
        form.save_many2many()
        self.object.set_permissions(form.cleaned_data['permissions'])

        abstract = None
        date = None
        regions = []
        keywords = []
        bbox = None

        out = {'success': False}

        if getattr(settings, 'EXIF_ENABLED', False):
            try:
                from geonode.documents.exif.utils import exif_extract_metadata_doc
                exif_metadata = exif_extract_metadata_doc(self.object)
                if exif_metadata:
                    date = exif_metadata.get('date', None)
                    keywords.extend(exif_metadata.get('keywords', []))
                    bbox = exif_metadata.get('bbox', None)
                    abstract = exif_metadata.get('abstract', None)
            except BaseException:
                logger.error("Exif extraction failed.")

        if abstract:
            self.object.abstract = abstract
            self.object.save()

        if date:
            self.object.date = date
            self.object.date_type = "Creation"
            self.object.save()

        if len(regions) > 0:
            self.object.regions.add(*regions)

        if len(keywords) > 0:
            self.object.keywords.add(*keywords)

        if bbox:
            bbox_x0, bbox_x1, bbox_y0, bbox_y1 = bbox
            Document.objects.filter(id=self.object.pk).update(
                bbox_x0=bbox_x0,
                bbox_x1=bbox_x1,
                bbox_y0=bbox_y0,
                bbox_y1=bbox_y1)

        if getattr(settings, 'SLACK_ENABLED', False):
            try:
                from geonode.contrib.slack.utils import build_slack_message_document, send_slack_message
                send_slack_message(
                    build_slack_message_document(
                        "document_new", self.object))
            except BaseException:
                logger.error("Could not send slack message for new document.")

        register_event(self.request, EventType.EVENT_UPLOAD, self.object)

        if self.request.GET.get('no__redirect', False):
            out['success'] = True
            out['url'] = reverse(
                'document_detail',
                args=(
                    self.object.id,
                ))
            if out['success']:
                status_code = 200
            else:
                status_code = 400
            return HttpResponse(
                json.dumps(out),
                content_type='application/json',
                status=status_code)
        else:
            return HttpResponseRedirect(
                reverse(
                    'document_metadata',
                    args=(
                        self.object.id,
                    )))
Beispiel #17
0
def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("index"))
Beispiel #18
0
def document_metadata(
        request,
        docid,
        template='documents/document_metadata.html',
        ajax=True):

    document = None
    try:
        document = _resolve_document(
            request,
            docid,
            'base.change_resourcebase_metadata',
            _PERMISSION_MSG_METADATA)

    except Http404:
        return HttpResponse(
            loader.render_to_string(
                '404.html', context={
                }, request=request), status=404)

    except PermissionDenied:
        return HttpResponse(
            loader.render_to_string(
                '401.html', context={
                    'error_message': _("You are not allowed to edit this document.")}, request=request), status=403)

    if document is None:
        return HttpResponse(
            'An unknown error has occured.',
            content_type="text/plain",
            status=401
        )

    else:
        poc = document.poc
        metadata_author = document.metadata_author
        topic_category = document.category

        if request.method == "POST":
            document_form = DocumentForm(
                request.POST,
                instance=document,
                prefix="resource")
            category_form = CategoryForm(request.POST, prefix="category_choice_field", initial=int(
                request.POST["category_choice_field"]) if "category_choice_field" in request.POST and
                request.POST["category_choice_field"] else None)
            tkeywords_form = TKeywordForm(request.POST)
        else:
            document_form = DocumentForm(instance=document, prefix="resource")
            category_form = CategoryForm(
                prefix="category_choice_field",
                initial=topic_category.id if topic_category else None)

            # Keywords from THESAURUS management
            doc_tkeywords = document.tkeywords.all()
            tkeywords_list = ''
            lang = 'en'  # TODO: use user's language
            if doc_tkeywords and len(doc_tkeywords) > 0:
                tkeywords_ids = doc_tkeywords.values_list('id', flat=True)
                if hasattr(settings, 'THESAURUS') and settings.THESAURUS:
                    el = settings.THESAURUS
                    thesaurus_name = el['name']
                    try:
                        t = Thesaurus.objects.get(identifier=thesaurus_name)
                        for tk in t.thesaurus.filter(pk__in=tkeywords_ids):
                            tkl = tk.keyword.filter(lang=lang)
                            if len(tkl) > 0:
                                tkl_ids = ",".join(
                                    map(str, tkl.values_list('id', flat=True)))
                                tkeywords_list += "," + \
                                    tkl_ids if len(
                                        tkeywords_list) > 0 else tkl_ids
                    except BaseException:
                        tb = traceback.format_exc()
                        logger.error(tb)

            tkeywords_form = TKeywordForm(instance=document)

        if request.method == "POST" and document_form.is_valid(
        ) and category_form.is_valid():
            new_poc = document_form.cleaned_data['poc']
            new_author = document_form.cleaned_data['metadata_author']
            new_keywords = document_form.cleaned_data['keywords']
            new_regions = document_form.cleaned_data['regions']

            new_category = None
            if category_form and 'category_choice_field' in category_form.cleaned_data and\
            category_form.cleaned_data['category_choice_field']:
                new_category = TopicCategory.objects.get(
                    id=int(category_form.cleaned_data['category_choice_field']))

            if new_poc is None:
                if poc is None:
                    poc_form = ProfileForm(
                        request.POST,
                        prefix="poc",
                        instance=poc)
                else:
                    poc_form = ProfileForm(request.POST, prefix="poc")
                if poc_form.is_valid():
                    if len(poc_form.cleaned_data['profile']) == 0:
                        # FIXME use form.add_error in django > 1.7
                        errors = poc_form._errors.setdefault(
                            'profile', ErrorList())
                        errors.append(
                            _('You must set a point of contact for this resource'))
                        poc = None
                if poc_form.has_changed and poc_form.is_valid():
                    new_poc = poc_form.save()

            if new_author is None:
                if metadata_author is None:
                    author_form = ProfileForm(request.POST, prefix="author",
                                              instance=metadata_author)
                else:
                    author_form = ProfileForm(request.POST, prefix="author")
                if author_form.is_valid():
                    if len(author_form.cleaned_data['profile']) == 0:
                        # FIXME use form.add_error in django > 1.7
                        errors = author_form._errors.setdefault(
                            'profile', ErrorList())
                        errors.append(
                            _('You must set an author for this resource'))
                        metadata_author = None
                if author_form.has_changed and author_form.is_valid():
                    new_author = author_form.save()

            document = document_form.instance
            if new_poc is not None and new_author is not None:
                document.poc = new_poc
                document.metadata_author = new_author
            document.keywords.clear()
            document.keywords.add(*new_keywords)
            document.regions.clear()
            document.regions.add(*new_regions)
            document.category = new_category
            document.save()
            document_form.save_many2many()

            register_event(request, EventType.EVENT_CHANGE_METADATA, document)
            if not ajax:
                return HttpResponseRedirect(
                    reverse(
                        'document_detail',
                        args=(
                            document.id,
                        )))

            message = document.id

            try:
                # Keywords from THESAURUS management
                # Rewritten to work with updated autocomplete
                if not tkeywords_form.is_valid():
                    return HttpResponse(json.dumps({'message': "Invalid thesaurus keywords"}, status_code=400))

                tkeywords_data = tkeywords_form.cleaned_data['tkeywords']

                thesaurus_setting = getattr(settings, 'THESAURUS', None)
                if thesaurus_setting:
                    tkeywords_data = tkeywords_data.filter(
                        thesaurus__identifier=thesaurus_setting['name']
                    )
                    document.tkeywords = tkeywords_data
            except BaseException:
                tb = traceback.format_exc()
                logger.error(tb)

            return HttpResponse(json.dumps({'message': message}))

        # - POST Request Ends here -

        # Request.GET
        if poc is not None:
            document_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

        if metadata_author is not None:
            document_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

        metadata_author_groups = []
        if request.user.is_superuser or request.user.is_staff:
            metadata_author_groups = GroupProfile.objects.all()
        else:
            try:
                all_metadata_author_groups = chain(
                    request.user.group_list_all(),
                    GroupProfile.objects.exclude(
                        access="private").exclude(access="public-invite"))
            except BaseException:
                all_metadata_author_groups = GroupProfile.objects.exclude(
                    access="private").exclude(access="public-invite")
            [metadata_author_groups.append(item) for item in all_metadata_author_groups
                if item not in metadata_author_groups]

        if settings.ADMIN_MODERATE_UPLOADS:
            if not request.user.is_superuser:
                document_form.fields['is_published'].widget.attrs.update(
                    {'disabled': 'true'})

                can_change_metadata = request.user.has_perm(
                    'change_resourcebase_metadata',
                    document.get_self_resource())
                try:
                    is_manager = request.user.groupmember_set.all().filter(role='manager').exists()
                except BaseException:
                    is_manager = False
                if not is_manager or not can_change_metadata:
                    document_form.fields['is_approved'].widget.attrs.update(
                        {'disabled': 'true'})

        register_event(request, EventType.EVENT_VIEW_METADATA, document)
        return render(request, template, context={
            "resource": document,
            "document": document,
            "document_form": document_form,
            "poc_form": poc_form,
            "author_form": author_form,
            "category_form": category_form,
            "tkeywords_form": tkeywords_form,
            "metadata_author_groups": metadata_author_groups,
            "TOPICCATEGORY_MANDATORY": getattr(settings, 'TOPICCATEGORY_MANDATORY', False),
            "GROUP_MANDATORY_RESOURCES": getattr(settings, 'GROUP_MANDATORY_RESOURCES', False),
        })
Beispiel #19
0
def delete_comment(request, comment_id):
    comment = Comment.objects.get(id=comment_id)
    comment.delete()
    return HttpResponseRedirect(reverse('users:disp_post'))
Beispiel #20
0
def verifying(request):
    """
    This function verification of the salary slips starting from the range of the dealing assistant to sr. dealing assistant to asst. registrar FA to
    asst. registrar aud to registrar/director

    @param
    request - trivial
officeOfRegistrar
    @variables
    a - object of the verifying method
    id - primary key of the payment scheme model
    """
    k = HoldsDesignation.objects.filter(working = request.user)

    for z in k:
        if request.method == "POST" :
            if(str(z.designation) == 'dealing assistant'):
                a = request.POST.getlist('box')
                for i in range(len(a)) :
                    if "verify" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.senior_verify = True
                        p.save()


                    if "delete" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.senior_verify = False
                        p.delete()

            if(str(z.designation) == 'sr dealing assitant'):
                a = request.POST.getlist('box')
                for i in range(len(a)) :
                    if "verify" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.ass_registrar_verify = True
                        p.save()


                    if "delete" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.senior_verify = False
                        p.save()


            if(str(z.designation) == 'asst. registrar fa'):
                a = request.POST.getlist('box')
                for i in range(len(a)) :
                    if "verify" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.ass_registrar_aud_verify = True
                        p.save()


                    if "delete" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.ass_registrar_verify = False
                        p.save()

            if(str(z.designation) == 'asst. registrar aud'):
                a = request.POST.getlist('box')
                for i in range(len(a)) :
                    if "verify" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.registrar_director_verify = True
                        p.save()


                    if "delete" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.ass_registrar_aud_verify = False
                        p.save()

            if(str(z.designation) == 'Registrar'):
                a = request.POST.getlist('box')
                for i in range(len(a)) :
                    if "verify" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.runpayroll = True
                        p.view = False
                        p.save()


                    if "delete" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.registrar_director_verify = False
                        p.view = True
                        p.save()

            if(str(z.designation) == 'director'):
                a = request.POST.getlist('box')
                for i in range(len(a)) :
                    if "verify" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.runpayroll = True
                        p.view = False
                        p.save()


                    if "delete" in request.POST :
                        p = Paymentscheme.objects.get(id = a[i])
                        p.registrar_director_verify = False
                        p.view = True
                        p.save()

    return HttpResponseRedirect("/finance/finance/")
Beispiel #21
0
def edit_student_save(request):
    if request.method != "POST":
        return HttpResponse("Method Not Allowed")
    else:

        student_id = request.session.get("student_id")
        if student_id == None:
            return HttpResponseRedirect("/manage_student")

        form = EditStudentForm(request.POST, request.FILES)
        if form.is_valid():
            first_name = form.cleaned_data["first_name"]
            last_name = form.cleaned_data["last_name"]
            username = form.cleaned_data["username"]
            email = form.cleaned_data["email"]
            address = form.cleaned_data["address"]
            session_year_id = form.cleaned_data["session_year_id"]
            course_id = form.cleaned_data["course"]
            sex = form.cleaned_data["sex"]

            if request.FILES.get('profile_pic', False):
                profile_pic = request.FILES['profile_pic']
                fs = FileSystemStorage()
                filename = fs.save(profile_pic.name, profile_pic)
                profile_pic_url = fs.url(filename)
            else:
                profile_pic_url = None

            try:
                user = CustomUser.objects.get(id=student_id)
                user.first_name = first_name
                user.last_name = last_name
                user.username = username
                user.email = email
                user.save()

                student = Student.objects.get(admin=student_id)
                student.address = address
                session_year = SessionYearModel.object.get(id=session_year_id)
                student.session_year_id = session_year
                student.gender = sex

                course = Course.objects.get(id=course_id)
                student.course_id = course
                if profile_pic_url != None:
                    student.profile_pic = profile_pic_url
                student.save()
                del request.session['student_id']
                messages.success(request, "Successfully Edited Student")
                return HttpResponseRedirect(
                    reverse("edit_student", kwargs={"student_id": student_id}))
            except:
                messages.error(request, "Failed to Edit Student")
                return HttpResponseRedirect(
                    reverse("edit_student", kwargs={"student_id": student_id}))
        else:
            form = EditStudentForm(request.POST)
            student = Student.objects.get(admin=student_id)
            return render(request, "hod_template/edit_student.html", {
                "form": form,
                "id": student_id,
                "username": student.admin.username
            })
Beispiel #22
0
def previous(request) :
    """
        This method is used to view the already executed payroll run the registrar, and this method will take the input of the month and year which generates
        the entire payments of the employee of particular month and year

        @param
        request - trivial

        @variables
        a,b - these are taken as inout variables of month and year respectively for the display of the corresponding month's payments
    """
    k = HoldsDesignation.objects.filter(working = request.user)
    
    for z in k:
        if request.method == "POST" :
            if(str(z.designation) == 'dealing assistant'):
                a = request.POST.get('selectmonth')
                b = request.POST.get('selectyear')
                print (a)

                c = Paymentscheme.objects.filter(month = a , year = b , runpayroll = True)
                context = {
                    'c': c,

                }
                return render(request, "financeAndAccountsModule/financeAndAccpyhtomountsModuleds.html", context)

            if(str(z.designation) == 'sr dealing assitant'):
                a = request.POST.get('selectmonth')
                b = request.POST.get('selectyear')
                print (a)

                c = Paymentscheme.objects.filter(month = a , year = b , runpayroll = True)
                context = {
                    'c': c
                }
                return render(request, "financeAndAccountsModule/financeAndAccountsModulesrda.html", context)

            if(str(z.designation) == 'asst. registrar fa'):
                a = request.POST.get('selectmonth')
                b = request.POST.get('selectyear')
                print (a)

                c = Paymentscheme.objects.filter(month = a , year = b , runpayroll = True)
                context = {
                    'c': c
                }
                return render(request, "financeAndAccountsModule/financeAndAccountsModulearfa.html", context)


            if(str(z.designation) == 'asst. registrar aud'):
                a = request.POST.get('selectmonth')
                b = request.POST.get('selectyear')
                print (a)

                c = Paymentscheme.objects.filter(month = a , year = b , runpayroll = True)
                context = {
                    'c': c
                }
                return render(request, "financeAndAccountsModule/finanaceAndAccountsModulearaud.html", context)


            if(str(z.designation) == 'Registrar'):
                a = request.POST.get('selectmonth')
                b = request.POST.get('selectyear')
                print (a)

                c = Paymentscheme.objects.filter(month = a , year = b , runpayroll = True)
                context = {
                    'c': c
                }
                return render(request, "financeAndAccountsModule/financeAndAccountsModule.html", context)

            if(str(z.designation) == 'director'):
                a = request.POST.get('selectmonth')
                b = request.POST.get('selectyear')
                print (a)

                c = Paymentscheme.objects.filter(month = a , year = b , runpayroll = True)
                context = {
                    'c': c
                }
                return render(request, "financeAndAccountsModule/financeAndAccountsModule.html", context)
    return HttpResponseRedirect("/finance/finance/")
Beispiel #23
0
def staff_disapprove_leave(request, leave_id):
    leave = LeaveReportStaff.objects.get(id=leave_id)
    leave.leave_status = 2
    leave.save()
    return HttpResponseRedirect(reverse("staff_leave_view"))
Beispiel #24
0
def previousReceipts(request) :
    """
        This method is used to view Receipts of already created payement transaction, and this method will take the input of the month and year which generates
        the entire payments of particular month and year, made by the concerned authorities.

        @param
        request - trivial

        @variables
        a,b - these are taken as inout variables of month and year respectively for the display of the corresponding month's payment recei.
    """
    k = HoldsDesignation.objects.filter(working = request.user)

    for z in k:
        if request.method == "POST" :
            if(str(z.designation) == 'asst. registrar fa'):
                a = request.POST.get('selectmonth')
                b = request.POST.get('selectyear')
                month_no = getMonth(a)

                c = Receipts.objects.filter(Date__month = month_no , Date__year = b)
                context = {
                    'x': c
                }
                return render(request, "financeAndAccountsModule/financeAndAccountsModulearfa.html", context)


            if(str(z.designation) == 'asst. registrar aud'):
                a = request.POST.get('selectmonth')
                b = request.POST.get('selectyear')
                month_no = getMonth(a)

                c = Receipts.objects.filter(Date__month = month_no , Date__year = b)
                context = {
                    'x': c
                }
                return render(request, "financeAndAccountsModule/finanaceAndAccountsModulearaud.html", context)


            if(str(z.designation) == 'Registrar'):
                a = request.POST.get('selectmonth')
                b = request.POST.get('selectyear')
                month_no = getMonth(a)

                c = Receipts.objects.filter(Date__month = month_no , Date__year = b)
                context = {
                    'x': c
                }
                return render(request, "financeAndAccountsModule/financeAndAccountsModule.html", context)

            if(str(z.designation) == 'director'):
                a = request.POST.get('selectmonth')
                b = request.POST.get('selectyear')
                month_no = getMonth(a)

                c = Receipts.objects.filter(Date__month = month_no , Date__year = b)
                context = {
                    'x': c
                }
                return render(request, "financeAndAccountsModule/financeAndAccountsModule.html", context)
    return HttpResponseRedirect("/finance/finance/")
Beispiel #25
0
    def post(self, request, *args, **kwargs):
        """View's dispatch method automatically calls this"""
        try:
            self.workbook = get_workbook(request.FILES.get('bulk_upload_file'))
        except WorkbookJSONError as e:
            messages.error(request, six.text_type(e))
            return self.get(request, *args, **kwargs)

        try:
            self.user_specs = self.workbook.get_worksheet(title='users')
        except WorksheetNotFound:
            try:
                self.user_specs = self.workbook.get_worksheet()
            except WorksheetNotFound:
                return HttpResponseBadRequest("Workbook has no worksheets")

        try:
            self.group_specs = self.workbook.get_worksheet(title='groups')
        except WorksheetNotFound:
            self.group_specs = []

        try:
            check_headers(self.user_specs)
        except UserUploadError as e:
            messages.error(request, _(six.text_type(e)))
            return HttpResponseRedirect(reverse(UploadCommCareUsers.urlname, args=[self.domain]))

        # convert to list here because iterator destroys the row once it has
        # been read the first time
        self.user_specs = list(self.user_specs)

        for user_spec in self.user_specs:
            try:
                user_spec['username'] = enforce_string_type(user_spec['username'])
            except StringTypeRequiredError:
                messages.error(
                    request,
                    _("Error: Expected username to be a Text type for username {0}")
                    .format(user_spec['username'])
                )
                return HttpResponseRedirect(reverse(UploadCommCareUsers.urlname, args=[self.domain]))

        try:
            check_existing_usernames(self.user_specs, self.domain)
        except UserUploadError as e:
            messages.error(request, _(six.text_type(e)))
            return HttpResponseRedirect(reverse(UploadCommCareUsers.urlname, args=[self.domain]))

        try:
            check_duplicate_usernames(self.user_specs)
        except UserUploadError as e:
            messages.error(request, _(six.text_type(e)))
            return HttpResponseRedirect(reverse(UploadCommCareUsers.urlname, args=[self.domain]))

        task_ref = expose_cached_download(payload=None, expiry=1*60*60, file_extension=None)
        task = bulk_upload_async.delay(
            self.domain,
            self.user_specs,
            list(self.group_specs),
        )
        task_ref.set_task(task)
        return HttpResponseRedirect(
            reverse(
                UserUploadStatusView.urlname,
                args=[self.domain, task_ref.download_id]
            )
        )
Beispiel #26
0
def profile_detail(request, username):
    return HttpResponseRedirect(reverse(
        'devmo.views.profile_view', args=(username,)))
Beispiel #27
0
def solution_run_checker(request, solution_id):
    solution = Solution.objects.get(pk=solution_id)
    check_solution(solution, True)
    return HttpResponseRedirect(
        reverse('solution_detail_full', args=[solution_id]))
Beispiel #28
0
def download(request, slug):
    """Demo download with action counting"""
    submission = get_object_or_404(Submission, slug=slug)
    return HttpResponseRedirect(submission.demo_package.url)
Beispiel #29
0
def logout_user(request):
    if request.user.is_authenticated:
        logout(request)
    return HttpResponseRedirect('/')
Beispiel #30
0
    def get(self, request, *args, **kwargs):
        """See if we have a direct match. If so redirect, if not, search.

        Try fetching a remote profile if the search term is a handle or fid.
        """
        q = safe_text(request.GET.get("q"))
        if q:
            q = q.strip().lower().strip("@")
        self.q = q
        # Check if direct tag matches
        if q.startswith('#'):
            try:
                tag = Tag.objects.filter(
                    name=q[1:]
                ).annotate(
                    content_count=Count('contents')
                ).filter(
                    content_count__gt=0
                ).get()
            except Tag.DoesNotExist:
                pass
            else:
                return redirect(tag.get_absolute_url())
        # Check if profile matches
        profile = None
        try:
            profile = Profile.objects.visible_for_user(request.user).fed(q).get()
        except Profile.DoesNotExist:
            # Try a remote search
            if is_url(q) or validate_handle(q):
                try:
                    remote_profile = retrieve_remote_profile(q)
                except (AttributeError, ValueError, xml.parsers.expat.ExpatError):
                    # Catch various errors parsing the remote profile
                    return super().get(request, *args, **kwargs)
                if remote_profile and isinstance(remote_profile, base.Profile):
                    profile = Profile.from_remote_profile(remote_profile)
        if profile:
            return redirect(reverse("users:profile-detail", kwargs={"uuid": profile.uuid}))
        # Check if content matches
        content = None
        try:
            content = Content.objects.visible_for_user(request.user).fed(q).get()
        except Content.DoesNotExist:
            # Try a remote search
            if is_url(q):
                try:
                    remote_content = retrieve_remote_content(q)
                except (AttributeError, ValueError):
                    # Catch various errors parsing the remote content
                    return super().get(request, *args, **kwargs)
                if remote_content:
                    process_entities([remote_content])
                    # Try again
                    try:
                        content = Content.objects.visible_for_user(request.user).fed(remote_content.id).get()
                    except Content.DoesNotExist:
                        return super().get(request, *args, **kwargs)
        if content:
            return redirect(reverse("content:view", kwargs={"pk": content.id}))
        try:
            return super().get(request, *args, **kwargs)
        except QueryError:
            # Re-render the form
            messages.warning(self.request, _("Search string is invalid, please try another one."))
            return HttpResponseRedirect(self.get_success_url())