def htmllist(request): LOGGER.debug('HTML list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) start = int(reqd['start']) if 'start' in reqd else 0 assert start >= 0 docins = DocumentIndex.objects.using('sphinx').filter(**par).order_by( '-posted', 'id') total = docins.count() if total and start >= total: start = total - 1 if start >= FTLIM: if 'text' in reqd: return render( request, 'ftlim.xhtml', { 'app': APP, 'page_title': FTLIM_TITLE, 'limit': FTLIM, 'back': reverse('uds:mainpage') }) docs = Document.objects.filter(**par).order_by('-posted', 'id').distinct() total = docs.count() if total and start >= total: start = total - 1 docs = docs[start:(start + BATCH)] else: docins = list(docins[start:(start + BATCH)].values_list('id', flat=True)) docs = Document.objects.filter(id__in=docins).order_by( '-posted', 'id').distinct() for doc in docs: doc.files = File.objects.filter( document=doc).order_by('fileid').distinct() idx = 1 for file in doc.files: file.brk = idx % 5 == 0 idx += 1 except: raise Http404 return render( request, 'uds_list.xhtml', { 'app': APP, 'page_title': 'Výsledky vyhledávání', 'rows': docs, 'pager': Pager(start, total, reverse('uds:htmllist'), reqd, BATCH), 'total': total, 'noindex': True })
def transdel(request, idx=0): LOGGER.debug( 'Transaction delete page accessed using method {}, id={}'.format(request.method, idx), request, request.POST) idx = int(idx) - 1 debt = getdebt(request) if not debt: # pragma: no cover return error(request) if idx >= len(debt.transactions): raise Http404 if request.method == 'GET': return render( request, 'hjp_transdel.xhtml', {'app': APP, 'page_title': 'Smazání transakce', 'date': debt.transactions[idx].date}) else: button = getbutton(request) if button == 'yes': del debt.transactions[idx] if not setdebt(request, debt): # pragma: no cover return error(request) return redirect('hjp:transdeleted') return redirect('hjp:mainpage')
def doc(request, filename): LOGGER.debug('Document accessed: {}'.format(filename), request) pathname = join(BASE_DIR, filename).encode('utf-8') if not isfile(pathname): raise Http404 mimetype = guess_type(filename, strict=False)[0] or '(neznámý)' mtime = datetime.fromtimestamp( getmtime(pathname)).strftime('%d.%m.%Y %H:%M:%S') docinfo = { 'filename': filename, 'path': split(filename)[0], 'basename': basename(filename), 'mimetype': mimetype, 'mtime': mtime, 'url': getdocurl(filename), } return render(request, 'doc.xhtml', { 'page_title': 'Archivovaný dokument', 'docinfo': docinfo })
def pwchange(request): LOGGER.debug('Password change page accessed using method {}'.format(request.method), request, request.POST) var = {'page_title': 'Změna hesla'} user = request.user uid = user.id username = request.user.username if request.method == 'POST': if request.POST.get('back'): return redirect('home') fields = ('oldpassword', 'newpassword1', 'newpassword2') for fld in fields: var[fld] = request.POST.get(fld, '') if not user.check_password(var['oldpassword']): var['error_message'] = 'Nesprávné heslo' var['oldpassword'] = '' elif var['newpassword1'] != var['newpassword2']: var['error_message'] = 'Zadaná hesla se neshodují' var['newpassword1'] = var['newpassword2'] = '' elif len(var['newpassword1']) < MIN_PWLEN: var['error_message'] = 'Nové heslo je příliš krátké' var['newpassword1'] = var['newpassword2'] = '' else: user.set_password(var['newpassword1']) user.save() LOGGER.info('User "{}" ({:d}) changed password'.format(username, uid), request) return redirect('/accounts/pwchanged/') return render(request, 'pwchange.xhtml', var)
def pwchange(request): LOGGER.debug( 'Password change page accessed using method {}'.format(request.method), request, request.POST) var = {'page_title': 'Změna hesla'} user = request.user uid = user.id username = request.user.username if request.method == 'POST': if request.POST.get('back'): return redirect('home') fields = ('oldpassword', 'newpassword1', 'newpassword2') for fld in fields: var[fld] = request.POST.get(fld, '') if not user.check_password(var['oldpassword']): var['error_message'] = 'Nesprávné heslo' var['oldpassword'] = '' elif var['newpassword1'] != var['newpassword2']: var['error_message'] = 'Zadaná hesla se neshodují' var['newpassword1'] = var['newpassword2'] = '' elif len(var['newpassword1']) < MIN_PWLEN: var['error_message'] = 'Nové heslo je příliš krátké' var['newpassword1'] = var['newpassword2'] = '' else: user.set_password(var['newpassword1']) user.save() LOGGER.info( 'User "{}" ({:d}) changed password'.format(username, uid), request) return redirect('/accounts/pwchanged/') return render(request, 'pwchange.xhtml', var)
def robots(request): LOGGER.debug('robots.txt requested', request) return render( request, 'robots.txt', content_type='text/plain; charset=utf-8')
def doc(request, filename): LOGGER.debug('Document accessed: {}'.format(filename), request) pathname = join(BASE_DIR, filename).encode('utf-8') if not isfile(pathname): raise Http404 mimetype = guess_type(filename, strict=False)[0] or '(neznámý)' mtime = datetime.fromtimestamp(getmtime(pathname)).strftime('%d.%m.%Y %H:%M:%S') docinfo = { 'filename': filename, 'path': split(filename)[0], 'basename': basename(filename), 'mimetype': mimetype, 'mtime': mtime, 'url': getdocurl(filename), } return render( request, 'doc.xhtml', {'page_title': 'Archivovaný dokument', 'docinfo': docinfo})
def home(request): LOGGER.debug('Home page accessed', request) grps = [ { 'title': 'Jednoduché výpočty', 'apps': convappinfo(['sop', 'lht', 'cin', 'dvt', 'cnb', 'kos']) }, { 'title': 'Komplexní výpočty', 'apps': convappinfo(['knr', 'hjp', 'hsp']) }, { 'title': 'Prohlížení databasí', 'apps': convappinfo(['psj', 'uds', 'udn', 'pir']) }, { 'title': 'Sledování', 'apps': convappinfo(['szr', 'sur', 'sir', 'dir']) }, ] return render(request, 'home.xhtml', { 'page_title': 'Právnické výpočty', 'grps': grps, 'suppress_home': True })
def about(request): LOGGER.debug('About page accessed', request) server_version = connection.pg_version env = ( { 'name': 'Python', 'version': python_version() }, { 'name': 'Django', 'version': django_version() }, { 'name': 'PostgreSQL', 'version': '{:d}.{:d}.{:d}'.format(server_version // 10000, (server_version // 100) % 100, server_version % 100) }, { 'name': 'Platforma', 'version': '{0}-{2}'.format(*uname()) }, ) return render(request, 'about.xhtml', { 'page_title': 'O aplikaci', 'apps': getappinfo(), 'env': env })
def htmllist(request): LOGGER.debug('HTML list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) start = int(reqd['start']) if 'start' in reqd else 0 assert start >= 0 res = Hearing.objects.filter(**par).order_by('-time', 'pk').distinct() except: raise Http404 total = res.count() if total and start >= total: start = total - 1 return render( request, 'psj_list.xhtml', {'app': APP, 'page_title': 'Výsledky vyhledávání', 'rows': res[start:start + BATCH], 'pager': Pager(start, total, reverse('psj:htmllist'), reqd, BATCH), 'today': date.today(), 'total': total, 'NULL_REGISTERS': NULL_REGISTERS, 'noindex': True})
def stat(request): LOGGER.debug('Statistics page accessed', request) return render(request, 'stat.xhtml', { 'page_title': 'Statistické údaje', 'apps': getappstat(), })
def error400(request, *args, **kwargs): LOGGER.debug('Bad request error page (400) generated', request) return render( request, '400.xhtml', {}, status=HTTPStatus.BAD_REQUEST)
def error404(request, *args, **kwargs): LOGGER.debug('Not found error page (404) generated', request) return render( request, '404.xhtml', {}, status=HTTPStatus.NOT_FOUND)
def error403_csrf(request, *args, **kwargs): LOGGER.debug('Permission denied due to CSRF violation error page (403_csrf) generated', request) return render( request, '403_csrf.xhtml', {}, status=HTTPStatus.FORBIDDEN)
def userinfo(request): LOGGER.debug('User information page accessed', request) return render( request, 'user.xhtml', { 'page_title': 'Informace o uživateli', 'userinfo': getuserinfo(request.user), })
def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) err_message = '' page_title = apps.get_app_config(APP).verbose_name if request.method == 'GET': form = MainForm() return render( request, 'pir_mainpage.xhtml', { 'app': APP, 'page_title': page_title, 'err_message': err_message, 'form': form }) form = MainForm(request.POST) if form.is_valid(): cld = form.cleaned_data for key in ('name', 'first_name', 'city'): if not cld[key]: del cld[key + '_opt'] cld['birthid'] = cld['birthid'].replace('/', '') query = QueryDict(mutable=True) for key in cld: if cld[key]: query[key] = cld[key] for key in ('role_debtor', 'role_trustee', 'role_creditor', 'deleted', 'creditors'): if cld[key]: query[key] = 'on' query['start'] = 0 del query['format'] return redirect('{}?{}'.format( reverse('{}:{}list'.format(APP, cld['format'])), query.urlencode())) LOGGER.debug('Invalid form', request) err_message = INERR return render( request, 'pir_mainpage.xhtml', { 'app': APP, 'page_title': page_title, 'err_message': err_message, 'form': form })
def error500(request, *args, **kwargs): LOGGER.debug('Internal server error page (500) generated', request) return render( request, '500.xhtml', {}, status=HTTPStatus.INTERNAL_SERVER_ERROR)
def error(request): LOGGER.debug('Internal server error page generated', request) var = {'page_title': 'Interní chyba aplikace'} return render(request, 'error.xhtml', var, status=HTTPStatus.INTERNAL_SERVER_ERROR)
def gdpr(request): LOGGER.debug('GDPR page accessed', request) return render( request, 'gdpr.xhtml', {'page_title': 'Ochrana osobních údajů'})
def error403(request, *args, **kwargs): LOGGER.debug('Permission denied error page (403) generated', request) return render( request, '403.xhtml', {}, status=HTTPStatus.FORBIDDEN)
def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) messages = [] if request.method == 'GET': form = MainForm() else: form = MainForm(request.POST) if form.is_valid(): cld = form.cleaned_data beg_date = cld['beg_date'] years = (cld['years'] if cld['years'] else 0) months = (cld['months'] if cld['months'] else 0) days = (cld['days'] if cld['days'] else 0) messages.append( ('Trest skončí: {}'.format(calc( beg_date, years, months, days)), 'res')) messages.append( ('Třetina trestu: {}'.format(calc( beg_date, years // 3, ((years % 3) * 4) + (months // 3), ((months % 3) * 10) + (days // 3))), 'normal')) messages.append( ('Polovina trestu: {}'.format(calc( beg_date, years // 2, ((years % 2) * 6) + (months // 2), ((months % 2) * 15) + (days // 2))), 'normal')) messages.append( ('Dvě třetiny trestu: {}'.format(calc( beg_date, (years * 2) // 3, (((years * 2) % 3) * 4) + ((months * 2) // 3), (((months * 2) % 3) * 10) + ((days * 2) // 3))), None)) else: LOGGER.debug('Invalid form', request) messages = [(INERR_SHORT, None)] return render( request, 'dvt_mainpage.xhtml', {'app': APP, 'form': form, 'messages': messages, 'page_title': 'Doba výkonu trestu'})
def procform(request, idx=0): LOGGER.debug( 'Proceedings form accessed using method {}, id={}'.format( request.method, idx), request, request.POST) err_message = '' uid = request.user.id uname = request.user.username page_title = 'Úprava řízení' if idx else 'Nové řízení' button = getbutton(request) if request.method == 'GET': form = ProcForm(initial=model_to_dict( get_object_or_404(Proceedings, pk=idx, uid=uid))) if idx else ProcForm() elif button == 'back': return redirect('szr:mainpage') else: form = ProcForm(request.POST) if form.is_valid(): cld = form.cleaned_data if not cld['senate']: cld['senate'] = 0 if idx: proc = get_object_or_404(Proceedings, pk=idx, uid=uid) cld['pk'] = idx cld['timestamp_add'] = proc.timestamp_add cld['court_id'] = cld['court'] del cld['court'] onlydesc = (idx and proc.court.id == cld['court_id'] and proc.senate == cld['senate'] and proc.register == cld['register'] and proc.number == cld['number'] and proc.year == cld['year']) if onlydesc: cld['changed'] = proc.changed cld['updated'] = proc.updated cld['hash'] = proc.hash cld['auxid'] = proc.auxid cld['notify'] = proc.notify proc = Proceedings(uid_id=uid, **cld) if not onlydesc: updateproc(proc) proc.save() LOGGER.info( 'User "{}" ({:d}) {} proceedings "{}" ({})'.format( uname, uid, 'updated' if idx else 'added', proc.desc, p2s(proc)), request) return redirect('szr:mainpage') else: # pragma: no cover LOGGER.debug('Invalid form', request) err_message = INERR return render( request, 'szr_procform.xhtml', { 'app': APP, 'form': form, 'page_title': page_title, 'err_message': err_message })
def error(request): LOGGER.debug('Internal server error page generated', request) var = {'page_title': 'Interní chyba aplikace'} return render( request, 'error.xhtml', var, status=HTTPStatus.INTERNAL_SERVER_ERROR)
def unauth(request): LOGGER.debug('Unauthorized access', request) var = {'page_title': 'Neoprávněný přístup'} return render( request, 'unauth.xhtml', var, status=HTTPStatus.UNAUTHORIZED)
def userinfo(request): LOGGER.debug('User information page accessed', request) return render( request, 'user.xhtml', {'page_title': 'Informace o uživateli', 'userinfo': getuserinfo(request.user), })
def stat(request): LOGGER.debug('Statistics page accessed', request) return render( request, 'stat.xhtml', {'page_title': 'Statistické údaje', 'apps': getappstat(), })
def courts(request): LOGGER.debug('List of courts accessed', request) return render( request, 'szr_courts.xhtml', { 'app': APP, 'page_title': 'Přehled soudů', 'rows': Court.objects.order_by('name').values('id', 'name') })
def courts(request): LOGGER.debug('List of courts accessed', request) return render( request, 'szr_courts.xhtml', {'app': APP, 'page_title': 'Přehled soudů', 'rows': Court.objects.order_by('name').values('id', 'name')})
def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) err_message = '' page_title = apps.get_app_config(APP).verbose_name if request.method == 'GET': form = MainForm() return render( request, 'pir_mainpage.xhtml', {'app': APP, 'page_title': page_title, 'err_message': err_message, 'form': form}) form = MainForm(request.POST) if form.is_valid(): cld = form.cleaned_data for key in ('name', 'first_name', 'city'): if not cld[key]: del cld[key + '_opt'] cld['birthid'] = cld['birthid'].replace('/', '') query = QueryDict(mutable=True) for key in cld: if cld[key]: query[key] = cld[key] for key in ('role_debtor', 'role_trustee', 'role_creditor', 'deleted', 'creditors'): if cld[key]: query[key] = 'on' query['start'] = 0 del query['format'] return redirect('{}?{}'.format( reverse('{}:{}list'.format(APP, cld['format'])), query.urlencode())) LOGGER.debug('Invalid form', request) err_message = INERR return render( request, 'pir_mainpage.xhtml', {'app': APP, 'page_title': page_title, 'err_message': err_message, 'form': form})
def debtorform(request, idx=0): LOGGER.debug( 'Debtor form accessed using method {}, id={}'.format(request.method, idx), request, request.POST) err_message = '' uid = request.user.id uname = request.user.username page_title = 'Úprava dlužníka' if idx else 'Nový dlužník' button = getbutton(request) if request.method == 'GET': if idx: debtor = model_to_dict(get_object_or_404(Debtor, pk=idx, uid=uid)) for opt in OPTS: debtor[opt] = TEXT_OPTS_KEYS[debtor[opt]] if debtor['birthid']: debtor['birthid'] = '{}/{}'.format(debtor['birthid'][:6], debtor['birthid'][6:]) form = DebtorForm(initial=debtor) else: form = DebtorForm() elif button == 'back': return redirect('dir:mainpage') else: form = DebtorForm(request.POST) if form.is_valid(): cld = form.cleaned_data if idx: debtor = get_object_or_404(Debtor, pk=idx, uid=uid) cld['pk'] = idx cld['notify'] = debtor.notify cld['timestamp_add'] = debtor.timestamp_add cld['birthid'] = cld['birthid'].replace('/', '') for key in cld: if cld[key] == '': cld[key] = None debtor = Debtor(uid_id=uid, **cld) for opt in OPTS: debtor.__setattr__(opt, TEXT_OPTS_KEYS.index(cld[opt])) debtor.save() LOGGER.info( 'User "{}" ({:d}) {} debtor {}'.format(uname, uid, 'updated' if idx else 'added', debtor.desc), request) return redirect('dir:mainpage') else: LOGGER.debug('Invalid form', request) err_message = INERR return render( request, 'dir_debtorform.xhtml', {'app': APP, 'form': form, 'page_title': page_title, 'err_message': err_message})
def courts(request): LOGGER.debug('List of courts accessed', request) rows = sorted([{'short': L2S[x], 'name': L2N[x]} for x in Vec.objects.values_list('idOsobyPuvodce', flat=True).distinct()], key=lambda x: strxfrm(x['name'])) return render( request, 'sir_courts.xhtml', {'app': APP, 'page_title': 'Přehled insolvenčních soudů', 'rows': rows})
def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) err_message = '' page_title = apps.get_app_config(APP).verbose_name if request.method == 'GET': form = MainForm() return render( request, 'psj_mainpage.xhtml', {'app': APP, 'page_title': page_title, 'err_message': err_message, 'form': form}) else: form = MainForm(request.POST) if form.is_valid(): cld = form.cleaned_data if not cld['party']: del cld['party_opt'] query = QueryDict(mutable=True) for key in cld: if cld[key]: query[key] = cld[key] query['start'] = 0 del query['format'] return redirect('{}?{}'.format( reverse('{}:{}list'.format(APP, cld['format'])), query.urlencode())) else: LOGGER.debug('Invalid form', request) err_message = INERR return render( request, 'psj_mainpage.xhtml', {'app': APP, 'page_title': page_title, 'err_message': err_message, 'form': form})
def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) err_message = '' page_title = apps.get_app_config(APP).verbose_name agendas = Agenda.objects.all().order_by('desc') if request.method == 'GET': form = MainForm() return render( request, 'uds_mainpage.xhtml', { 'app': APP, 'page_title': page_title, 'err_message': err_message, 'agendas': agendas, 'form': form }) form = MainForm(request.POST) if form.is_valid(): cld = form.cleaned_data query = QueryDict(mutable=True) for key in cld: if cld[key]: query[key] = cld[key] query['start'] = 0 del query['format'] return redirect('{}?{}'.format( reverse('{}:{}list'.format(APP, cld['format'])), query.urlencode())) err_message = INERR LOGGER.debug('Invalid form', request) return render( request, 'uds_mainpage.xhtml', { 'app': APP, 'page_title': page_title, 'err_message': err_message, 'agendas': agendas, 'form': form })
def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) err_message = '' page_title = apps.get_app_config(APP).verbose_name agendas = Agenda.objects.all().order_by('desc') if request.method == 'GET': form = MainForm() return render( request, 'udn_mainpage.xhtml', {'app': APP, 'page_title': page_title, 'err_message': err_message, 'agendas': agendas, 'form': form}) form = MainForm(request.POST) if form.is_valid(): cld = form.cleaned_data if not cld['party']: del cld['party_opt'] query = QueryDict(mutable=True) for key in cld: if cld[key]: query[key] = cld[key] query['start'] = 0 del query['format'] return redirect('{}?{}'.format(reverse('{}:{}list'.format(APP, cld['format'])), query.urlencode())) err_message = INERR LOGGER.debug('Invalid form', request) return render( request, 'udn_mainpage.xhtml', {'app': APP, 'page_title': page_title, 'err_message': err_message, 'agendas': agendas, 'form': form})
def procform(request, idx=0): LOGGER.debug('Proceedings form accessed using method {}, id={}'.format(request.method, idx), request, request.POST) err_message = '' uid = request.user.id uname = request.user.username page_title = 'Úprava řízení' if idx else 'Nové řízení' button = getbutton(request) if request.method == 'GET': form = ProcForm(initial=model_to_dict(get_object_or_404(Proceedings, pk=idx, uid=uid))) if idx else ProcForm() elif button == 'back': return redirect('szr:mainpage') else: form = ProcForm(request.POST) if form.is_valid(): cld = form.cleaned_data if not cld['senate']: cld['senate'] = 0 if idx: proc = get_object_or_404(Proceedings, pk=idx, uid=uid) cld['pk'] = idx cld['timestamp_add'] = proc.timestamp_add cld['court_id'] = cld['court'] del cld['court'] onlydesc = ( idx and proc.court.id == cld['court_id'] and proc.senate == cld['senate'] and proc.register == cld['register'] and proc.number == cld['number'] and proc.year == cld['year']) if onlydesc: cld['changed'] = proc.changed cld['updated'] = proc.updated cld['hash'] = proc.hash cld['auxid'] = proc.auxid cld['notify'] = proc.notify proc = Proceedings(uid_id=uid, **cld) if not onlydesc: updateproc(proc) proc.save() LOGGER.info( 'User "{}" ({:d}) {} proceedings "{}" ({})' .format(uname, uid, 'updated' if idx else 'added', proc.desc, p2s(proc)), request) return redirect('szr:mainpage') else: # pragma: no cover LOGGER.debug('Invalid form', request) err_message = INERR return render( request, 'szr_procform.xhtml', {'app': APP, 'form': form, 'page_title': page_title, 'err_message': err_message})
def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) today = date.today() messages = [] if request.method == 'GET': form = MainForm() else: form = MainForm(request.POST) button = getbutton(request) if button == 'set_beg_date': form.data = form.data.copy() form.data['beg_date'] = today elif form.is_valid(): cld = form.cleaned_data beg = cld['beg_date'] preset = cld['preset'] if preset == 'none': dur = cld['dur'] unit = cld['unit'] else: dur = int(preset[1:]) unit = preset[0] per = Period(beg, dur, unit) if per.error: messages = [(per.msg, None)] else: if per.res != per.bus: messages.append(('{} není pracovní den'.format(fdt(per.res)), None)) messages.append(('{} {}'.format(WD_NAMES[per.bus.weekday()], fdt(per.bus)), 'res')) if per.unc: messages.append(('(evidence pracovních dnů v tomto období není úplná)', 'note')) else: LOGGER.debug('Invalid form', request) messages = [(INERR_SHORT, None)] return render(request, 'lht_mainpage.xhtml', {'app': APP, 'page_title': 'Konec lhůty', 'messages': messages, 'form': form})
def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) err_message = '' uid = request.user.id page_title = 'Sledování účastníků řízení' reqd = request.GET.copy() start = int(reqd['start']) if 'start' in reqd else 0 if request.method == 'GET': form = EmailForm( initial=model_to_dict(get_object_or_404(User, pk=uid))) else: form = EmailForm(request.POST) if form.is_valid(): cld = form.cleaned_data user = get_object_or_404(User, pk=uid) user.email = cld['email'] user.save() return redirect('sur:mainpage') else: LOGGER.debug('Invalid form', request) err_message = INERR res = Party.objects.filter(uid=uid).order_by('party', 'party_opt', 'pk').values() total = res.count() if start >= total and total: start = total - 1 rows = res[start:start + BATCH] for row in rows: row['party_opt_text'] = TEXT_OPTS[row['party_opt']][1] query = QueryDict(mutable=True) query['party'] = row['party'] query['party_opt'] = TEXT_OPTS_KEYS[row['party_opt']] row['search'] = query.urlencode() query = QueryDict(mutable=True) query['text'] = '"{}"'.format(row['party']) row['uds_search'] = query.urlencode() return render( request, 'sur_mainpage.xhtml', { 'app': APP, 'form': form, 'page_title': page_title, 'err_message': err_message, 'rows': rows, 'pager': Pager(start, total, reverse('sur:mainpage'), reqd, BATCH), 'total': total })
def csvlist(request): LOGGER.debug('CSV list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) resins = DocumentIndex.objects.using('sphinx').filter(**par).order_by( 'posted', 'id') except: raise Http404 total = resins.count() if total > EXLIM: return render( request, 'exlim.xhtml', { 'app': APP, 'page_title': EXLIM_TITLE, 'limit': EXLIM, 'total': total, 'back': reverse('uds:mainpage') }) resins = list(resins.values_list('id', flat=True)) res = Document.objects.filter(id__in=resins).order_by('posted', 'id').distinct() response = HttpResponse(content_type='text/csv; charset=utf-8') response['Content-Disposition'] = 'attachment; filename=Dokumenty.csv' writer = csvwriter(response) hdr = ( 'Datum vyvěšení', 'Soud/státní zastupitelství', 'Popis dokumentu', 'Spisová značka/číslo jednací', 'Agenda', 'Soubory', ) writer.writerow(hdr) for item in res: files = File.objects.filter( document=item).order_by('fileid').distinct() dat = ( '{:%d.%m.%Y}'.format(item.posted), item.publisher.name, item.desc, item.ref, item.agenda.desc, ';'.join([ join(REPO_PREFIX, str(fil.fileid), fil.name) for fil in files ]), ) writer.writerow(dat) return response
def csvlist(request): LOGGER.debug('CSV list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) res = Hearing.objects.filter(**par).order_by('time', 'pk').distinct() except: raise Http404 total = res.count() if total > EXLIM: return render( request, 'exlim.xhtml', {'app': APP, 'page_title': EXLIM_TITLE, 'limit': EXLIM, 'total': total, 'back': reverse('psj:mainpage')}) response = HttpResponse(content_type='text/csv; charset=utf-8') response['Content-Disposition'] = 'attachment; filename=Jednani.csv' writer = csvwriter(response) hdr = ( 'Soud', 'Jednací síň', 'Datum', 'Čas', 'Spisová značka', 'Řešitel', 'Účastníci řízení', 'Druh jednání', 'Neveřejné', 'Zrušeno', ) writer.writerow(hdr) for item in res: dat = ( item.courtroom.court.name, item.courtroom.desc, '{:%d.%m.%Y}'.format(item.time), '{:%H:%M}'.format(item.time), composeref(item.senate, item.register, item.number, item.year), item.judge.name, ';'.join([p['name'] for p in item.parties.values()]), item.form.name, 'ano' if item.closed else 'ne', 'ano' if item.cancelled else 'ne', ) writer.writerow(dat) return response
def courtinfo(request, court): LOGGER.debug('Court information accessed, court="{}"'.format(court), request) courtrooms = ( Hearing.objects.filter(courtroom__court_id=court).values('courtroom_id', 'courtroom__desc').distinct() .order_by('courtroom__desc')) judges = list(Hearing.objects.filter(courtroom__court_id=court).values('judge_id', 'judge__name').distinct()) judges.sort(key=stripjudge) return render( request, 'psj_court.xhtml', {'courtrooms': courtrooms, 'judges': judges}, content_type='text/plain; charset=utf-8')
def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) err_message = '' uid = request.user.id page_title = 'Sledování nových dlužníků v insolvenci' rdt = request.GET.copy() start = int(rdt['start']) if 'start' in rdt else 0 if request.method == 'GET': form = EmailForm(initial=model_to_dict(get_object_or_404(User, pk=uid))) else: form = EmailForm(request.POST) if form.is_valid(): cld = form.cleaned_data user = get_object_or_404(User, pk=uid) user.email = cld['email'] user.save() return redirect('dir:mainpage') else: LOGGER.debug('Invalid form', request) err_message = INERR debtors = Debtor.objects.filter(uid=uid).order_by('desc', 'pk').values() total = debtors.count() if start >= total and total: start = total - 1 rows = debtors[start:(start + BATCH)] for row in rows: query = QueryDict(mutable=True) query['role_debtor'] = query['deleted'] = 'on' for key in ('court', 'genid', 'taxid', 'birthid', 'date_birth', 'year_birth_from', 'year_birth_to'): if row[key]: query[key] = row[key] for key in OFIELDS: if row[key]: query[key] = row[key] key_opt = '{}_opt'.format(key) query[key_opt] = TEXT_OPTS_KEYS[row[key_opt]] row['search'] = query.urlencode() return render( request, 'dir_mainpage.xhtml', {'app': APP, 'form': form, 'page_title': page_title, 'err_message': err_message, 'rows': rows, 'pager': Pager(start, total, reverse('dir:mainpage'), rdt, BATCH), 'total': total})
def courts(request): LOGGER.debug('List of courts accessed', request) rows = sorted([{ 'short': L2S[x], 'name': L2N[x] } for x in Vec.objects.values_list('idOsobyPuvodce', flat=True).distinct() ], key=lambda x: strxfrm(x['name'])) return render(request, 'sir_courts.xhtml', { 'app': APP, 'page_title': 'Přehled insolvenčních soudů', 'rows': rows })
def partyform(request, idx=0): LOGGER.debug( 'Party form accessed using method {}, id={}'.format( request.method, idx), request, request.POST) err_message = '' uid = request.user.id uname = request.user.username page_title = 'Úprava účastníka' if idx else 'Nový účastník' button = getbutton(request) if request.method == 'GET': if idx: dct = model_to_dict(get_object_or_404(Party, pk=idx, uid=uid)) dct['party_opt'] = TEXT_OPTS_KEYS[dct['party_opt']] form = PartyForm(initial=dct) else: form = PartyForm() elif button == 'back': return redirect('sur:mainpage') else: form = PartyForm(request.POST) if form.is_valid(): cld = form.cleaned_data if idx: res = get_object_or_404(Party, pk=idx, uid=uid) cld['pk'] = idx cld['notify'] = res.notify cld['timestamp_add'] = res.timestamp_add res = Party(uid_id=uid, **cld) res.party_opt = TEXT_OPTS_KEYS.index(cld['party_opt']) res.save() LOGGER.info( 'User "{}" ({:d}) {} party {}'.format( uname, uid, 'updated' if idx else 'added', res.party), request) return redirect('sur:mainpage') else: LOGGER.debug('Invalid form', request) err_message = INERR return render( request, 'sur_partyform.xhtml', { 'app': APP, 'form': form, 'min_chars': grammar(MIN_LENGTH, GR_CHAR), 'page_title': page_title, 'err_message': err_message })
def lostpw(request): LOGGER.debug( 'Lost password page accessed using method {}'.format(request.method), request, request.POST) err_message = None page_title = 'Ztracené heslo' if request.method == 'GET': form = LostPwForm() elif request.POST.get('back'): return redirect('login') else: form = LostPwForm(request.POST) if form.is_valid(): cld = form.cleaned_data users = User.objects.filter(username=cld['username']) if users.exists() and users[0].email: user = users[0] link = '{:032x}'.format(getrandbits(16 * 8)) PwResetLink(user_id=user.id, link=link).save() text = '''Vážený uživateli, někdo požádal o obnovení hesla pro Váš účet "{0}" na serveru {1} ({2}). Pokud skutečně chcete své heslo obnovit, použijte, prosím, následující jednorázový odkaz: {2}{3} V případě, že jste o obnovení hesla nežádali, můžete tuto zprávu ignorovat. Server {1} ({2}) '''.format(user.username, LOCAL_SUBDOMAIN, LOCAL_URL, reverse('resetpw', args=(link, ))) send_mail('Link pro obnoveni hesla', text, (user.email, )) LOGGER.info( 'Password recovery link for user "{0.username}" ({0.id:d}) sent' .format(user), request) return redirect('/accounts/pwlinksent/') else: LOGGER.debug('Invalid form', request) err_message = 'Prosím, opravte označená pole ve formuláři' return render(request, 'lostpw.xhtml', { 'form': form, 'page_title': page_title, 'err_message': err_message, })
def jsonlist(request): LOGGER.debug('JSON list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) resins = DocumentIndex.objects.using('sphinx').filter(**par).order_by( 'posted', 'id') except: raise Http404 total = resins.count() if total > EXLIM: return render( request, 'exlim.xhtml', { 'app': APP, 'page_title': EXLIM_TITLE, 'limit': EXLIM, 'total': total, 'back': reverse('uds:mainpage') }) resins = list(resins.values_list('id', flat=True)) res = Document.objects.filter(id__in=resins).order_by('posted', 'id').distinct() response = HttpResponse(content_type='application/json; charset=utf-8') response['Content-Disposition'] = 'attachment; filename=Dokumenty.json' lst = [] for item in res: files = File.objects.filter( document=item).order_by('fileid').distinct() lst.append({ 'posted': item.posted.isoformat(), 'publisher': item.publisher.name, 'desc': item.desc, 'ref': item.ref, 'agenda': item.agenda.desc, 'files': [{ 'id': f.fileid, 'name': f.name, 'url': join(REPO_PREFIX, str(f.fileid), f.name) } for f in files], }) dump(lst, response) return response
def htmllist(request): LOGGER.debug('HTML list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) start = int(reqd['start']) if 'start' in reqd else 0 assert start >= 0 res = Vec.objects.filter(**par).order_by('firstAction', 'rocnik', 'bc', 'idOsobyPuvodce').distinct() except: raise Http404 total = res.count() if total and start >= total: start = total - 1 creditors = 'creditors' in reqd batch = 10 if creditors else 20 rows = res[start:start + batch] for row in rows: row.court = L2N[row.idOsobyPuvodce] row.court_short = L2S[row.idOsobyPuvodce] row.court_reg = L2R[row.idOsobyPuvodce] row.state = S2D[ row.druhStavRizeni.desc] if row.druhStavRizeni else '(není známo)' row.debtors = [] for osoba in getosoby(row, 'debtor'): row.debtors.append({ 'text': o2s(osoba, detailed=True), 'id': osoba.id }) row.trustees = [] for osoba in getosoby(row, 'trustee'): row.trustees.append({'text': o2s(osoba), 'id': osoba.id}) if creditors: row.creditors = [] for osoba in getosoby(row, 'motioner', 'creditor'): row.creditors.append({'text': o2s(osoba), 'id': osoba.id}) return render( request, 'pir_list.xhtml', { 'app': APP, 'page_title': 'Výsledky vyhledávání', 'rows': rows, 'creditors': creditors, 'pager': Pager(start, total, reverse('pir:htmllist'), reqd, batch), 'total': total, 'NULL_REGISTERS': NULL_REGISTERS, 'noindex': True })
def partydelall(request): LOGGER.debug('Delete all parties page accessed using method {}'.format(request.method), request) uid = request.user.id uname = request.user.username if request.method == 'GET': return render( request, 'sur_partydelall.xhtml', {'app': APP, 'page_title': 'Smazání všech účastníků'}) else: if getbutton(request) == 'yes' and 'conf' in request.POST and request.POST['conf'] == 'Ano': Party.objects.filter(uid=uid).delete() LOGGER.info('User "{}" ({:d}) deleted all parties'.format(uname, uid), request) return redirect('sur:mainpage')
def debtordelall(request): LOGGER.debug('Delete all debtors page accessed using method {}'.format(request.method), request) uid = request.user.id uname = request.user.username if request.method == 'GET': return render( request, 'dir_debtordelall.xhtml', {'app': APP, 'page_title': 'Smazání všech dlužníků'}) else: if getbutton(request) == 'yes' and 'conf' in request.POST and request.POST['conf'] == 'Ano': Debtor.objects.filter(uid=uid).delete() LOGGER.info('User "{}" ({:d}) deleted all debtors'.format(uname, uid), request) return redirect('dir:mainpage')
def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) err_message = '' uid = request.user.id page_title = 'Sledování účastníků řízení' reqd = request.GET.copy() start = int(reqd['start']) if 'start' in reqd else 0 if request.method == 'GET': form = EmailForm(initial=model_to_dict(get_object_or_404(User, pk=uid))) else: form = EmailForm(request.POST) if form.is_valid(): cld = form.cleaned_data user = get_object_or_404(User, pk=uid) user.email = cld['email'] user.save() return redirect('sur:mainpage') else: LOGGER.debug('Invalid form', request) err_message = INERR res = Party.objects.filter(uid=uid).order_by('party', 'party_opt', 'pk').values() total = res.count() if start >= total and total: start = total - 1 rows = res[start:start + BATCH] for row in rows: row['party_opt_text'] = TEXT_OPTS[row['party_opt']][1] query = QueryDict(mutable=True) query['party'] = row['party'] query['party_opt'] = TEXT_OPTS_KEYS[row['party_opt']] row['search'] = query.urlencode() query = QueryDict(mutable=True) query['text'] = '"{}"'.format(row['party']) row['uds_search'] = query.urlencode() return render( request, 'sur_mainpage.xhtml', {'app': APP, 'form': form, 'page_title': page_title, 'err_message': err_message, 'rows': rows, 'pager': Pager(start, total, reverse('sur:mainpage'), reqd, BATCH), 'total': total})
def htmllist(request): LOGGER.debug('HTML list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) start = int(reqd['start']) if 'start' in reqd else 0 assert start >= 0 res = Vec.objects.filter(**par).order_by('firstAction', 'rocnik', 'bc', 'idOsobyPuvodce').distinct() except: raise Http404 total = res.count() if total and start >= total: start = total - 1 creditors = 'creditors' in reqd batch = 10 if creditors else 20 rows = res[start:start + batch] for row in rows: row.court = L2N[row.idOsobyPuvodce] row.court_short = L2S[row.idOsobyPuvodce] row.court_reg = L2R[row.idOsobyPuvodce] row.state = S2D[row.druhStavRizeni.desc] if row.druhStavRizeni else '(není známo)' row.debtors = [] for osoba in getosoby(row, 'debtor'): row.debtors.append({ 'text': o2s(osoba, detailed=True), 'id': osoba.id}) row.trustees = [] for osoba in getosoby(row, 'trustee'): row.trustees.append({ 'text': o2s(osoba), 'id': osoba.id}) if creditors: row.creditors = [] for osoba in getosoby(row, 'motioner', 'creditor'): row.creditors.append({'text': o2s(osoba), 'id': osoba.id}) return render( request, 'pir_list.xhtml', {'app': APP, 'page_title': 'Výsledky vyhledávání', 'rows': rows, 'creditors': creditors, 'pager': Pager(start, total, reverse('pir:htmllist'), reqd, batch), 'total': total, 'NULL_REGISTERS': NULL_REGISTERS, 'noindex': True})
def partyform(request, idx=0): LOGGER.debug('Party form accessed using method {}, id={}'.format(request.method, idx), request, request.POST) err_message = '' uid = request.user.id uname = request.user.username page_title = 'Úprava účastníka' if idx else 'Nový účastník' button = getbutton(request) if request.method == 'GET': if idx: dct = model_to_dict(get_object_or_404(Party, pk=idx, uid=uid)) dct['party_opt'] = TEXT_OPTS_KEYS[dct['party_opt']] form = PartyForm(initial=dct) else: form = PartyForm() elif button == 'back': return redirect('sur:mainpage') else: form = PartyForm(request.POST) if form.is_valid(): cld = form.cleaned_data if idx: res = get_object_or_404(Party, pk=idx, uid=uid) cld['pk'] = idx cld['notify'] = res.notify cld['timestamp_add'] = res.timestamp_add res = Party(uid_id=uid, **cld) res.party_opt = TEXT_OPTS_KEYS.index(cld['party_opt']) res.save() LOGGER.info( 'User "{}" ({:d}) {} party {}'.format(uname, uid, 'updated' if idx else 'added', res.party), request) return redirect('sur:mainpage') else: LOGGER.debug('Invalid form', request) err_message = INERR return render( request, 'sur_partyform.xhtml', {'app': APP, 'form': form, 'min_chars': grammar(MIN_LENGTH, GR_CHAR), 'page_title': page_title, 'err_message': err_message})
def jsonlist(request): LOGGER.debug('JSON list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) res = Decision.objects.filter(**par).order_by('date', 'pk').distinct() except: raise Http404 total = res.count() if total > EXLIM: return render( request, 'exlim.xhtml', {'app': APP, 'page_title': EXLIM_TITLE, 'limit': EXLIM, 'total': total, 'back': reverse('udn:mainpage')}) response = HttpResponse(content_type='application/json; charset=utf-8') response['Content-Disposition'] = 'attachment; filename=Rozhodnuti.json' lst = [] court = { 'id': SUPREME_ADMINISTRATIVE_COURT, 'name': SUPREME_ADMINISTRATIVE_COURT_NAME, } for item in res: files = {'abridged': join(REPO_PREFIX, item.filename)} if item.anonfilename: files['anonymized'] = join(REPO_PREFIX, item.anonfilename) lst.append({ 'court': court, 'date': item.date.isoformat(), 'ref': { 'senate': item.senate, 'register': item.register, 'number': item.number, 'year': item.year, 'page': item.page, }, 'agenda': item.agenda.desc, 'parties': [p['name'] for p in item.parties.values()], 'files': files, }) dump(lst, response) return response
def useradd(request): LOGGER.debug( 'User add page accessed using method {}'.format(request.method), request, request.POST) err_message = None if request.method == 'GET': form = UserAddForm() else: form = UserAddForm(request.POST) if form.is_valid(): cld = form.cleaned_data user = User.objects.create_user(cld['username'], cld['email'], cld['password1']) if user: user.first_name = cld['first_name'] user.last_name = cld['last_name'] user.save() logout(request) LOGGER.info( 'New user "{0.username}" ({0.id:d}) created'.format(user), request) return redirect('useradded') LOGGER.error('Failed to create user', request) return error(request) # pragma: no cover else: LOGGER.debug('Invalid form', request) err_message = INERR if 'Duplicate username' in form['username'].errors.as_text(): err_message = 'Toto uživatelské jméno se již používá' LOGGER.debug('Duplicate user name', request) elif 'Wrong answer' in form['captcha'].errors.as_text(): err_message = 'Chybná odpověď na kontrolní otázku' LOGGER.debug('Wrong answer', request) elif 'Different passwords' in form['password2'].errors.as_text(): err_message = 'Rozdílná hesla' LOGGER.debug('Different passwords', request) else: err_message = 'Slabé heslo' LOGGER.debug('Weak password', request) return render( request, 'useradd.xhtml', { 'form': form, 'page_title': 'Registrace nového uživatele', 'err_message': err_message, })
def jsonlist(request): LOGGER.debug('JSON list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) res = Hearing.objects.filter(**par).order_by('time', 'pk').distinct() except: raise Http404 total = res.count() if total > EXLIM: return render( request, 'exlim.xhtml', {'app': APP, 'page_title': EXLIM_TITLE, 'limit': EXLIM, 'total': total, 'back': reverse('psj:mainpage')}) response = HttpResponse(content_type='application/json; charset=utf-8') response['Content-Disposition'] = 'attachment; filename=Jednani.json' lst = [] for item in res: court = { 'id': item.courtroom.court.id, 'name': item.courtroom.court.name, } lst.append({ 'court': court, 'courtroom': item.courtroom.desc, 'time': item.time.isoformat(), 'ref': { 'senate': item.senate, 'register': item.register, 'number': item.number, 'year': item.year, }, 'judge': item.judge.name, 'parties': [p['name'] for p in item.parties.values()], 'form': item.form.name, 'closed': item.closed, 'cancelled': item.cancelled, }) dump(lst, response) return response
def lostpw(request): LOGGER.debug('Lost password page accessed using method {}'.format(request.method), request, request.POST) err_message = None page_title = 'Ztracené heslo' if request.method == 'GET': form = LostPwForm() elif request.POST.get('back'): return redirect('login') else: form = LostPwForm(request.POST) if form.is_valid(): cld = form.cleaned_data users = User.objects.filter(username=cld['username']) if users.exists() and users[0].email: user = users[0] link = '{:032x}'.format(getrandbits(16 * 8)) PwResetLink(user_id=user.id, link=link).save() text = '''Vážený uživateli, někdo požádal o obnovení hesla pro Váš účet "{0}" na serveru {1} ({2}). Pokud skutečně chcete své heslo obnovit, použijte, prosím, následující jednorázový odkaz: {2}{3} V případě, že jste o obnovení hesla nežádali, můžete tuto zprávu ignorovat. Server {1} ({2}) '''.format(user.username, LOCAL_SUBDOMAIN, LOCAL_URL, reverse('resetpw', args=(link,))) send_mail('Link pro obnoveni hesla', text, (user.email,)) LOGGER.info('Password recovery link for user "{0.username}" ({0.id:d}) sent'.format(user), request) return redirect('/accounts/pwlinksent/') else: LOGGER.debug('Invalid form', request) err_message = 'Prosím, opravte označená pole ve formuláři' return render( request, 'lostpw.xhtml', {'form': form, 'page_title': page_title, 'err_message': err_message, })
def jsonlist(request): LOGGER.debug('JSON list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) res = Vec.objects.filter(**par).order_by('firstAction', 'rocnik', 'bc', 'idOsobyPuvodce').distinct() except: raise Http404 total = res.count() if total > EXLIM: return render( request, 'exlim.xhtml', { 'app': APP, 'page_title': EXLIM_TITLE, 'limit': EXLIM, 'total': total, 'back': reverse('pir:mainpage') }) response = HttpResponse(content_type='application/json; charset=utf-8') response['Content-Disposition'] = 'attachment; filename=Insolvence.json' lst = [] for item in res: par = { 'court': L2N[item.idOsobyPuvodce], 'ref': { 'court': L2S[item.idOsobyPuvodce], 'senate': item.senat, 'register': 'INS', 'number': item.bc, 'year': item.rocnik, }, 'state': S2D[item.druhStavRizeni.desc] if item.druhStavRizeni else '', 'debtors': json_addparties(getosoby(item, 'debtor')), 'trustees': json_addparties(getosoby(item, 'trustee')), } if 'creditors' in reqd: par['creditors'] = json_addparties( getosoby(item, 'motioner', 'creditor')) lst.append(par) dump(lst, response) return response
def csvlist(request): LOGGER.debug('CSV list accessed', request, request.GET) reqd = request.GET.copy() try: par = g2p(reqd) res = Decision.objects.filter(**par).order_by('date', 'pk').distinct() except: raise Http404 total = res.count() if total > EXLIM: return render( request, 'exlim.xhtml', {'app': APP, 'page_title': EXLIM_TITLE, 'limit': EXLIM, 'total': total, 'back': reverse('udn:mainpage')}) response = HttpResponse(content_type='text/csv; charset=utf-8') response['Content-Disposition'] = 'attachment; filename=Rozhodnuti.csv' writer = csvwriter(response) hdr = ( 'Soud', 'Datum', 'Číslo jednací', 'Oblast', 'Účastníci řízení', 'Zkrácené znění', 'Anonymisované znění', ) writer.writerow(hdr) for item in res: dat = ( SUPREME_ADMINISTRATIVE_COURT_NAME, '{:%d.%m.%Y}'.format(item.date), composeref(item.senate, item.register, item.number, item.year, item.page), item.agenda.desc, ';'.join([par['name'] for par in item.parties.values()]), join(REPO_PREFIX, item.filename), join(REPO_PREFIX, item.anonfilename) if item.anonfilename else '', ) writer.writerow(dat) return response
def home(request): LOGGER.debug('Home page accessed', request) grps = [ {'title': 'Jednoduché výpočty', 'apps': convappinfo(['sop', 'lht', 'cin', 'dvt', 'cnb', 'kos'])}, {'title': 'Komplexní výpočty', 'apps': convappinfo(['knr', 'hjp', 'hsp'])}, {'title': 'Prohlížení databasí', 'apps': convappinfo(['psj', 'uds', 'udn', 'pir'])}, {'title': 'Sledování', 'apps': convappinfo(['szr', 'sur', 'sir', 'dir'])}, ] return render( request, 'home.xhtml', {'page_title': 'Právnické výpočty', 'grps': grps, 'suppress_home': True})
def resetpw(request, link): LOGGER.debug('Password reset page accessed', request) PwResetLink.objects.filter(timestamp_add__lt=(datetime.now() - LINKLIFE)).delete() link = get_object_or_404(PwResetLink, link=link) user = link.user newpassword = '' for _ in range(PWLEN): newpassword += choice(PWCHARS) user.set_password(newpassword) user.save() link.delete() LOGGER.info('Password for user "{}" ({:d}) reset'.format(user.username, user.id), request) return render( request, 'pwreset.xhtml', {'page_title': 'Heslo bylo obnoveno', 'newpassword': newpassword, })