예제 #1
0
 def save(self, domain_override=None,
          subject_template_name='registration/password_reset_subject.txt',
          email_template_name='registration/password_reset_email.html',
          use_https=False, token_generator=default_token_generator,
          from_email=None, request=None):
     """
     Generates a one-use only link for resetting password and sends to the
     user.
     """
     from djangocg.core.mail import send_mail
     for user in self.users_cache:
         if not domain_override:
             current_site = get_current_site(request)
             site_name = current_site.name
             domain = current_site.domain
         else:
             site_name = domain = domain_override
         c = {
             'email': user.email,
             'domain': domain,
             'site_name': site_name,
             'uid': int_to_base36(user.id),
             'user': user,
             'token': token_generator.make_token(user),
             'protocol': use_https and 'https' or 'http',
         }
         subject = loader.render_to_string(subject_template_name, c)
         # Email subject *must not* contain newlines
         subject = ''.join(subject.splitlines())
         email = loader.render_to_string(email_template_name, c)
         send_mail(subject, email, from_email, [user.email])
예제 #2
0
    def test_error_message(self):
        with self.assertRaisesRegexp(AssertionError, r'^template_used/base\.html'):
            with self.assertTemplateUsed('template_used/base.html'):
                pass

        with self.assertRaisesRegexp(AssertionError, r'^template_used/base\.html'):
            with self.assertTemplateUsed(template_name='template_used/base.html'):
                pass

        with self.assertRaisesRegexp(AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'):
            with self.assertTemplateUsed('template_used/base.html'):
                render_to_string('template_used/alternative.html')
예제 #3
0
def render_to_response(*args, **kwargs):
    """
    Returns a HttpResponse whose content is filled with the result of calling
    djangocg.template.loader.render_to_string() with the passed arguments.
    """
    httpresponse_kwargs = {'content_type': kwargs.pop('mimetype', None)}
    return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
예제 #4
0
def render_to_kmz(*args, **kwargs):
    """
    Compresses the KML content and returns as KMZ (using the correct 
    MIME type).
    """
    return HttpResponse(compress_kml(loader.render_to_string(*args, **kwargs)),
        content_type='application/vnd.google-earth.kmz')
예제 #5
0
def sitemap(request, sitemaps, section=None):
    """
    This view generates a sitemap with additional geographic
    elements defined by Google.
    """
    maps, urls = [], []
    if section is not None:
        if section not in sitemaps:
            raise Http404(_("No sitemap available for section: %r") % section)
        maps.append(sitemaps[section])
    else:
        maps = list(six.itervalues(sitemaps))

    page = request.GET.get("p", 1)
    current_site = get_current_site(request)
    for site in maps:
        try:
            if callable(site):
                urls.extend(site().get_urls(page=page, site=current_site))
            else:
                urls.extend(site.get_urls(page=page, site=current_site))
        except EmptyPage:
            raise Http404(_("Page %s empty") % page)
        except PageNotAnInteger:
            raise Http404(_("No page '%s'") % page)
    xml = loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls})
    return HttpResponse(xml, content_type='application/xml')
예제 #6
0
    def test_failure(self):
        with self.assertRaises(TypeError):
            with self.assertTemplateUsed():
                pass

        with self.assertRaises(AssertionError):
            with self.assertTemplateUsed(''):
                pass

        with self.assertRaises(AssertionError):
            with self.assertTemplateUsed(''):
                render_to_string('template_used/base.html')

        with self.assertRaises(AssertionError):
            with self.assertTemplateUsed(template_name=''):
                pass

        with self.assertRaises(AssertionError):
            with self.assertTemplateUsed('template_used/base.html'):
                render_to_string('template_used/alternative.html')
예제 #7
0
 def render(self):
     """
     Generates the JavaScript for the collection of Google Maps in
     this set.
     """
     params = {'js_module' : self.js_module,
               'dom_ids' : self.dom_ids,
               'load_map_js' : self.load_map_js(),
               'icons' : self.icons,
               }
     params.update(self.extra_context)
     return render_to_string(self.template, params)
예제 #8
0
    def render(self, name, value, attrs=None):
        # Update the template parameters with any attributes passed in.
        if attrs: self.params.update(attrs)

        # Defaulting the WKT value to a blank string -- this
        # will be tested in the JavaScript and the appropriate
        # interface will be constructed.
        self.params['wkt'] = ''

        # If a string reaches here (via a validation error on another
        # field) then just reconstruct the Geometry.
        if isinstance(value, six.string_types):
            try:
                value = GEOSGeometry(value)
            except (GEOSException, ValueError):
                value = None

        if value and value.geom_type.upper() != self.geom_type:
            value = None

        # Constructing the dictionary of the map options.
        self.params['map_options'] = self.map_options()

        # Constructing the JavaScript module name using the name of
        # the GeometryField (passed in via the `attrs` keyword).
        # Use the 'name' attr for the field name (rather than 'field')
        self.params['name'] = name
        # note: we must switch out dashes for underscores since js
        # functions are created using the module variable
        js_safe_name = self.params['name'].replace('-','_')
        self.params['module'] = 'geodjango_%s' % js_safe_name

        if value:
            # Transforming the geometry to the projection used on the
            # OpenLayers map.
            srid = self.params['srid']
            if value.srid != srid:
                try:
                    ogr = value.ogr
                    ogr.transform(srid)
                    wkt = ogr.wkt
                except OGRException:
                    wkt = ''
            else:
                wkt = value.wkt

            # Setting the parameter WKT with that of the transformed
            # geometry.
            self.params['wkt'] = wkt

        return loader.render_to_string(self.template, self.params,
                                       context_instance=geo_context)
