本文整理汇总了Python中django.contrib方法的典型用法代码示例。如果您正苦于以下问题:Python django.contrib方法的具体用法?Python django.contrib怎么用?Python django.contrib使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django
的用法示例。
在下文中一共展示了django.contrib方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_sites
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def test_sites(self):
""" Tests the django.contrib.sites support.
A separate metadata definition is used, WithSites, which has turned on sites support.
"""
path = "/abc/"
site = Site.objects.get_current()
path_metadata = WithSites._meta.get_model('path').objects.create(_site=site, title="Site Path title",
_path=path)
self.assertEqual(seo_get_metadata(path, name="WithSites").title.value, 'Site Path title')
# Metadata with site=null should work
path_metadata._site_id = None
path_metadata.save()
self.assertEqual(seo_get_metadata(path, name="WithSites").title.value, 'Site Path title')
# Metadata with an explicitly wrong site should not work
path_metadata._site_id = site.id + 1
path_metadata.save()
self.assertEqual(seo_get_metadata(path, name="WithSites").title.value, None)
示例2: get_admin_site
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def get_admin_site(current_app):
"""
Method tries to get actual admin.site class, if any custom admin sites
were used. Couldn't find any other references to actual class other than
in func_closer dict in index() func returned by resolver.
"""
try:
resolver_match = resolve(reverse('%s:index' % current_app))
# Django 1.9 exposes AdminSite instance directly on view function
if hasattr(resolver_match.func, 'admin_site'):
return resolver_match.func.admin_site
for func_closure in resolver_match.func.__closure__:
if isinstance(func_closure.cell_contents, AdminSite):
return func_closure.cell_contents
except:
pass
from django.contrib import admin
return admin.site
示例3: drf_router
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def drf_router():
"""
DRF Router as a lazy object because it needs to import User model which
can't be done until after django.setup()
"""
from django.contrib.auth.models import User
from rest_framework import routers
from rest_framework import serializers
from rest_framework import viewsets
class UserSerializer(serializers.Serializer):
id = serializers.IntegerField(label="ID", read_only=True)
username = serializers.CharField(max_length=200)
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
router = routers.SimpleRouter()
router.register(r"users", UserViewSet)
return router
示例4: tastypie_api
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def tastypie_api():
"""
Tastypie API as a lazy object because it needs to import User model which
can't be done until after django.setup()
"""
from django.contrib.auth.models import User
try:
from tastypie.api import Api as TastypieApi
from tastypie.resources import ModelResource as TastypieModelResource
except ImportError:
return None
class UserResource(TastypieModelResource):
class Meta:
queryset = User.objects.all()
allowed_methods = ["get"]
api = TastypieApi(api_name="v1")
api.register(UserResource())
return api
示例5: email
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def email(recipient, context, template_name, sender=None):
if not settings.MANDRILL_API_KEY or settings.MANDRILL_API_KEY == 'None':
return
current_site = Site.objects.get_current()
context['domain'] = current_site.domain
User = django.contrib.auth.get_user_model()
# The recipient list can be a list of User model instances or Email Address string
# Which means you could pass a User model QuerySet as recipient
# If a recipient is User model instance then simple convert to Email Address string
recipient_email_list = []
for rec in recipient:
if isinstance(rec, User):
if rec.first_name and rec.last_name:
recipient_email_list.append('"%s %s" <%s>' % (rec.first_name, rec.last_name, rec.email))
elif rec.first_name:
recipient_email_list.append('"%s" <%s>' % (rec.first_name, rec.email))
else:
recipient_email_list.append('%s' % rec.email)
else:
recipient_email_list.append(rec)
mail.send(
sender=sender or settings.DEFAULT_FROM_EMAIL,
recipients=recipient_email_list,
template=template_name,
context=context,
priority=PRIORITY.now
)
示例6: _get_seo_content_types
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def _get_seo_content_types(seo_models):
""" Returns a list of content types from the models defined in settings
(SEO_MODELS)
"""
from django.contrib.contenttypes.models import ContentType
try:
return [ContentType.objects.get_for_model(m).id for m in seo_models]
except: # previously caught DatabaseError
# Return an empty list if this is called too early
return []
示例7: register_model_in_admin
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def register_model_in_admin(model, admin_class=None):
"""
Register model in Django admin interface
"""
from django.contrib import admin
admin.site.register(model, admin_class)
_reload_urlconf()
示例8: test_default_fallback
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def test_default_fallback(self):
""" Tests the ability to use the current Site name as a default
fallback.
"""
from django.contrib.sites.models import Site
site = Site.objects.get_current()
self.assertEqual(site.name, self.context.title.value)
示例9: django_settings
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def django_settings(self):
import django
from django.conf import settings
from django.contrib import admin
from django.urls import path
if settings.configured:
return
settings.configure(
ALLOWED_HOSTS=[
'testserver',
],
INSTALLED_APPS=[
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
],
MIDDLEWARE=[
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
)
django.setup()
settings.ROOT_URLCONF = (
path('admin/', admin.site.urls),
)
示例10: test_subdomains
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def test_subdomains(self):
path = '/abc/'
subdomain = 'msk'
path_metadata = WithSubdomains._meta.get_model('path').objects.create(
_subdomain='msk', title='German Path title', _path=path
)
self.assertEqual(
seo_get_metadata(path, name='WithSubdomains', subdomain=subdomain).title.value, 'German Path title')
path_metadata._subdomain = 'spb'
path_metadata.save()
self.assertEqual(seo_get_metadata(path, name='WithSubdomains', subdomain=subdomain).title.value, None)
# # FUTURE feature
#
# def test_redirect(self):
# """ Tests django.contrib.redirect support, automatically adding redirects for new paths.
# """
# old_path = "/abc/"
# new_path = "/new-path/"
#
# # Check that the redirect doesn't already exist
# self.assertEqual(Redirect.objects.filter(old_path=old_path, new_path=new_path).count(), 0)
#
# path_metadata = WithRedirect._meta.get_model('path').objects.create(title="A Path title", _path=old_path)
# self.assertEqual(seo_get_metadata(old_path, name="WithRedirect").title.value, 'A Path title')
#
# # Rename the path
# path_metadata._path = new_path
# path_metadata.save()
# self.assertEqual(seo_get_metadata(old_path, name="WithRedirect").title.value, None)
# self.assertEqual(seo_get_metadata(new_path, name="WithRedirect").title.value, 'A Path title')
#
# # Check that a redirect was created
# self.assertEqual(Redirect.objects.filter(old_path=old_path, new_path=new_path).count(), 1)
#
# def test_redirect_with_sites(self):
# """ Tests django.contrib.redirect support, automatically adding redirects for new paths.
# """
# old_path = "/abc/"
# new_path = "/new-path/"
# site = Site.objects.get_current()
#
# # Check that the redirect doesn't already exist
# self.assertEqual(Redirect.objects.filter(old_path=old_path, new_path=new_path, site=site).count(), 0)
#
# path_metadata = WithRedirectSites._meta.get_model('path').objects.create(title="A Path title", _path=old_path, _site=site)
# self.assertEqual(seo_get_metadata(old_path, name="WithRedirectSites").title.value, 'A Path title')
#
# # Rename the path
# path_metadata._path = new_path
# path_metadata.save()
# self.assertEqual(seo_get_metadata(old_path, name="WithRedirectSites").title.value, None)
# self.assertEqual(seo_get_metadata(new_path, name="WithRedirectSites").title.value, 'A Path title')
#
# # Check that a redirect was created
# self.assertEqual(Redirect.objects.filter(old_path=old_path, new_path=new_path, site=site).count(), 1)
示例11: get_menu
# 需要导入模块: import django [as 别名]
# 或者: from django import contrib [as 别名]
def get_menu(context, request, position='left'):
"""
:type request: WSGIRequest
"""
if not isinstance(request, HttpRequest):
return None
use_custom_menu = get_adminlte_option('USE_CUSTOM_MENU')
if use_custom_menu.get('USE_CUSTOM_MENU',
'0') == '1' and use_custom_menu.get('valid') is True:
return get_custom_menu(request, position)
if position != 'left':
return []
# Django 1.9+
available_apps = context.get('available_apps')
if not available_apps:
# Django 1.8 on app index only
available_apps = context.get('app_list')
# Django 1.8 on rest of the pages
if not available_apps:
try:
from django.contrib import admin
template_response = get_admin_site(request.current_app).index(
request)
available_apps = template_response.context_data['app_list']
except Exception:
pass
if not available_apps:
logging.warn('adminlteui was unable to retrieve apps list for menu.')
for app in available_apps:
if app.get('app_label') == 'django_admin_settings':
if request.user.has_perm('django_admin_settings.add_options') or \
request.user.has_perm(
'django_admin_settings.change_options'):
app.get('models').insert(0, {
'name': _('General Options'),
'object_name': 'Options',
'perms':
{
'add': True,
'change': True,
'delete': True,
'view': True
},
'admin_url': reverse(
'admin:general_option'),
'view_only': False
})
else:
for model in app.get('models', []):
model['icon'] = get_adminlte_settings() \
.get('icons', {}).get(app['app_label'], {}).get(
model['name'].lower())
# return MenuManager(available_apps, context, request)
return available_apps