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 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 my_django.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])
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(_(u"No sitemap available for section: %r") % section) maps.append(sitemaps[section]) else: maps = sitemaps.values() 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(_(u"Page %s empty") % page) except PageNotAnInteger: raise Http404(_(u"No page '%s'") % page) xml = smart_str( loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls})) return HttpResponse(xml, content_type='application/xml')
def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None): """ Logs out the user and displays 'You are logged out' message. """ auth_logout(request) redirect_to = request.REQUEST.get(redirect_field_name, '') if redirect_to: netloc = urlparse.urlparse(redirect_to)[1] # Security check -- don't allow redirection to a different host. if not (netloc and netloc != request.get_host()): return HttpResponseRedirect(redirect_to) if next_page is None: current_site = get_current_site(request) context = { 'site': current_site, 'site_name': current_site.name, 'title': _('Logged out') } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context, current_app=current_app) else: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page or request.path)
def sitemap(request, sitemaps, section=None, template_name='sitemap.xml', mimetype='application/xml'): req_protocol = 'https' if request.is_secure() else 'http' req_site = get_current_site(request) if section is not None: if section not in sitemaps: raise Http404("No sitemap available for section: %r" % section) maps = [sitemaps[section]] else: maps = sitemaps.values() page = request.GET.get("p", 1) urls = [] for site in maps: try: if callable(site): site = site() urls.extend( site.get_urls(page=page, site=req_site, protocol=req_protocol)) except EmptyPage: raise Http404("Page %s empty" % page) except PageNotAnInteger: raise Http404("No page '%s'" % page) return TemplateResponse(request, template_name, {'urlset': urls}, content_type=mimetype)
def test_get_current_site(self): # Test that the correct Site object is returned request = HttpRequest() request.META = { "SERVER_NAME": "example.com", "SERVER_PORT": "80", } site = get_current_site(request) self.assertTrue(isinstance(site, Site)) self.assertEqual(site.id, settings.SITE_ID) # Test that an exception is raised if the sites framework is installed # but there is no matching Site site.delete() self.assertRaises(ObjectDoesNotExist, get_current_site, request) # A RequestSite is returned if the sites framework is not installed Site._meta.installed = False site = get_current_site(request) self.assertTrue(isinstance(site, RequestSite)) self.assertEqual(site.name, u"example.com")
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ redirect_to = request.REQUEST.get(redirect_field_name, '') if request.method == "POST": form = authentication_form(data=request.POST) if form.is_valid(): netloc = urlparse.urlparse(redirect_to)[1] # Use default setting if redirect_to is empty if not redirect_to: redirect_to = settings.LOGIN_REDIRECT_URL # Heavier security check -- don't allow redirection to a different # host. elif netloc and netloc != request.get_host(): redirect_to = settings.LOGIN_REDIRECT_URL # Okay, security checks complete. Log the user in. auth_login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() return HttpResponseRedirect(redirect_to) else: form = authentication_form(request) request.session.set_test_cookie() current_site = get_current_site(request) context = { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context, current_app=current_app)
def index(request, sitemaps, template_name='sitemap_index.xml', mimetype='application/xml', sitemap_url_name='my_django.contrib.sitemaps.views.sitemap'): req_protocol = 'https' if request.is_secure() else 'http' req_site = get_current_site(request) sites = [] for section, site in sitemaps.items(): if callable(site): site = site() protocol = req_protocol if site.protocol is None else site.protocol sitemap_url = urlresolvers.reverse(sitemap_url_name, kwargs={'section': section}) absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url) sites.append(absolute_url) for page in range(2, site.paginator.num_pages + 1): sites.append('%s?p=%s' % (absolute_url, page)) return TemplateResponse(request, template_name, {'sitemaps': sites}, content_type=mimetype)
def shortcut(request, content_type_id, object_id): """ Redirect to an object's page based on a content-type ID and an object ID. """ # Look up the object, making sure it's got a get_absolute_url() function. try: content_type = ContentType.objects.get(pk=content_type_id) if not content_type.model_class(): raise http.Http404( _(u"Content type %(ct_id)s object has no associated model") % {'ct_id': content_type_id}) obj = content_type.get_object_for_this_type(pk=object_id) except (ObjectDoesNotExist, ValueError): raise http.Http404( _(u"Content type %(ct_id)s object %(obj_id)s doesn't exist") % { 'ct_id': content_type_id, 'obj_id': object_id }) try: get_absolute_url = obj.get_absolute_url except AttributeError: raise http.Http404( _("%(ct_name)s objects don't have a get_absolute_url() method") % {'ct_name': content_type.name}) absurl = get_absolute_url() # Try to figure out the object's domain, so we can do a cross-site redirect # if necessary. # If the object actually defines a domain, we're done. if absurl.startswith('http://') or absurl.startswith('https://'): return http.HttpResponseRedirect(absurl) # Otherwise, we need to introspect the object's relationships for a # relation to the Site object object_domain = None if Site._meta.installed: opts = obj._meta # First, look for an many-to-many relationship to Site. for field in opts.many_to_many: if field.rel.to is Site: try: # Caveat: In the case of multiple related Sites, this just # selects the *first* one, which is arbitrary. object_domain = getattr(obj, field.name).all()[0].domain except IndexError: pass if object_domain is not None: break # Next, look for a many-to-one relationship to Site. if object_domain is None: for field in obj._meta.fields: if field.rel and field.rel.to is Site: try: object_domain = getattr(obj, field.name).domain except Site.DoesNotExist: pass if object_domain is not None: break # Fall back to the current site (if possible). if object_domain is None: try: object_domain = get_current_site(request).domain except Site.DoesNotExist: pass # If all that malarkey found an object domain, use it. Otherwise, fall back # to whatever get_absolute_url() returned. if object_domain is not None: protocol = request.is_secure() and 'https' or 'http' return http.HttpResponseRedirect('%s://%s%s' % (protocol, object_domain, absurl)) else: return http.HttpResponseRedirect(absurl)
def get_feed(self, obj, request): """ Returns a feedgenerator.DefaultFeed object, fully populated, for this feed. Raises FeedDoesNotExist for invalid parameters. """ current_site = get_current_site(request) link = self.__get_dynamic_attr('link', obj) link = add_domain(current_site.domain, link, request.is_secure()) feed = self.feed_type( title=self.__get_dynamic_attr('title', obj), subtitle=self.__get_dynamic_attr('subtitle', obj), link=link, description=self.__get_dynamic_attr('description', obj), language=settings.LANGUAGE_CODE.decode(), feed_url=add_domain( current_site.domain, self.__get_dynamic_attr('feed_url', obj) or request.path, request.is_secure(), ), author_name=self.__get_dynamic_attr('author_name', obj), author_link=self.__get_dynamic_attr('author_link', obj), author_email=self.__get_dynamic_attr('author_email', obj), categories=self.__get_dynamic_attr('categories', obj), feed_copyright=self.__get_dynamic_attr('feed_copyright', obj), feed_guid=self.__get_dynamic_attr('feed_guid', obj), ttl=self.__get_dynamic_attr('ttl', obj), **self.feed_extra_kwargs(obj)) title_tmp = None if self.title_template is not None: try: title_tmp = loader.get_template(self.title_template) except TemplateDoesNotExist: pass description_tmp = None if self.description_template is not None: try: description_tmp = loader.get_template( self.description_template) except TemplateDoesNotExist: pass for item in self.__get_dynamic_attr('items', obj): if title_tmp is not None: title = title_tmp.render( RequestContext(request, { 'obj': item, 'site': current_site })) else: title = self.__get_dynamic_attr('item_title', item) if description_tmp is not None: description = description_tmp.render( RequestContext(request, { 'obj': item, 'site': current_site })) else: description = self.__get_dynamic_attr('item_description', item) link = add_domain( current_site.domain, self.__get_dynamic_attr('item_link', item), request.is_secure(), ) enc = None enc_url = self.__get_dynamic_attr('item_enclosure_url', item) if enc_url: enc = feedgenerator.Enclosure( url=smart_unicode(enc_url), length=smart_unicode( self.__get_dynamic_attr('item_enclosure_length', item)), mime_type=smart_unicode( self.__get_dynamic_attr('item_enclosure_mime_type', item))) author_name = self.__get_dynamic_attr('item_author_name', item) if author_name is not None: author_email = self.__get_dynamic_attr('item_author_email', item) author_link = self.__get_dynamic_attr('item_author_link', item) else: author_email = author_link = None pubdate = self.__get_dynamic_attr('item_pubdate', item) if pubdate and is_naive(pubdate): ltz = tzinfo.LocalTimezone(pubdate) pubdate = pubdate.replace(tzinfo=ltz) feed.add_item( title=title, link=link, description=description, unique_id=self.__get_dynamic_attr('item_guid', item, link), enclosure=enc, pubdate=pubdate, author_name=author_name, author_email=author_email, author_link=author_link, categories=self.__get_dynamic_attr('item_categories', item), item_copyright=self.__get_dynamic_attr('item_copyright', item), **self.item_extra_kwargs(item)) return feed