我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用django.shortcuts.reverse()。
def event_signin(request, *args, **kwargs): if not request.user.is_anonymous(): logout(request) event = Event.objects.get(pk=kwargs.get('pk', None)) if request.method == "GET": return render(request, 'signin_sheets/participant_signin.html', {'form': ParticipantSigninForm, 'event': event}) elif request.method == "POST": form = ParticipantSigninForm(request.POST) if form.is_valid(): user = form.save() user.event = Event.objects.get(pk=kwargs.get('pk')) user.save() messages.success(request, "Your information has been saved.<br>Thanks for signing in!") return redirect(reverse('event-signin', kwargs={'pk': kwargs.get('pk')})) return redirect(reverse('event-list'))
def scan_scan_list(request: HttpRequest, scan_list_id: int) -> HttpResponse: """Schedule the scan of a scan list.""" scan_list = get_object_or_404( ScanList.objects.prefetch_related(Prefetch( 'sites', queryset=Site.objects.select_related('last_scan') \ .annotate_most_recent_scan_start() \ .annotate_most_recent_scan_end_or_null()) ), pk=scan_list_id) was_any_site_scannable = scan_list.scan() if was_any_site_scannable: num_scanning_sites = Scan.objects.filter(end__isnull=True).count() messages.success(request, _("Scans for this list have been scheduled. "+ \ "The total number of sites in the scanning queue "+ \ "is %i (including yours)." % num_scanning_sites)) else: messages.warning(request, _('All sites have been scanned recently. Please wait 30 minutes and try again.')) return redirect(reverse('frontend:view_scan_list', args=(scan_list_id,)))
def _create_user(request): username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') verified = request.POST.get('verified', 'false') == 'true' dummy = request.POST.get('dummy', 'false') == 'true' user = accounts.models.User( username=username, email=email, email_verified=verified) user.set_password(password) try: user.save() if dummy: user.groups = [accounts.models.Group.objects.get(name='Dummy')] except django.db.IntegrityError as exc: return django.http.JsonResponse({ 'error': str(exc)}, status=422) resp = django.http.JsonResponse( _encode_user(request, user), status=201) resp['Location'] = reverse('api:users-detail', kwargs={'username': user.username}) return resp
def post(self, request, *args, **kwargs): pk = self.kwargs.get(self.pk_url_kwarg) queryset = self.get_queryset().filter(pk=pk) try: object = queryset.get() except queryset.model.DoesNotExist: return redirect(request.META.get('HTTP_REFERER', reverse('management-user-list'))) object.is_active = not object.is_active object.save() for s in Session.objects.all(): data = s.get_decoded() if data.get('_auth_user_id', None) == str(object.id): s.delete() return redirect(request.META.get('HTTP_REFERER', reverse('management-user-list')))
def post(self, request, *args, **kwargs): post = self.get_object() if post.price > request.user.coin: return render(request, 'error.html', context={ 'errors': '??????????', 'return_url': reverse('archive:detail', kwargs=dict(pk=post.id)) }) request.user.coin -= post.price request.user.save() post.author.coin += post.price post.author.save() post.buyers.add(request.user) log_coin(-post.price, request.user.coin, None, request.user, '???%s?' % (post.title, )) log_coin(post.price, post.author.coin, None, post.author, '???%s?' % (post.title, )) return redirect('archive:detail', pk=post.id)
def homepage(request): """ Homepage view for when the URL does not specify a specific semester. Looks at session data to see the user's last visited semester. If no data is given, the homepage defaults to the semester given by DEFAULT_SEMESTER_PK """ if request.user.is_authenticated: return redirect(to=request.user.options.get_absolute_url()) elif request.session.get('homepage', ''): # If the student has visited a student page before, redirect return redirect(django_reverse( 'semesterpage-studyprogram', args=(request.session.get('homepage'),) )) else: semester_pk = request.session.get('semester_pk', DEFAULT_SEMESTER_PK) semester = Semester.objects.get(pk=semester_pk) return redirect(to=semester.get_absolute_url())
def problem_meta_description_instance(request, mid, did): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) description = get_object_or_404(Description.objects, id=int(did)) return render(request, 'problem/metaProblem/description/instance.html', { 'user': info, 'meta_problem': meta_problem, 'description': description })
def problem_meta_sample_instance(request, mid, sid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) sample = get_object_or_404(Sample.objects, id=int(sid)) return render(request, 'problem/metaProblem/sample/instance.html', { 'user': info, 'meta_problem': meta_problem, 'sample': sample })
def problem_meta_test_instance(request, mid, tid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) test_data = get_object_or_404(TestData.objects, id=int(tid)) return render(request, 'problem/metaProblem/testData/instance.html', { 'user': info, 'meta_problem': meta_problem, 'test': test_data, 'max_input': MAX_INPUT_SIZE })
def problem_meta_problem_instance(request, mid, pid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) return render(request, 'problem/metaProblem/problem/instance.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob })
def problem_meta_problem_limits_create(request, mid, pid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) return render(request, 'problem/metaProblem/problem/limit/create.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob })
def problem_meta_problem_limits_instance(request, mid, pid, lid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) limit = get_object_or_404(Limit.objects, id=int(lid)) return render(request, 'problem/metaProblem/problem/limit/instance.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob, 'limit': limit })
def problem_meta_problem_spj(request, mid, pid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) return render(request, 'problem/metaProblem/problem/specialJudge/list.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob })
def problem_meta_problem_spj_create(request, mid, pid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) return render(request, 'problem/metaProblem/problem/specialJudge/create.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob })
def problem_meta_problem_spj_instance(request, mid, pid, sid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) spj = get_object_or_404(SpecialJudge.objects, id=int(sid)) return render(request, 'problem/metaProblem/problem/specialJudge/instance.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob, 'spj': spj })
def problem_meta_problem_iw_create(request, mid, pid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) return render(request, 'problem/metaProblem/problem/invalidWord/create.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob })
def problem_meta_problem_iw_instance(request, mid, pid, iw_id): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) iw = get_object_or_404(InvalidWord.objects, id=int(iw_id)) return render(request, 'problem/metaProblem/problem/invalidWord/instance.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob, 'iw': iw })
def problem_meta_problem_test(request, mid, pid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) return render(request, 'problem/metaProblem/problem/testDataRelation/list.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob })
def problem_meta_problem_test_create(request, mid, pid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) return render(request, 'problem/metaProblem/problem/testDataRelation/create.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob })
def problem_meta_problem_test_instance(request, mid, pid, tid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_problem_admin(info): return redirect(reverse('homepage')) meta_problem = get_object_or_404(MetaProblem.objects, id=int(mid)) prob = get_object_or_404(Problem.objects, id=int(pid)) test = get_object_or_404(ProblemTestData.objects, id=int(tid)) return render(request, 'problem/metaProblem/problem/testDataRelation/instance.html', { 'user': info, 'meta_problem': meta_problem, 'problem': prob, 'test': test })
def problem_instance(request, pid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_category_admin(info): return redirect(reverse('homepage')) prob = get_object_or_404(Problem.objects, id=int(pid)) return render(request, 'problem/problem/instance.html', { 'user': info, 'pid': pid, 'problem': prob })
def client_category_instance(request, cid, rid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_client_admin(info): return redirect(reverse('homepage')) client = get_object_or_404(Client.objects, id=int(cid)) relation = get_object_or_404(ClientCategory.objects, id=int(rid)) return render(request, 'client/client/categoryRelation/instance.html', { 'user': info, 'client': client, 'relation': relation })
def user_instance(request, username): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_user_admin(info): return redirect(reverse('homepage')) groups = Group.objects.exclude(name=GROUP_NAME_CLIENT) u_info = get_object_or_404(User.objects.exclude(groups__name=GROUP_NAME_CLIENT), username=username) return render(request, 'user/instance.html', { 'user': info, 'groups': groups, 'u_info': u_info })
def submit_problem(request, pid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not has_problem_access(info): return redirect(reverse('homepage')) prob = get_object_or_404(Problem.objects.filter(available=True, deleted=False), id=int(pid)) environments = Environment.objects.filter(available=True, deleted=False).order_by('id') return render(request, 'problem/problem/submit.html', { 'user': info, 'problem': prob, 'envs': environments })
def judge_instance(request, jid): info = user_info(request) if not info['is_authenticated']: return redirect(reverse('login_page')) if not is_judge_admin(info): return redirect(reverse('homepage')) judge = get_object_or_404(Judge.objects.all(), id=int(jid)) return render(request, 'judge/judge/instance.html', { 'user': info, 'jid': jid, 'judge': judge })
def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.helper = FormHelper() # set form tag attributes self.helper.action = reverse('contact_admin') self.helper.form_method = 'POST' self.helper.form_class = 'form-horizontal contact-form' # set form field properties self.helper.help_text_inline = True self.helper.html5_required = False self.helper.attrs = {'novalidate': ''} self.helper.label_class = 'col-sm-2 control-label' self.helper.field_class = 'col-sm-10' # add buttons self.helper.add_input(Submit('send_button', _(u'Submit')))
def results_delete(request, rid): if request.method == "POST": if request.POST.get('cancel_button'): messages.warning(request, _(u"Deleting results of exam canceled")) else: exam = Exam.objects.get(pk=int(rid)) exam.is_completed = False results = Result.objects.filter(result_exam=exam) results.delete() exam.save() messages.success(request, _(u"Information about results of exam %s deleted successfully") % exam.name) return HttpResponseRedirect(reverse('results')) else: try: exam = Exam.objects.get(pk=int(rid)) except: messages.error(_(u'There was an error on the server. Please try again later')) return HttpResponseRedirect(reverse('results')) else: return render(request, 'students/results_confirm_delete.html', {'exam': exam})
def test_changed_group_notification_mail(self): tasks.send_support_group_changed_notification(self.group.pk, ["information", "contact"]) self.assertEqual(len(mail.outbox), 3) for message in mail.outbox: self.assertEqual(len(message.recipients()), 1) messages = {message.recipients()[0]: message for message in mail.outbox} self.assertCountEqual(messages.keys(), [self.creator.email, self.member1.email, self.member2.email]) for recipient, message in messages.items(): text = message.body.replace('\n', '') self.assert_(self.group.name in text, 'group name not in message') # self.assert_( # dj_reverse('quit_group', kwargs={'pk': self.group.pk}, urlconf='front.urls') in message.body, # 'quit group link not in message' # ) self.assert_('/groupes/details/{}'.format(self.group.pk), 'group link not in message') self.assert_(str(tasks.CHANGE_DESCRIPTION['information']) in text) self.assert_(str(tasks.CHANGE_DESCRIPTION['contact']) in text) self.assert_(str(tasks.CHANGE_DESCRIPTION['location']) not in text)
def test_can_add_delete_address(self): emails = list(self.person.emails.all()) # should be possible to get the delete page for one of the two addresses, and to actually delete res = self.client.get('/message_preferences/adresses/{}/supprimer/'.format(emails[1].pk)) self.assertEqual(res.status_code, status.HTTP_200_OK) res = self.client.post('/message_preferences/adresses/{}/supprimer/'.format(emails[1].pk)) self.assertRedirects(res, reverse('email_management')) # address should indeed be gone self.assertEqual(len(self.person.emails.all()), 1) self.assertEqual(self.person.emails.first(), emails[0]) # both get and post should give 403 when there is only one primary address res = self.client.get('/message_preferences/adresses/{}/supprimer/'.format(emails[0].pk)) self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN) res = self.client.post('/message_preferences/adresses/{}/supprimer/'.format(emails[0].pk)) self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)
def test_can_change_address(self, geocode_person): self.client.force_login(self.person.role) address_fields = { 'location_address1': '73 boulevard Arago', 'location_zip': '75013', 'location_country': 'FR', 'location_city': 'Paris', } response = self.client.post(reverse('change_profile'), address_fields) geocode_person.delay.assert_called_once() self.assertEqual(geocode_person.delay.call_args[0], (self.person.pk,)) geocode_person.reset_mock() response = self.client.post(reverse('change_profile'), { 'first_name': 'Arthur', 'last_name': 'Cheysson', **address_fields }) geocode_person.delay.assert_not_called()
def test_can_rsvp(self, rsvp_notification): url = reverse('view_event', kwargs={'pk': self.other_event.pk}) self.client.force_login(self.person.role) response = self.client.get(url) self.assertIn('Participer à cet événement', response.content.decode()) response = self.client.post(url, data={ 'action': 'rsvp' }, follow=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIn(self.person, self.other_event.attendees.all()) self.assertIn('Annuler ma participation', response.content.decode()) rsvp_notification.delay.assert_called_once() rsvp = RSVP.objects.get(person=self.person, event=self.other_event) self.assertEqual(rsvp_notification.delay.call_args[0][0], rsvp.pk)
def test_can_join(self, someone_joined): url = reverse('view_group', kwargs={'pk': self.manager_group.pk}) self.client.force_login(self.other_person.role) response = self.client.get(url) self.assertNotIn(self.other_person, self.manager_group.members.all()) self.assertIn('Rejoindre ce groupe', response.content.decode()) response = self.client.post(url, data={ 'action': 'join' }, follow=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIn(self.other_person, self.manager_group.members.all()) self.assertIn('Quitter le groupe', response.content.decode()) someone_joined.delay.assert_called_once() membership = Membership.objects.get(person=self.other_person, supportgroup=self.manager_group) self.assertEqual(someone_joined.delay.call_args[0][0], membership.pk)
def test_cannot_view_unpublished_group(self, geocode_person): self.client.force_login(self.person.role) self.referent_group.published = False self.referent_group.save() res = self.client.get(reverse('dashboard')) self.assertNotContains(res, self.referent_group.pk) geocode_person.delay.assert_called_once() res = self.client.get('/groupes/{}/'.format(self.referent_group.pk)) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) group_pages = ['view_group', 'manage_group', 'edit_group', 'change_group_location', 'quit_group'] for page in group_pages: res = self.client.get(reverse(page, args=(self.referent_group.pk,))) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND, '"{}" did not return 404'.format(page))
def post(self, request, cid): if self.contest.status != 0: raise PermissionDenied text = request.POST["text"] if not text or not request.user.is_authenticated: raise PermissionDenied if is_contest_manager(request.user, self.contest): ContestClarification.objects.create(contest=self.contest, important=True, author=request.user, answer=text) notify.send(sender=request.user, recipient=list(map(lambda x: x.user, self.contest.contestparticipant_set.select_related("user").all())), verb="posted a notification in", level="warning", target=self.contest, description=text) else: ContestClarification.objects.create(contest=self.contest, author=request.user, text=text) notify.send(sender=request.user, recipient=self.contest.managers.all(), verb="asked a question in", level="warning", target=self.contest, description=text) return redirect(reverse("contest:dashboard", kwargs={"cid": self.contest.pk}))
def post(self, request, cid): try: if self.contest.status != 0: raise ValueError("Contest is not running.") lang = request.POST.get('lang', '') if lang not in self.contest.supported_language_list: raise ValueError("Invalid language.") try: problem = self.contest.contestproblem_set.get(identifier=request.POST.get('problem', '')).problem_id except ContestProblem.DoesNotExist: raise ValueError("Invalid problem.") submission = create_submission(problem, self.user, request.POST.get('code', ''), lang, contest=self.contest, ip=get_ip(request)) contest_participant, _ = self.contest.contestparticipant_set.get_or_create(user=self.user) if contest_participant.is_disabled: raise ValueError("You have quitted the contest.") judge_submission_on_contest(submission) return JsonResponse({"url": reverse('contest:submission_api', kwargs={'cid': self.contest.id, 'sid': submission.id})}) except Exception as e: return HttpResponseBadRequest(str(e).encode())
def proxy_file_downloader(request): if not is_admin_or_root(request.user): raise PermissionDenied def download_file(url): local_filename = url.split('/')[-1] if local_filename == '': local_filename = random_string() r = requests.get(url, stream=True, timeout=30) with open(path.join(settings.UPLOAD_DIR, local_filename), 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) if request.method == 'POST': try: url = request.POST['url'] Thread(target=download_file, args=(url,)).start() except Exception as e: raise PermissionDenied(repr(e)) return redirect(reverse('filemanager'))
def authorize_user(func): def _authorize_user(request, *args, **kwargs): anno_user_id = request.session.get('anno_user_id', False) if not anno_user_id: return HttpResponseRedirect(reverse('annotator:login')) try: anno_user = AnnoUser.objects.get(id=anno_user_id) request.session['user_name'] = anno_user.user_name try: ret = func(request, *args, **kwargs) return ret finally: del request.session['user_name'] except AnnoUser.DoesNotExist: return HttpResponseRedirect(reverse('annotator:login')) return _authorize_user
def get_absolute_url(self): return reverse('event-detail', kwargs={'pk': self.pk})
def __call__(self, request): url = resolve(request.path_info) if request.user.is_anonymous and url.url_name not in self.UNAUTHENTICATED_URLS: return redirect(reverse('common:login') + f'?next={request.path}') return self.get_response(request)
def test_home_has_all_domains(self): domain1 = Domain(name='????', keywords='???1|???2') domain1.save() domain2 = Domain(name='????2', keywords='???1|???3') domain2.save() resp = self.client.get(reverse('home')) resp.text = resp.content.decode('utf-8') self.assertIn(domain1.name, resp.text) self.assertIn(domain1.get_absolute_url(), resp.text) self.assertIn(domain2.name, resp.text) self.assertIn(domain2.get_absolute_url(), resp.text)
def test_home_has_pages(self): page1 = Page(title='??1', url='https://test1.org', birth_date='2017-06-30', has_birth_date=True) page1.save() page2 = Page(title='??2', url='https://test2.org', birth_date='2017-07-01', has_birth_date=True) page2.save() resp = self.client.get(reverse('home')) resp.text = resp.content.decode('utf-8') self.assertIn(page1.title, resp.text) self.assertIn(page1.url, resp.text) self.assertIn(page1.birth_date, resp.text) self.assertIn(page2.title, resp.text) self.assertIn(page2.url, resp.text) self.assertIn(page2.birth_date, resp.text)
def test_domain_page_ok(self): domain = Domain(name='????', keywords='???1|???2') domain.save() resp = self.client.get(reverse('domain', kwargs=dict(domain_id=domain.id))) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, 'index.html')
def test_domain_page_has_title(self): domain = Domain(name='????', keywords='???1|???2') domain.save() resp = self.client.get(reverse('domain', kwargs=dict(domain_id=domain.id))) resp.text = resp.content.decode('utf-8') self.assertRegexpMatches(resp.text, r'<title>.*?{}.*?</title>'.format(domain.name))
def test_domain_page_has_all_domains(self): domain = Domain(name='????', keywords='???1|???2') domain.save() resp = self.client.get(reverse('domain', kwargs=dict(domain_id=domain.id))) resp.text = resp.content.decode('utf-8') self.assertIn(domain.get_absolute_url(), resp.text) self.assertRegexpMatches( resp.text, re.compile(r'<body>.*?{}.*?</body>'.format(domain.name), re.I|re.DOTALL))
def get_absolute_url(self): return reverse('domain', kwargs=dict(domain_id=self.pk))
def scan_site(request: HttpRequest, site_id: Union[int, None] = None) -> HttpResponse: """Schedule the scan of a site.""" if site_id: site = get_object_or_404( Site.objects.annotate_most_recent_scan_start() \ .annotate_most_recent_scan_end_or_null(), pk=site_id) else: # no site_id supplied form = SingleSiteForm(request.POST) if form.is_valid(): site, created = Site.objects.annotate_most_recent_scan_start() \ .annotate_most_recent_scan_end_or_null().get_or_create( url=form.cleaned_data.get('url')) if created: site.last_scan__end_or_null = None site.last_scan__start = None else: return render(request, 'frontend/create_site.html', { 'form': form, }) status_code = site.scan() if status_code == Site.SCAN_OK: if not site_id: # if the site is new we want to show the dog return redirect(reverse('frontend:scan_site_created', args=(site.pk,))) else: num_scanning_sites = Scan.objects.filter(end__isnull=True).count() messages.success(request, _("A scan of the site has been scheduled. "+ \ "The total number of sites in the scanning queue "+ \ "is %i (including yours)." % num_scanning_sites)) return redirect(reverse('frontend:view_site', args=(site.pk,))) elif status_code == Site.SCAN_COOLDOWN: messages.warning(request, _('The site is already scheduled for scanning or it has been scanned recently. No scan was scheduled.')) elif status_code == Site.SCAN_BLACKLISTED: messages.warning(request, _('The operator of this website requested to be blacklisted, scanning this website is not possible, sorry.')) return redirect(reverse('frontend:view_site', args=(site.pk,)))
def success_url(self): return self.request.POST.get('return_url', reverse('management-post-list'))