def ping_google(sitemap_url=None, ping_url=PING_URL): """ Alerts Google that the sitemap for the current site has been updated. If sitemap_url is provided, it should be an absolute path to the sitemap for this site -- e.g., '/sitemap.xml'. If sitemap_url is not provided, this function will attempt to deduce it by using urlresolvers.reverse(). """ if sitemap_url is None: try: # First, try to get the "index" sitemap URL. sitemap_url = urlresolvers.reverse( 'my_django.contrib.sitemaps.views.index') except urlresolvers.NoReverseMatch: try: # Next, try for the "global" sitemap URL. sitemap_url = urlresolvers.reverse( 'my_django.contrib.sitemaps.views.sitemap') except urlresolvers.NoReverseMatch: pass if sitemap_url is None: raise SitemapNotFound( "You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected." ) from my_django.contrib.sites.models import Site current_site = Site.objects.get_current() url = "http://%s%s" % (current_site.domain, sitemap_url) params = urllib.urlencode({'sitemap': url}) urllib.urlopen("%s?%s" % (ping_url, params))
def app_index(self, request, app_label, extra_context=None): user = request.user has_module_perms = user.has_module_perms(app_label) app_dict = {} for model, model_admin in self._registry.items(): if app_label == model._meta.app_label: if has_module_perms: perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): info = (app_label, model._meta.module_name) model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'perms': perms, } if perms.get('change', False): try: model_dict['admin_url'] = reverse( 'admin:%s_%s_changelist' % info, current_app=self.name) except NoReverseMatch: pass if perms.get('add', False): try: model_dict['add_url'] = reverse( 'admin:%s_%s_add' % info, current_app=self.name) except NoReverseMatch: pass if app_dict: app_dict['models'].append(model_dict), else: # First time around, now that we know there's # something to display, add in the necessary meta # information. app_dict = { 'name': app_label.title(), 'app_url': '', 'has_module_perms': has_module_perms, 'models': [model_dict], } if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) context = { 'title': _('%s administration') % capfirst(app_label), 'app_list': [app_dict], } context.update(extra_context or {}) return TemplateResponse( request, self.app_index_template or ['admin/%s/app_index.html' % app_label, 'admin/app_index.html'], context, current_app=self.name)
def inner(request, *args, **kwargs): if not self.has_permission(request): if request.path == reverse('admin:logout', current_app=self.name): index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) return self.login(request) return view(request, *args, **kwargs)
def test_form_jump(self): response = self.client.get( reverse(self.wizard_urlname, kwargs={'step': 'form1'})) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['wizard']['steps'].current, 'form1') response = self.client.get( reverse(self.wizard_urlname, kwargs={'step': 'form3'})) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['wizard']['steps'].current, 'form3')
def post_form(context, form, forum, topic=None): if topic: action = reverse('cicero.views.topic', args=[forum.slug, topic.id]) else: action = reverse('cicero.views.forum', args=[forum.slug]) return { 'form': form, 'topic': topic, 'action': action, 'user': context['user'], 'profile': context['profile'], }
def article_delete(request, id): article = get_object_or_404(Article, pk=id) if not request.user.cicero_profile.can_change_article(article): return HttpResponseForbidden('Нет прав для удаления') article.deleted = datetime.now() article.save() caching.invalidate_by_article(article.topic.forum.slug, article.topic.id) if article.topic.article_set.count(): return HttpResponseRedirect( reverse(topic, args=(article.topic.forum.slug, article.topic.id))) else: article.topic.deleted = datetime.now() article.topic.save() return HttpResponseRedirect( reverse(forum, args=(article.topic.forum.slug, )))
def test_form_reset(self): response = self.client.post( reverse(self.wizard_urlname, kwargs={'step': 'form1'}), self.wizard_step_data[0]) response = self.client.get(response['Location']) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['wizard']['steps'].current, 'form2') response = self.client.get('%s?reset=1' % reverse('%s_start' % self.wizard_urlname)) self.assertEqual(response.status_code, 302) response = self.client.get(response['Location']) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['wizard']['steps'].current, 'form1')
def get_content_object_url(self): """ Get a URL suitable for redirecting to the content object. """ return urlresolvers.reverse("comments-url-redirect", args=(self.content_type_id, self.object_pk))
def render(self, name, value, attrs=None): rel_to = self.rel.to if attrs is None: attrs = {} extra = [] if rel_to in self.admin_site._registry: # The related object is registered with the same AdminSite related_url = reverse( 'admin:%s_%s_changelist' % (rel_to._meta.app_label, rel_to._meta.module_name), current_app=self.admin_site.name) params = self.url_parameters() if params: url = u'?' + u'&'.join( [u'%s=%s' % (k, v) for k, v in params.items()]) else: url = u'' if "class" not in attrs: attrs[ 'class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook. # TODO: "lookup_id_" is hard-coded here. This should instead use # the correct API to determine the ID dynamically. extra.append( u'<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % (related_url, url, name)) extra.append( u'<img src="%s" width="16" height="16" alt="%s" /></a>' % (static('admin/img/selector-search.gif'), _('Lookup'))) output = [ super(ForeignKeyRawIdWidget, self).render(name, value, attrs) ] + extra if value: output.append(self.label_for_value(value)) return mark_safe(u''.join(output))
def view_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) if settings.ADMIN_FOR: settings_modules = [import_module(m) for m in settings.ADMIN_FOR] else: settings_modules = [settings] views = [] for settings_mod in settings_modules: urlconf = import_module(settings_mod.ROOT_URLCONF) view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns) if Site._meta.installed: site_obj = Site.objects.get(pk=settings_mod.SITE_ID) else: site_obj = GenericSite() for (func, regex) in view_functions: views.append({ 'full_name': '%s.%s' % (func.__module__, getattr(func, '__name__', func.__class__.__name__)), 'site_id': settings_mod.SITE_ID, 'site': site_obj, 'url': simplify_regex(regex), }) return render_to_response('admin_doc/view_index.html', { 'root_path': urlresolvers.reverse('admin:index'), 'views': views }, context_instance=RequestContext(request))
def template_filter_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) load_all_installed_template_libraries() filters = [] app_libs = template.libraries.items() builtin_libs = [(None, lib) for lib in template.builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring(filter_func.__doc__) if title: title = utils.parse_rst(title, 'filter', _('filter:') + filter_name) if body: body = utils.parse_rst(body, 'filter', _('filter:') + filter_name) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'filter', _('filter:') + filter_name) if library in template.builtins: tag_library = None else: tag_library = module_name.split('.')[-1] filters.append({ 'name': filter_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) return render_to_response('admin_doc/template_filter_index.html', { 'root_path': urlresolvers.reverse('admin:index'), 'filters': filters }, context_instance=RequestContext(request))
def index(request, sitemaps): """ This view generates a sitemap index that uses the proper view for resolving geographic section sitemap URLs. """ current_site = get_current_site(request) sites = [] protocol = request.is_secure() and 'https' or 'http' for section, site in sitemaps.items(): if callable(site): pages = site().paginator.num_pages else: pages = site.paginator.num_pages sitemap_url = urlresolvers.reverse( 'my_django.contrib.gis.sitemaps.views.sitemap', kwargs={'section': section}) sites.append('%s://%s%s' % (protocol, current_site.domain, sitemap_url)) if pages > 1: for page in range(2, pages + 1): sites.append( '%s://%s%s?p=%s' % (protocol, current_site.domain, sitemap_url, page)) xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites}) return HttpResponse(xml, content_type='application/xml')
def password_change(request, template_name='registration/password_change_form.html', post_change_redirect=None, password_change_form=PasswordChangeForm, current_app=None, extra_context=None): if post_change_redirect is None: post_change_redirect = reverse( 'my_django.contrib.auth.views.password_change_done') if request.method == "POST": form = password_change_form(user=request.user, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(post_change_redirect) else: form = password_change_form(user=request.user) context = { 'form': form, } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context, current_app=current_app)
def add_template_response(request, message_type): for msg in request.POST.getlist('messages'): getattr(messages, message_type)(request, msg) show_url = reverse( 'my_django.contrib.messages.tests.urls.show_template_response') return HttpResponseRedirect(show_url)
def location(self, obj): return urlresolvers.reverse('my_django.contrib.gis.sitemaps.views.%s' % self.geo_format, kwargs={ 'label': obj[0], 'model': obj[1], 'field_name': obj[2], })
def model_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) m_list = [m._meta for m in models.get_models()] return render_to_response('admin_doc/model_index.html', { 'root_path': urlresolvers.reverse('admin:index'), 'models': m_list }, context_instance=RequestContext(request))
def test_repository_in_db_but_not_in_FS(self): """ test thats passing an unknown repository returns a 404 page """ response = self.client.get(reverse('hg-repo-action', None, None, { 'name': 'foo', 'action': 'changesets' }), {}, follow=True, **{'HTTP_HOST': 'localhost:8000'}) self.failUnlessEqual(response.status_code, 404)
def test_commands_unknown_command(self): ''' pass an unknown command ''' response = self.client.get(reverse('hg-repo', None, None, {'name': 'django'}), {'cmd': 'foo'}, follow=False, **{'HTTP_HOST': 'localhost:8000'}) self.failUnlessEqual(response.status_code, 200)
def test_commands_known_command_but_no_required_params(self): ''' pass a known command ''' response = self.client.get(reverse('hg-repo', None, None, {'name': 'django'}), {'cmd': 'between'}, follow=False, **{'HTTP_HOST': 'localhost:8000'}) self.failUnlessEqual(response.status_code, 200)
def password_change(self, request): """ Handles the "change password" task -- both form display and validation. """ from my_django.contrib.auth.views import password_change url = reverse('admin:password_change_done', current_app=self.name) defaults = {'current_app': self.name, 'post_change_redirect': url} if self.password_change_template is not None: defaults['template_name'] = self.password_change_template return password_change(request, **defaults)
def get_form_target(): """ Returns the target URL for the comment form submission view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr( get_comment_app(), "get_form_target"): return get_comment_app().get_form_target() else: return urlresolvers.reverse( "my_django.contrib.comments.views.comments.post_comment")
def test_repository_in_db_but_not_in_FS(self): """ test thats passing an unknown repository returns a 404 page """ response = self.client.get( reverse('hg-repo', None, None, {'name': 'bar'}), { 'cmd': 'between', 'pairs': '0000000000000000000000000000000000000000-0000000000000000000000000000000000000000' }) self.failUnlessEqual(response.status_code, 404)
def test_manipulated_data(self): response = self.client.get( reverse(self.wizard_urlname, kwargs={'step': 'form1'})) self.assertEqual(response.status_code, 200) response = self.client.post( reverse( self.wizard_urlname, kwargs={'step': response.context['wizard']['steps'].current}), self.wizard_step_data[0]) response = self.client.get(response['Location']) self.assertEqual(response.status_code, 200) post_data = self.wizard_step_data[1] post_data['form2-file1'] = open(__file__) response = self.client.post( reverse( self.wizard_urlname, kwargs={'step': response.context['wizard']['steps'].current}), post_data) response = self.client.get(response['Location']) self.assertEqual(response.status_code, 200) response = self.client.post( reverse( self.wizard_urlname, kwargs={'step': response.context['wizard']['steps'].current}), self.wizard_step_data[2]) loc = response['Location'] response = self.client.get(loc) self.assertEqual(response.status_code, 200, loc) self.client.cookies.pop('sessionid', None) self.client.cookies.pop('wizard_cookie_contact_wizard', None) response = self.client.post( reverse( self.wizard_urlname, kwargs={'step': response.context['wizard']['steps'].current}), self.wizard_step_data[3]) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['wizard']['steps'].current, 'form1')
def __log(request, repo, rev, path): """ display the file log ``repo`` the repository ``rev`` the revision in the changesets history ``path`` the file for which we want the log """ ctx = repo.get_context().repository[rev] fctx = ctx.filectx(path) filelog = [] for fl in fctx.filelog(): l = fctx.filectx(fl) filelog.append({ 'user': l.user(), "time": datetime.fromtimestamp(l.date()[0]).time(), "date": date.fromtimestamp(l.date()[0]), 'description': l.description(), 'branch': l.branch(), 'hash': str(l)[str(l).rfind('@') + 1:], 'filesize': l.size(), 'rev': l.rev(), 'files_count': len(ctx.files()) }) filelog.reverse() from_rev = request.GET.get('from_rev', '') to_rev = request.GET.get('to_rev', '') form = HgDiffForm(filelog, {'from_rev': from_rev, 'to_rev': to_rev}) if '' != from_rev and '' != to_rev and form.is_valid(): return HttpResponseRedirect( reverse('hg-repo-action-rev-path', kwargs={ 'name': repo.name, 'action': 'changesets', 'rev': from_rev, 'path': path }) + '?from_rev=' + str(from_rev) + '&to_rev=' + str(to_rev)) return render_to_response('django_hg/log.html', { 'file': path, 'filelog': filelog, 'form': form, 'from_rev': from_rev, 'path': path, 'repo': repo, 'rev': rev, 'to_rev': to_rev, 'groups': _get_left_side_cont(), }, context_instance=RequestContext(request))
def article_spam(request, id): if not request.user.cicero_profile.moderator: return HttpResponseForbidden('Нет прав определять спам') article = get_object_or_404(Article, pk=id) if not article.from_guest(): pass # scipio_profile = article.author.user.scipio_profile # if scipio_profile.spamer is None: # scipio_profile.spamer = True # scipio_profile.save() #antispam.conveyor.submit_spam(article=article) slug, topic_id = article.topic.forum.slug, article.topic.id article.delete() caching.invalidate_by_article(slug, topic_id) if Topic.objects.filter(pk=topic_id).count(): return HttpResponseRedirect(reverse(topic, args=(slug, topic_id))) else: return HttpResponseRedirect(reverse(forum, args=(slug, )))
def test_initial_call_with_params(self): get_params = {'getvar1': 'getval1', 'getvar2': 'getval2'} response = self.client.get(reverse('%s_start' % self.wizard_urlname), get_params) self.assertEqual(response.status_code, 302) # Test for proper redirect GET parameters location = response['Location'] self.assertNotEqual(location.find('?'), -1) querydict = QueryDict(location[location.find('?') + 1:]) self.assertEqual(dict(querydict.items()), get_params)
def articles_list(request, *args, **kwargs): if 'application/xrds+xml' in request.META.get('HTTP_ACCEPT', ''): return render_to_response(request, 'cicero/yadis.xml', { 'return_to': absolute_url(reverse(auth)), }, mimetype='application/xrds+xml') kwargs['extra_context'] = {'groups': _get_left_side_cont()} return object_list(request, *args, **kwargs)
def test_changesets_anonymous_access(self): """ the repository is accessible without authentication""" response = self.client.get(reverse('hg-repo-action', None, None, { 'name': 'django', 'action': 'changesets' }), {}, follow=True, **{'HTTP_HOST': 'localhost:8000'}) self.failUnlessEqual(response.status_code, 200) ctx = response.context[0] self.failUnlessEqual(ctx['repo'].anonymous_access, True)
def get_approve_url(comment): """ Get the URL for the "approve this comment from moderation" view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr( get_comment_app(), "get_approve_url"): return get_comment_app().get_approve_url(comment) else: return urlresolvers.reverse( "my_django.contrib.comments.views.moderation.approve", args=(comment.id, ))
def test_unknown_repository_returns_404(self): """ test thats passing an unknown repository returns a 404 page """ response = self.client.get(reverse( 'hg-repo-action-rev-path', None, None, { 'name': 'foo', 'action': 'changesets', 'rev': 'tip', 'path': 'foo/bar/baz' }), {}, follow=True, **{'HTTP_HOST': 'localhost:8000'}) self.failUnlessEqual(response.status_code, 404)