def make_search_breadcumbs(attrs, values): attrs_values = get_pairs(attrs, values) search_breadcumbs = [] search_url = urlresolvers.reverse('ssearch:frontend:index') attrs_prepare = [] values_prepare = [] for attr, value in attrs_values: attr_url_part = u'attr=' + attr value_url_part = u'q=' + urlquote(value) search_breadcumbs.append({ 'attr': attr, 'title': get_attr_title(attr), 'href': search_url + u'?' + u'&'.join(attrs_prepare) + u'&' + attr_url_part + u'&' + u'&'.join( values_prepare) + u'&' + value_url_part, 'value': get_attr_value_title(attr, value) }) attrs_prepare.append(attr_url_part) values_prepare.append(value_url_part) return search_breadcumbs
def test_show_index_page(self): url = '%s%s' % (self.live_server_url, urlresolvers.reverse('index')) self.browser.visit(url) self.assertEquals( self.browser.find_by_id('score1').first.text, u'0.00%') self.assertEquals( self.browser.find_by_id('score2').first.text, u'0.00%')
def edit(request, template_name): admin_edit = True person = Person.objects.get(pk=1) img = person.img form = PersonEditForm(instance=person) if request.method=="POST": data = request.POST.copy() form = PersonEditForm(data,request.FILES) if form.is_valid(): person.name = form.cleaned_data['name'] person.last_name = form.cleaned_data['last_name'] person.email = form.cleaned_data['email'] person.jabber = form.cleaned_data['jabber'] person.skype = form.cleaned_data['skype'] person.bio = form.cleaned_data['bio'] person.other = form.cleaned_data['other'] person.date_of_birth = form.cleaned_data['date_of_birth'] if not request.FILES and data.has_key("img-clear"): person.img = None elif not request.FILES and not data.has_key("img-clear"): person.img = img else: person.img = request.FILES['img'] person.save() return HttpResponseRedirect(urlresolvers.reverse("welcome")) return render_to_response(template_name,{'form':form, 'admin_edit':admin_edit}, context_instance=RequestContext(request))
def make_search_breadcumbs(attrs_values): """ Создание целопчки поисковых фильтров :param attrs_values: :return: """ search_breadcumbs = [] search_url = urlresolvers.reverse('search:frontend:index') attrs_prepare = [] values_prepare = [] for item in attrs_values: attr_url_part = u'attr=' + getattr(item, 'attr') value_url_part = u'value=' + urlunquote_plus(getattr(item, 'value')) search_breadcumbs.append({ 'attr': getattr(item, 'attr'), 'title': getattr(item, 'title', getattr(item, 'attr')), 'href': search_url + u'?' + u'&'.join(attrs_prepare) + u'&' + attr_url_part + u'&' + u'&'.join( values_prepare) + u'&' + value_url_part, 'value': titles.get_attr_value_title(getattr(item, 'attr'), getattr(item, 'value')), }) attrs_prepare.append(attr_url_part) values_prepare.append(value_url_part) return search_breadcumbs
def addGrupo(request): form = GruposForm(request.POST or None) #table = permissionTable(Permission.objects.all()) permisos = Permission.objects.all() #RequestConfig(request).configure(table) template='autorizaciones/addGrupo.html' if request.method == 'POST': checks = request.POST.getlist('duallistbox_permisos') ids = map(int, checks) permisosSeleccionados=Permission.objects.filter(pk__in=ids) if form.is_valid(): grupo=form.save(commit=False) grupo.save() for permiso in permisosSeleccionados: grupo.permissions.add(permiso) grupo.save() success_message = "El Grupo "+str(grupo.name)+" fue creado con exito" messages.add_message(request, messages.SUCCESS, success_message) url = urlresolvers.reverse('autorizaciones:det_grupo', args=(grupo.id,)) return HttpResponseRedirect(url) else: for id_permiso_seleccionado in ids: for permiso in permisos: if id_permiso_seleccionado==permiso.id: permiso.seleccionado='selected="selected"' break return render_to_response(template, {"form": form, "permisos":permisos}, context_instance=RequestContext(request, locals()))
def question_answer(request, id): manager = QuestionManager.get_manager(request.user) if not manager: return HttpResponse(u'Вы не можете обрабатывать вопросы') question = get_object_or_404(Question, id=id) if question.is_ready(): return HttpResponse(u'Ответ на вопрос уже дан.') if request.method == 'POST': form = AnswerQuestionForm(request.POST, instance=question) if form.is_valid(): question = form.save(commit=False) if question.is_new(): question.take_to_process(manager, commit=False) question.close_process() if question.email: domain = settings.SITE_DOMAIN from_mail = settings.DEFAULT_FROM_EMAIL send_mail(u"Спроси библиотекаря", u'Ваш вопрос был обработан. Вы можете посмотреть ответ по адресу http://%s%s' % (domain, urlresolvers.reverse('ask_librarian:frontend:detail', args=(question.id,))), from_mail, [question.email], # fail_silently=True ) return redirect('ask_librarian:administration:question_detail', id=id) else: form = AnswerQuestionForm(instance=question) return render(request, 'ask_librarian/administration/question_answer.html', { 'question': question, 'form': form })
def test_vote(self): Candidate.objects.create(id=1, score=5) url = '%s%s' % (self.live_server_url, urlresolvers.reverse('vote', args='1')) self.browser.visit(url) self.assertEquals( self.browser.find_by_id('score1').first.text, u'100.00%') self.assertEquals( self.browser.find_by_id('score2').first.text, u'0.00%')
def delete_order(request, order_id): order_manager = OrderManager(settings.ORDERS['db_catalog'], settings.ORDERS['rdx_path']) transactions = order_manager.get_order(order_id=order_id.encode('utf-8'), user_id=unicode(request.user.id)) if len(transactions): if check_for_can_delete(transactions[0]): pass order_manager.delete_order(order_id=order_id.encode('utf-8'), user_id=unicode(request.user.id)) return redirect(urlresolvers.reverse('orders:frontend:index'))
def create_document_info(rbclient, code, fd, token1): edoc_path = urlresolvers.reverse('rbooks:frontend:edoc') key_path = urlresolvers.reverse('rbooks:frontend:key') ver = md5(fd).hexdigest() li = rbooks_client.LinkInfo( file='source.xml', url= edoc_path + '?code=%s&part=part0.zip&version=%s' % (code, ver) ) file_url = edoc_path + '?code=%s&part={part}&version=%s' % ( code, ver ) pi = rbooks_client.PermissionsInfo(True, True) token2 = '1234567890' provider_key1 = rbclient.get_public_key1_string() key_url = key_path + '?code={code}&dh={dh}&sign={sign}' #di = rbooks_client.DownloadInfo('gergerg', 'rferf', 1212, 'wefwef') doc_info = rbooks_client.DocumentInfo( link_info=li, file_url=file_url, permissions_info=pi, token1=token1, token2=token2, provider_key1=provider_key1, key_url=key_url, print_url='111', downloads=[] ) return etree.tostring(doc_info.to_xml_element(), encoding='utf-8', xml_declaration=True)
def send_email_to_user(prolongation): message = u"""\ Состояние вашей заявки на продление %s в библиотеке %s изменилось (статус: %s).\ Более подробную информацию о заявке Вы можете посмотреть пройдя по адресу %s.\ """ % ( prolongation.doc_title, prolongation.manage_library.name, prolongation.get_status_display(), settings.SITE_URL + urlresolvers.reverse("prolongation_prolongation_user_detail", args=[prolongation.id]), ) send_mail( u"Изменение статуса заявки на электронное продление издания", message, "*****@*****.**", [prolongation.email] ) pass
def order_info(request, template_name="registration/order_info.html"): if request.method == "POST": postdata = request.POST.copy() form = UserProfileForm(postdata) if form.is_valid(): profile.set(request) url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url) else: user_profile = profile.retrieve(request) form = UserProfileForm(instance=user_profile) page_title = _("Edit order information") context = locals() context.update(csrf(request)) return render_to_resonse(template_name, context, context_instance=RequestContext(request))
def ask(request): QuestionForm = get_question_form(not request.user.is_authenticated()) if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) if request.user.is_authenticated(): question.user = request.user question.save() ask_librarian_settings = getattr(settings, 'ASK_LIBRARIAN', {}) main_dispatcher = ask_librarian_settings.get( 'MAIN_DISPATCHER', None) if main_dispatcher: fail_silently = True if settings.DEBUG: fail_silently = False domain = getattr(settings, 'SITE_DOMAIN', 'localhost') from_mail = settings.DEFAULT_FROM_EMAIL send_mail( u"Спроси библиографа. Новый вопрос.", u'Поступил новый вопрос. Информация находится по адресу http://%s%s' % (domain, urlresolvers.reverse( 'ask_librarian:administration:question_detail', args=(question.id, ))), from_mail, [main_dispatcher], fail_silently=fail_silently) return render(request, 'ask_librarian/frontend/thanks.html', { 'question': question, }) else: if request.user.is_authenticated(): form = QuestionForm( initial={ 'fio': request.user.last_name + u' ' + request.user.first_name, 'email': request.user.email, }) else: form = QuestionForm() return render(request, 'ask_librarian/frontend/ask.html', {'form': form})
def edit_page(request, page_url): """This view will display a form to edit the body of a WikiPage instance. If page_url does not match any of the stored WikiPage url then a new instance will be created. Attributes: request: HttpRequest object representing the current request object. page_url: WikiPage url. Returns: response: HttpResponse object used to render index page using wikipage_edit.html page. """ try: # Trying to fetch wiki page given its page url. wikipage = WikiPage.objects.get(url=page_url) except exceptions.ObjectDoesNotExist: # Create page automatically if this one does not exist. wikipage = WikiPage.objects.create(url=page_url) # Show WikiPage edit form. if request.method == 'GET': wikipage_form = WikiPageForm(initial={'body': wikipage.body}) # Save WikiPage form changes. elif request.method == 'POST': wikipage_form = WikiPageForm(request.POST) if wikipage_form.is_valid(): wikipage.body = wikipage_form.cleaned_data['body'] wikipage.save() Changelog.objects.create( wikipage=wikipage, comments=wikipage_form.cleaned_data['comments']) # Redirect response to view_page view. return HttpResponseRedirect( urlresolvers.reverse('view_page', args=[page_url])) return render(request, 'wikipage_edit.html', {'title': wikipage.title, 'wikiform': wikipage_form, 'wikipage': wikipage})
def zorder(request, library_id): record_id = request.GET.get('id', None) if not record_id: raise Http404() library = get_object_or_404(Library, id=library_id) # проверяем, привязан ли zgate к библиотеке чтобы можно было перенаправить на него try: zcatalog = ZCatalog.objects.get(latin_title=library.code) except ZCatalog.DoesNotExist: return HttpResponse(u'Библиотека не может принимать электронные заказы') # ищем связь пользователя с библиотекой, чтобы автоматически авторизовать для заказа # иначе перенаправляем для установления связи try: lib_reader = LibReader.objects.get(user=request.user, library=library) except LibReader.DoesNotExist: back = request.get_full_path() return redirect(urlresolvers.reverse('urt:frontend:auth', args=[library_id]) + '?back=' + back) (zgate_form, cookies) = zworker.get_zgate_form( zgate_url=zcatalog.url, xml=zcatalog.xml, xsl=zcatalog.xsl, cookies=request.COOKIES, username=lib_reader.lib_login, password=lib_reader.lib_password, ) session_id = zworker.get_zgate_session_id(zgate_form) form_params = zworker.get_form_dict(zgate_form) del (form_params['scan']) # удаляем, иначе происходит сканирование :-) form_params['use_1'] = '12:1.2.840.10003.3.1' form_params['term_1'] = record_id (result, cookies) = zworker.request(zcatalog.url, data=form_params, cookies=cookies) # анализируем полученный html на содержание текса с идентификатором записи - значит нашли if result.decode('utf-8').find(u'id="%s' % (record_id,)) >= 0: # link = reverse('zgate_index', args=(catalog.id,)) + '?zstate=preorder+%s+1+default+1+1.2.840.10003.5.28+rus' % session_id link = zcatalog.url + '?preorder+%s+1+default+1+1.2.840.10003.5.28+rus' % session_id resp = redirect(link) set_cookies_to_response(cookies, resp, domain='.kitap.tatar.ru') return resp return HttpResponse(u'Zgate order')
def ask(request): QuestionForm = get_question_form(not request.user.is_authenticated()) if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) if request.user.is_authenticated(): question.user = request.user question.save() ask_librarian_settings = getattr(settings, 'ASK_LIBRARIAN', {}) main_dispatcher = ask_librarian_settings.get('MAIN_DISPATCHER', None) if main_dispatcher: fail_silently = True if settings.DEBUG: fail_silently = False domain = getattr(settings, 'SITE_DOMAIN', 'localhost') from_mail = settings.DEFAULT_FROM_EMAIL send_mail(u"Спроси библиографа. Новый вопрос.", u'Поступил новый вопрос. Информация находится по адресу http://%s%s' % (domain, urlresolvers.reverse('ask_librarian:administration:question_detail', args=(question.id,))), from_mail, [main_dispatcher], fail_silently=fail_silently ) return render(request, 'ask_librarian/frontend/thanks.html', { 'question': question, }) else: if request.user.is_authenticated(): form = QuestionForm( initial={ 'fio': request.user.last_name + u' ' + request.user.first_name, 'email': request.user.email, } ) else: form = QuestionForm() return render(request, 'ask_librarian/frontend/ask.html', { 'form': form })
def changelog(request, page_url=None): """This view display a change log for a given WikiPage or all change logs in djwiki. Attributes: request: HttpRequest object representing the current request object. page_url: WikiPage url, maybe None. Returns: response: HttpResponse object used to render index page using changelog.html page. """ title = 'Global History' page_number = request.GET.get('page', 1) # If page_url is present then Changelog entries for that WikiPage should be # displayed. if page_url: try: # Trying to fetch wiki page given its page url. wikipage = WikiPage.objects.get(url=page_url) title = '"%s" History' % wikipage.title except exceptions.ObjectDoesNotExist: # Redirect response to wikipage edit view. return HttpResponseRedirect( urlresolvers.reverse('edit_page', args=[page_url])) else: # Filter ChangeLog entries for a WikiPage instance. changelogs = utils.get_view_paginator( Changelog, page_number, filters={'wikipage': wikipage}) else: # Return all ChangeLog instances in djwiki. changelogs = utils.get_view_paginator(Changelog, page_number) return render(request, 'changelog.html', {'title': title, 'page_url': page_url, 'changelogs': changelogs})
def updGrupo(request, pk): grupo = get_object_or_404(Group, pk=pk) form = GruposForm(request.POST or None, instance=grupo) permisosActuales = grupo.permissions.get_queryset() permisos = Permission.objects.all() for permiso_seleccionado in permisosActuales: for permiso in permisos: if permiso_seleccionado.id==permiso.id: permiso.seleccionado='selected="selected"' break if request.method == 'POST': checks = request.POST.getlist('duallistbox_permisos') ids = map(int, checks) permisosSeleccionados=Permission.objects.filter(pk__in=ids) if form.is_valid(): conjActuales= set(permisosActuales) conjSeleccionados = set(permisosSeleccionados) grupo=form.save(commit=False) grupo.save() aBorrar= conjActuales - conjSeleccionados for permiso in aBorrar: grupo.permissions.remove(permiso) for permiso in permisosSeleccionados: grupo.permissions.add(permiso) grupo.save() success_message = "El Grupo "+str(grupo.name)+" fue creado con exito" messages.add_message(request, messages.SUCCESS, success_message) url = urlresolvers.reverse('autorizaciones:det_grupo', args=(grupo.id,)) return HttpResponseRedirect(url) else: for id_permiso_seleccionado in ids: for permiso in permisos: if id_permiso_seleccionado==permiso.id: permiso.seleccionado='selected="selected"' break template='autorizaciones/updGrupo.html' return render_to_response(template, {"form": form, "permisos": permisos}, context_instance=RequestContext(request, locals()))
def addUsuario(request): if request.method == 'POST': form = usuarioForm(request.POST or None, request.FILES) if form.is_valid(): usuario=form.save() userPerfil=perfil.objects.get(user_id=usuario.id) if request.FILES: userPerfil.avatar=request.FILES['avatar'] userPerfil.save() # else: # userPerfil.avatar="avatar_user/default.png" # userPerfil.save() success_message = "El Usuario "+str(usuario.username)+" creado con exito" messages.add_message(request, messages.SUCCESS, success_message) url = urlresolvers.reverse('autorizaciones:det_usuario', args=(usuario.id,)) return HttpResponseRedirect(url) else: pass else: form = usuarioForm() template='autorizaciones/addUsuario.html' return render_to_response(template, {"form": form}, context_instance=RequestContext(request, locals()))
def register(request, template_name="registration/register.html"): if request.method == 'POST': postdata = request.POST.copy() form = RegistrationForm(postdata) if form.is_valid(): user = form.save(commit=False) user.email = postdata.get('email', '') user.save() username = postdata.get('username', '') password = postdata.get('password1', '') from django.contrib.auth import login, authenticate new_user = authenticate(username=username, password=password) if new_user and new_user.is_active: login(request, new_user) url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url) else: form = RegistrationForm() page_title = _("User registration") context = locals() context.update(csrf(request)) return render_to_response(template_name, context, context_instance=RequestContext(request))
def updUsuario(request, pk): user = get_object_or_404(User, pk=pk) form = updUsuarioForm(request.POST or None, request.FILES or None, instance=user) #form.fields['username'].widget.attrs['readonly'] = True if request.method == 'POST': if form.is_valid(): usuario = form.save() try: userPerfil = perfil.objects.get(user_id=usuario.id) except: userPerfil=perfil() userPerfil.user=usuario userPerfil.save() if request.FILES: userPerfil.avatar=request.FILES['avatar'] userPerfil.save() url = urlresolvers.reverse('autorizaciones:det_usuario', args=(pk,)) return HttpResponseRedirect(url) else: pass template='autorizaciones/updUsuario.html' return render_to_response(template, {"form": form}, context_instance=RequestContext(request, locals()))
def get_absolute_url(self): return urlresolvers.reverse('newinlib:frontend:show', args=[self.id])
def vote(request, id): candidate = get_object_or_404(Candidate, id=id) candidate.score += 1 candidate.save() return redirect(urlresolvers.reverse('index'))
def get_absolute_url(self): return urlresolvers.reverse('participant_news:frontend:show', args=[self.library.code, self.id])
def test_should_show_404_if_candidate_doesnt_exists(self): url = '%s%s' % (self.live_server_url, urlresolvers.reverse('vote', args='9')) self.assertRaises(HttpResponseError, self.browser.visit, url)
def get_absolute_url(self): return urlresolvers.reverse('ssearch:frontend:detail', args=[self.id])
def logout_page(request): logout(request) return HttpResponseRedirect(urlresolvers.reverse('welcome'))