code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
"""Refactored "safe reference" from dispatcher.py"""
import weakref, traceback
def safeRef(target, onDelete = None):
"""Return a *safe* weak reference to a callable target
target -- the object to be weakly referenced, if it's a
bound method reference, will create a BoundMethodWeakref,
otherwis... | Python |
"""Robust apply mechanism
Provides a function "call", which can sort out
what arguments a given callable object can take,
and subset the given arguments to match only
those which are acceptable.
"""
def function( receiver ):
"""Get function-like callable object for given receiver
returns (function_or_method,... | Python |
"""Multiple-producer-multiple-consumer signal-dispatching
dispatcher is the core of the PyDispatcher system,
providing the primary API and the core logic for the
system.
Module attributes of note:
Any -- Singleton used to signal either "Any Sender" or
"Any Signal". See documentation of the _Any class.
... | Python |
"""Module implementing error-catching version of send (sendRobust)"""
from django.dispatch.dispatcher import Any, Anonymous, liveReceivers, getAllReceivers
from django.dispatch.robustapply import robustApply
def sendRobust(
signal=Any,
sender=Anonymous,
*arguments, **named
):
"""Send signal from send... | Python |
"""Error types for dispatcher mechanism
"""
class DispatcherError(Exception):
"""Base class for all Dispatcher errors"""
class DispatcherKeyError(KeyError, DispatcherError):
"""Error raised when unknown (sender,signal) set specified"""
class DispatcherTypeError(TypeError, DispatcherError):
"""Error raised ... | Python |
"""Multi-consumer multi-producer dispatching mechanism
"""
__version__ = "1.0.0"
__author__ = "Patrick K. O'Brien"
__license__ = "BSD-style, see license.txt for details"
| Python |
from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import gettext_lazy as _
class Redirect(models.Model):
site = models.ForeignKey(Site, radio_admin=models.VERTICAL)
old_path = models.CharField(_('redirect from'), maxlength=200, db_index=True,
help_t... | Python |
from django.contrib.redirects.models import Redirect
from django import http
from django.conf import settings
class RedirectFallbackMiddleware(object):
def process_response(self, request, response):
if response.status_code != 404:
return response # No need to check for a redirect for non-404 re... | Python |
"""
USA-specific Form helpers
"""
from django.newforms import ValidationError
from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES
from django.newforms.util import smart_unicode
from django.utils.translation import gettext
import re
phone_digits_re = re.compile(r'^(?:1-?)?(\d{3})[-\.]?(\d{3})[-\... | Python |
"""
A mapping of state misspellings/abbreviations to normalized abbreviations, and
an alphabetical list of states for use as `choices` in a formfield.
This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
STATE_CHOICES = (
('AL', 'Alabama'),
('AK', 'Alaska'),
... | Python |
"""
UK-specific Form helpers
"""
from django.newforms.fields import RegexField
from django.utils.translation import gettext
class UKPostcodeField(RegexField):
"""
A form field that validates its input is a UK postcode.
The regular expression used is sourced from the schema for British Standard
BS7666... | Python |
from django.conf import settings
from django.db import models
from django.db.models.fields import FieldDoesNotExist
class CurrentSiteManager(models.Manager):
"Use this to limit objects to those associated with the current site."
def __init__(self, field_name='site'):
super(CurrentSiteManager, self).__i... | Python |
from django.db import models
from django.utils.translation import gettext_lazy as _
class SiteManager(models.Manager):
def get_current(self):
from django.conf import settings
return self.get(pk=settings.SITE_ID)
class Site(models.Model):
domain = models.CharField(_('domain name'), maxlength=10... | Python |
"""
Creates the default Site object.
"""
from django.dispatch import dispatcher
from django.db.models import signals
from django.contrib.sites.models import Site
from django.contrib.sites import models as site_app
def create_default_site(app, created_models, verbosity):
if Site in created_models:
if verbo... | Python |
"""
Set of "markup" template filters for Django. These filters transform plain text
markup syntaxes to HTML; currently there is support for:
* Textile, which requires the PyTextile library available at
http://dealmeida.net/projects/textile/
* Markdown, which requires the Python-markdown library from
... | Python |
from django.db import models
from django.utils.translation import gettext_lazy as _
CONTENT_TYPE_CACHE = {}
class ContentTypeManager(models.Manager):
def get_for_model(self, model):
"""
Returns the ContentType object for the given model, creating the
ContentType if necessary.
"""
... | Python |
"""
Creates content types for all installed models.
"""
from django.dispatch import dispatcher
from django.db.models import get_apps, get_models, signals
def create_contenttypes(app, created_models, verbosity=2):
from django.contrib.contenttypes.models import ContentType
ContentType.objects.clear_cache()
... | Python |
"""
Formtools Preview application.
This is an abstraction of the following workflow:
"Display an HTML form, force a preview, then do something with the submission."
Given a django.newforms.Form object that you define, this takes care of the
following:
* Displays the form as HTML on a Web page.
* Validat... | Python |
from django.conf import settings
from django.conf.urls.defaults import *
if settings.USE_I18N:
i18n_view = 'django.views.i18n.javascript_catalog'
else:
i18n_view = 'django.views.i18n.null_javascript_catalog'
urlpatterns = patterns('',
('^$', 'django.contrib.admin.views.main.index'),
('^r/(\d+)/(.*)/$'... | Python |
"Misc. utility functions/classes for admin documentation generator."
import re
from email.Parser import HeaderParser
from email.Errors import HeaderParseError
try:
import docutils.core
import docutils.nodes
import docutils.parsers.rst.roles
except ImportError:
docutils_is_available = False
else:
do... | Python |
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
ADDITION = 1
CHANGE = 2
DELETION = 3
class LogEntryManager(models.Manager):
def log_action(self, user_id, content_type_id, obje... | Python |
"""
FilterSpec encapsulates the logic for displaying filters in the Django admin.
Filters are specified in models with the "list_filter" option.
Each filter subclass knows how to display a filter for a field that passes a
certain test -- e.g. being a DateField or ForeignKey.
"""
from django.db import models
import da... | Python |
from django.contrib.admin.views.decorators import staff_member_required
from django.core import validators
from django import template, oldforms
from django.template import loader
from django.shortcuts import render_to_response
from django.contrib.sites.models import Site
from django.conf import settings
def template_... | Python |
from django import oldforms, template
from django.conf import settings
from django.contrib.admin.filterspecs import FilterSpec
from django.contrib.admin.views.decorators import staff_member_required
from django.views.decorators.cache import never_cache
from django.contrib.contenttypes.models import ContentType
from dja... | Python |
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.forms import UserCreationForm, AdminPasswordChangeForm
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django import oldforms, template
from django.shortcuts import rende... | Python |
from django import template, templatetags
from django.template import RequestContext
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.db import models
from django.shortcuts import render_to_response
from django.core.exceptions import ImproperlyConfigur... | Python |
from django import http, template
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.shortcuts import render_to_response
from django.utils.translation import gettext_lazy
import base64, datetime, md5
import cPickle as pickle
ERRO... | Python |
from django import template
from django.db.models import get_models
register = template.Library()
class AdminApplistNode(template.Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
from django.db import models
from django.utils.text import capfirst
... | Python |
from django import template
from django.contrib.admin.views.main import AdminBoundField
from django.template import loader
from django.utils.text import capfirst
from django.db import models
from django.db.models.fields import Field
from django.db.models.related import BoundRelatedObject
from django.conf import setting... | Python |
from django.template import Library
register = Library()
def admin_media_prefix():
"""
Returns the string contained in the setting ADMIN_MEDIA_PREFIX.
"""
try:
from django.conf import settings
except ImportError:
return ''
return settings.ADMIN_MEDIA_PREFIX
admin_media_prefix =... | Python |
from django.conf import settings
from django.contrib.admin.views.main import ALL_VAR, EMPTY_CHANGELIST_VALUE
from django.contrib.admin.views.main import ORDER_VAR, ORDER_TYPE_VAR, PAGE_VAR, SEARCH_VAR
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils import dateformat
... | Python |
from django import template
from django.contrib.admin.models import LogEntry
register = template.Library()
class AdminLogNode(template.Node):
def __init__(self, limit, varname, user):
self.limit, self.varname, self.user = limit, varname, user
def __repr__(self):
return "<GetAdminLog Node>"
... | Python |
from django.utils.translation import ngettext
from django.utils.translation import gettext_lazy as _
from django import template
import re
register = template.Library()
def ordinal(value):
"""
Converts an integer to its ordinal as a string. 1 is '1st', 2 is '2nd',
3 is '3rd', etc. Works for any integer.
... | Python |
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
from django.conf import settings
import datetime
MIN_PHOTO_DIMENSION = 5
MAX_PHOTO_DIME... | Python |
from django.conf import settings
from django.contrib.comments.models import Comment, FreeComment
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
class LatestFreeCommentsFeed(Feed):
"Feed of latest comments on the current site."
comments_class = FreeComment
d... | Python |
from django.conf.urls.defaults import *
urlpatterns = patterns('django.contrib.comments.views',
(r'^post/$', 'comments.post_comment'),
(r'^postfree/$', 'comments.post_free_comment'),
(r'^posted/$', 'comments.comment_was_posted'),
(r'^karma/vote/(?P<comment_id>\d+)/(?P<vote>up|down)/$', 'karma.vote'),
... | Python |
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import Http404
from django.contrib.comments.models import Comment, ModeratorDeletion, UserFlag
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedi... | Python |
from django.http import Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.comments.models import Comment, KarmaScore
def vote(request, comment_id, vote):
"""
Rate a comment (+1 or -1)
Templates: `karma_vote_accepted`
Context:
... | Python |
from django.core import validators
from django import oldforms
from django.core.mail import mail_admins, mail_managers
from django.http import Http404
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.comm... | Python |
from django.contrib.comments.models import Comment, FreeComment
from django.contrib.comments.models import PHOTOS_REQUIRED, PHOTOS_OPTIONAL, RATINGS_REQUIRED, RATINGS_OPTIONAL, IS_PUBLIC
from django.contrib.comments.models import MIN_PHOTO_DIMENSION, MAX_PHOTO_DIMENSION
from django import template
from django.template ... | Python |
from django.core import urlresolvers
import urllib
PING_URL = "http://www.google.com/webmasters/sitemaps/ping"
class SitemapNotFound(Exception):
pass
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 provi... | Python |
from django.http import HttpResponse, Http404
from django.template import loader
from django.contrib.sites.models import Site
from django.core import urlresolvers
def index(request, sitemaps):
current_site = Site.objects.get_current()
sites = []
protocol = request.is_secure() and 'https' or 'http'
for ... | Python |
import base64, md5, random, sys, datetime
import cPickle as pickle
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.conf import settings
class SessionManager(models.Manager):
def encode(self, session_dict):
"Returns the given session dictionary pickled and enc... | Python |
from django.conf import settings
from django.contrib.sessions.models import Session
from django.core.exceptions import SuspiciousOperation
from django.utils.cache import patch_vary_headers
import datetime
TEST_COOKIE_NAME = 'testcookie'
TEST_COOKIE_VALUE = 'worked'
class SessionWrapper(object):
def __init__(self,... | Python |
from django.conf.urls.defaults import *
urlpatterns = patterns('django.contrib.flatpages.views',
(r'^(?P<url>.*)$', 'flatpage'),
)
| Python |
from django.core import validators
from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import gettext_lazy as _
class FlatPage(models.Model):
url = models.CharField(_('URL'), maxlength=100, validator_list=[validators.isAlphaNumericURL],
help_text=_("Examp... | Python |
from django.contrib.flatpages.views import flatpage
from django.http import Http404
from django.conf import settings
class FlatpageFallbackMiddleware(object):
def process_response(self, request, response):
if response.status_code != 404:
return response # No need to check for a flatpage for non... | Python |
from django.contrib.flatpages.models import FlatPage
from django.template import loader, RequestContext
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.conf import settings
from django.core.xheaders import populate_xheaders
DEFAULT_TEMPLATE = 'flatpages/default.html'
de... | Python |
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.sites.models import Site
from django.template import Context, loader
from django.core import validators
from django import oldforms
from django.utils.translation import gettext as _
class UserCreationForm(oldfo... | Python |
from django.core import validators
from django.core.exceptions import ImproperlyConfigured
from django.db import backend, connection, models
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import gettext_lazy as _
import datetime
def check_password(raw_password, enc_password):
... | Python |
from django.contrib.auth import LOGIN_URL, REDIRECT_FIELD_NAME
from django.http import HttpResponseRedirect
from urllib import quote
def user_passes_test(test_func, login_url=LOGIN_URL):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. Th... | Python |
"""
Helper function for creating superusers in the authentication system.
If run from the command line, this module lets you create a superuser
interactively.
"""
from django.core import validators
from django.contrib.auth.models import User
import getpass
import os
import sys
def createsuperuser(username=None, emai... | Python |
"""
Creates permissions for all installed apps that need permissions.
"""
from django.dispatch import dispatcher
from django.db.models import get_models, signals
from django.contrib.auth import models as auth_app
def _get_permission_codename(action, opts):
return '%s_%s' % (action, opts.object_name.lower())
def ... | Python |
class LazyUser(object):
def __get__(self, request, obj_type=None):
if not hasattr(request, '_cached_user'):
from django.contrib.auth import get_user
request._cached_user = get_user(request)
return request._cached_user
class AuthenticationMiddleware(object):
def process_r... | Python |
from django.core.exceptions import ImproperlyConfigured
SESSION_KEY = '_auth_user_id'
BACKEND_SESSION_KEY = '_auth_user_backend'
LOGIN_URL = '/accounts/login/'
REDIRECT_FIELD_NAME = 'next'
def load_backend(path):
i = path.rfind('.')
module, attr = path[:i], path[i+1:]
try:
mod = __import__(module,... | Python |
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm
from django import oldforms
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.sites.models import Site
from django.http import... | Python |
from django.contrib.auth.models import User
class ModelBackend:
"""
Authenticate against django.contrib.auth.models.User
"""
# TODO: Model, login attribute name and password attribute name should be
# configurable.
def authenticate(self, username=None, password=None):
try:
u... | Python |
from mod_python import apache
import os
def authenhandler(req, **kwargs):
"""
Authentication handler that checks against Django's auth database.
"""
# mod_python fakes the environ, and thus doesn't process SetEnv. This fixes
# that so that the following import works
os.environ.update(req.subp... | Python |
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.template import Context, loader, Template, TemplateDoesNotExist
from django.contrib.sites.models import Site
from django.utils import feedgenerator
from django.conf import settings
def add_domain(domain, url):
if not url.starts... | Python |
from django.contrib.syndication import feeds
from django.http import HttpResponse, Http404
def feed(request, url, feed_dict=None):
if not feed_dict:
raise Http404, "No feeds are registered."
try:
slug, param = url.split('/', 1)
except ValueError:
slug, param = url, ''
try:
... | Python |
"""
Cross Site Request Forgery Middleware.
This module provides a middleware that implements protection
against request forgeries from other sites.
"""
from django.conf import settings
from django.http import HttpResponseForbidden
import md5
import re
import itertools
_ERROR_MSG = '<html xmlns="http://www.w3.org/19... | Python |
"""
Field classes
"""
from django.utils.translation import gettext
from util import ErrorList, ValidationError, smart_unicode
from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple
import datetime
import re
import time
__all__ = (
'... | Python |
"""
Form classes
"""
from django.utils.datastructures import SortedDict, MultiValueDict
from django.utils.html import escape
from fields import Field
from widgets import TextInput, Textarea, HiddenInput, MultipleHiddenInput
from util import flatatt, StrAndUnicode, ErrorDict, ErrorList, ValidationError
import copy
__a... | Python |
"""
Helper functions for creating Form classes from Django models
and database field objects.
"""
from django.utils.translation import gettext
from util import ValidationError
from forms import BaseForm, DeclarativeFieldsMetaclass, SortedDictFromList
from fields import Field, ChoiceField
from widgets import Select, Se... | Python |
"""
HTML Widget classes
"""
__all__ = (
'Widget', 'TextInput', 'PasswordInput', 'HiddenInput', 'MultipleHiddenInput',
'FileInput', 'Textarea', 'CheckboxInput',
'Select', 'NullBooleanSelect', 'SelectMultiple', 'RadioSelect', 'CheckboxSelectMultiple',
'MultiWidget', 'SplitDateTimeWidget',
)
from util im... | Python |
"""
Extra HTML Widget classes
"""
from django.newforms.widgets import Widget, Select
from django.utils.dates import MONTHS
import datetime
__all__ = ('SelectDateWidget',)
class SelectDateWidget(Widget):
"""
A Widget that splits date input into three <select> boxes.
This also serves as an example of a Wi... | Python |
from widgets import *
| Python |
from django.conf import settings
from django.utils.html import escape
# Converts a dictionary to a single string with key="value", XML-style with
# a leading space. Assumes keys do not need to be XML-escaped.
flatatt = lambda attrs: u''.join([u' %s="%s"' % (k, escape(v)) for k, v in attrs.items()])
def smart_unicode(... | Python |
"""
Django validation and HTML form handling.
TODO:
Default value for field
Field labels
Nestable Forms
FatalValidationError -- short-circuits all other validators on a form
ValidationWarning
"This form field requires foo.js" and form.js_includes()
"""
from util import ValidationError
from wid... | Python |
"Default tags used by the template system, available to all templates."
from django.template import Node, NodeList, Template, Context, resolve_variable
from django.template import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_START, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE... | Python |
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
_standard_context_processors = None
class ContextPopException(Exception):
"pop() has been called more times than push()"
pass
class Context(object):
"A stack container for variable context"
def __init__(self, dic... | Python |
"Default variable filters"
from django.template import resolve_variable, Library
from django.conf import settings
from django.utils.translation import gettext
import re
import random as random_module
register = Library()
#######################
# STRING DECORATOR #
#######################
def smart_string(obj):
... | Python |
# Wrapper for loading templates from storage of some sort (e.g. filesystem, database).
#
# This uses the TEMPLATE_LOADERS setting, which is a list of loaders to use.
# Each loader is expected to have this interface:
#
# callable(name, dirs=[])
#
# name is the template name.
# dirs is an optional list of directories ... | Python |
# Wrapper for loading templates from "template" directories in installed app packages.
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template import TemplateDoesNotExist
import os
# At compile time, cache the directories to search.
app_template_dirs = []
for app ... | Python |
# Wrapper for loading templates from eggs via pkg_resources.resource_string.
try:
from pkg_resources import resource_string
except ImportError:
resource_string = None
from django.template import TemplateDoesNotExist
from django.conf import settings
def load_template_source(template_name, template_dirs=None):... | Python |
# Wrapper for loading templates from the filesystem.
from django.conf import settings
from django.template import TemplateDoesNotExist
import os
def get_template_sources(template_name, template_dirs=None):
if not template_dirs:
template_dirs = settings.TEMPLATE_DIRS
for template_dir in template_dirs:
... | Python |
"""
This is the Django template system.
How it works:
The Lexer.tokenize() function converts a template string (i.e., a string containing
markup with custom template tags) to tokens, which can be either plain text
(TOKEN_TEXT), variables (TOKEN_VAR) or block statements (TOKEN_BLOCK).
The Parser() class takes a list ... | Python |
from django.template import TemplateSyntaxError, TemplateDoesNotExist, resolve_variable
from django.template import Library, Node
from django.template.loader import get_template, get_template_from_string, find_template_source
from django.conf import settings
register = Library()
class ExtendsError(Exception):
pas... | Python |
VERSION = (0, 96.1, None)
| Python |
from django import http
from django.utils.translation import check_for_language, activate, to_locale, get_language
from django.utils.text import javascript_quote
from django.conf import settings
import os
import gettext as gettext_module
def set_language(request):
"""
Redirect to a given url while setting the ... | Python |
from django.core.exceptions import ObjectDoesNotExist
from django.template import Context, RequestContext, loader
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django import http
def shortcut(request, content_type_id, object_id):
"Redirect to an object... | Python |
from django.utils.cache import patch_vary_headers
def vary_on_headers(*headers):
"""
A view decorator that adds the specified headers to the Vary header of the
response. Usage:
@vary_on_headers('Cookie', 'Accept-language')
def index(request):
...
Note that the header names ar... | Python |
"""
Decorator for views that tries getting the page from the cache and
populates the cache if the page isn't in the cache yet.
The cache is keyed by the URL and some data from the headers. Additionally
there is the key prefix that is used to distinguish different cache areas
in a multi-site setup. You could use the si... | Python |
"Decorator for views that gzips pages if the client supports it."
from django.utils.decorators import decorator_from_middleware
from django.middleware.gzip import GZipMiddleware
gzip_page = decorator_from_middleware(GZipMiddleware)
| Python |
"""
Decorators for views based on HTTP headers.
"""
from django.utils.decorators import decorator_from_middleware
from django.middleware.http import ConditionalGetMiddleware
from django.http import HttpResponseNotAllowed
conditional_page = decorator_from_middleware(ConditionalGetMiddleware)
def require_http_methods(... | Python |
from django.template import loader
from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseNotModified
from django.template import Template, Context, TemplateDoesNotExist
import mimetypes
import os
import posixpath
import re
import rfc822
import stat
import urllib
def serve(request, path, docu... | Python |
from django.conf import settings
from django.template import Template, Context, TemplateDoesNotExist
from django.utils.html import escape
from django.http import HttpResponseServerError, HttpResponseNotFound
import os, re
HIDDEN_SETTINGS = re.compile('SECRET|PASSWORD|PROFANITIES_LIST')
def linebreak_iter(template_sou... | Python |
from django.template import loader, RequestContext
from django.core.exceptions import ObjectDoesNotExist
from django.core.xheaders import populate_xheaders
from django.db.models.fields import DateTimeField
from django.http import Http404, HttpResponse
import datetime, time
def archive_index(request, queryset, date_fie... | Python |
from django.core.xheaders import populate_xheaders
from django.template import loader
from django import oldforms
from django.db.models import FileField
from django.contrib.auth.views import redirect_to_login
from django.template import RequestContext
from django.http import Http404, HttpResponse, HttpResponseRedirect
... | Python |
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponsePermanentRedirect, HttpResponseGone
def direct_to_template(request, template, extra_context={}, **kwargs):
"""
Render a given template with any extra URL parameters in th... | Python |
from django.template import loader, RequestContext
from django.http import Http404, HttpResponse
from django.core.xheaders import populate_xheaders
from django.core.paginator import ObjectPaginator, InvalidPage
from django.core.exceptions import ObjectDoesNotExist
def object_list(request, queryset, paginate_by=None, p... | Python |
from django.template import Node, resolve_variable
from django.template import TemplateSyntaxError, TokenParser, Library
from django.template import TOKEN_TEXT, TOKEN_VAR
from django.utils import translation
register = Library()
class GetAvailableLanguagesNode(Node):
def __init__(self, variable):
self.var... | Python |
from django.conf import settings
for a in settings.INSTALLED_APPS:
try:
__path__.extend(__import__(a + '.templatetags', {}, {}, ['']).__path__)
except ImportError:
pass
| Python |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^$', 'examples.views.index'),
(r'^hello/', include('examples.hello.urls')),
)
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to ... | Python |
# Django settings for the example project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'examples.urls'
| Python |
from django import http
def index(request):
r = http.HttpResponse('<h1>Django examples</h1><ul>')
r.write('<li><a href="hello/html/">Hello world (HTML)</a></li>')
r.write('<li><a href="hello/text/">Hello world (text)</a></li>')
r.write('<li><a href="hello/write/">HttpResponse objects are file-like obje... | Python |
from django.conf.urls.defaults import *
urlpatterns = patterns('examples.hello.views',
(r'^html/$', 'hello_html'),
(r'^text/$', 'hello_text'),
(r'^write/$', 'hello_write'),
(r'^metadata/$', 'metadata'),
(r'^getdata/$', 'get_data'),
(r'^postdata/$', 'post_data'),
)
| Python |
from django.http import HttpResponse
from django.utils.html import escape
def hello_html(request):
"This view is a basic 'hello world' example in HTML."
return HttpResponse('<h1>Hello, world.</h1>')
def hello_text(request):
"This view is a basic 'hello world' example in plain text."
return HttpRespons... | Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to ... | Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.