예제 #9
0
 def render(self, context):
     ctype, object_pk = self.get_target_ctype_pk(context)
     if object_pk:
         template_search_list = [
             "comments/%s/%s/form.html" % (ctype.app_label, ctype.model),
             "comments/%s/form.html" % ctype.app_label,
             "comments/form.html"
         ]
         context.push()
         formstr = render_to_string(template_search_list, {"form" : self.get_form(context)}, context)
         context.pop()
         return formstr
     else:
         return ''
예제 #10
0
 def render(self, context):
     ctype, object_pk = self.get_target_ctype_pk(context)
     if object_pk:
         template_search_list = [
             "comments/%s/%s/list.html" % (ctype.app_label, ctype.model),
             "comments/%s/list.html" % ctype.app_label,
             "comments/list.html"
         ]
         qs = self.get_query_set(context)
         context.push()
         liststr = render_to_string(template_search_list, {
             "comment_list" : self.get_context_value_from_queryset(context, qs)
         }, context)
         context.pop()
         return liststr
     else:
         return ''
예제 #11
0
 def render(self):
     """
     Generates the JavaScript necessary for displaying this Google Map.
     """
     params = {'calc_zoom' : self.calc_zoom,
               'center' : self.center,
               'dom_id' : self.dom_id,
               'js_module' : self.js_module,
               'kml_urls' : self.kml_urls,
               'zoom' : self.zoom,
               'polygons' : self.polygons,
               'polylines' : self.polylines,
               'icons': self.icons,
               'markers' : self.markers,
               }
     params.update(self.extra_context)
     return render_to_string(self.template, params)
예제 #12
0
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('djangocg.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')
예제 #13
0
def render(request, *args, **kwargs):
    """
    Returns a HttpResponse whose content is filled with the result of calling
    djangocg.template.loader.render_to_string() with the passed arguments.
    Uses a RequestContext by default.
    """
    httpresponse_kwargs = {
        'content_type': kwargs.pop('content_type', None),
        'status': kwargs.pop('status', None),
    }

    if 'context_instance' in kwargs:
        context_instance = kwargs.pop('context_instance')
        if kwargs.get('current_app', None):
            raise ValueError('If you provide a context_instance you must '
                             'set its current_app before calling render()')
    else:
        current_app = kwargs.pop('current_app', None)
        context_instance = RequestContext(request, current_app=current_app)

    kwargs['context_instance'] = context_instance

    return HttpResponse(loader.render_to_string(*args, **kwargs),
                        **httpresponse_kwargs)
예제 #14
0
 def test_basic(self):
     self.assertEqual(loader.render_to_string('test_context.html'), 'obj:')
예제 #15
0
    def test_usage(self):
        with self.assertTemplateUsed('template_used/base.html'):
            render_to_string('template_used/base.html')

        with self.assertTemplateUsed(template_name='template_used/base.html'):
            render_to_string('template_used/base.html')

        with self.assertTemplateUsed('template_used/base.html'):
            render_to_string('template_used/include.html')

        with self.assertTemplateUsed('template_used/base.html'):
            render_to_string('template_used/extends.html')

        with self.assertTemplateUsed('template_used/base.html'):
            render_to_string('template_used/base.html')
            render_to_string('template_used/base.html')
예제 #16
0
 def __init__(self, why):
     super(CommentPostBadRequest, self).__init__()
     if settings.DEBUG:
         self.content = render_to_string("comments/400-debug.html", {"why": why})
예제 #17
0
def render_to_kml(*args, **kwargs):
    "Renders the response as KML (using the correct MIME type)."
    return HttpResponse(loader.render_to_string(*args, **kwargs),
        content_type='application/vnd.google-earth.kml+xml')
예제 #18
0
def render_to_text(*args, **kwargs):
    "Renders the response using the MIME type for plain text."
    return HttpResponse(loader.render_to_string(*args, **kwargs),
        content_type='text/plain')
예제 #19
0
 def test_existing_context_kept_clean(self):
     context = Context({'obj': 'before'})
     output = loader.render_to_string('test_context.html', {'obj': 'after'},
                                      context_instance=context)
     self.assertEqual(output, 'obj:after')
     self.assertEqual(context['obj'], 'before')
예제 #20
0
 def test_basic_context(self):
     self.assertEqual(loader.render_to_string('test_context.html',
                                              {'obj': 'test'}), 'obj:test')
예제 #21
0
    def test_nested_usage(self):
        with self.assertTemplateUsed('template_used/base.html'):
            with self.assertTemplateUsed('template_used/include.html'):
                render_to_string('template_used/include.html')

        with self.assertTemplateUsed('template_used/extends.html'):
            with self.assertTemplateUsed('template_used/base.html'):
                render_to_string('template_used/extends.html')

        with self.assertTemplateUsed('template_used/base.html'):
            with self.assertTemplateUsed('template_used/alternative.html'):
                render_to_string('template_used/alternative.html')
            render_to_string('template_used/base.html')

        with self.assertTemplateUsed('template_used/base.html'):
            render_to_string('template_used/extends.html')
            with self.assertTemplateNotUsed('template_used/base.html'):
                render_to_string('template_used/alternative.html')
            render_to_string('template_used/base.html')