本文整理汇总了Python中mezzanine.utils.sites.current_site_id函数的典型用法代码示例。如果您正苦于以下问题:Python current_site_id函数的具体用法?Python current_site_id怎么用?Python current_site_id使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了current_site_id函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: handle
def handle(self, *args, **options):
if options['truncate']:
print 'Deleting Blog Entries:'
for entry in BlogPost.objects.all():
print '\t{}'.format(entry.title)
BlogPost.objects.all().delete()
category_lookup = {}
with open('db_export/blog_category.csv', 'rb') as f:
reader = DictReader(f)
for row in reader:
category_lookup[row['id']] = BlogCategory.objects.get(title=row['name']).id
site_id = current_site_id()
user = User.objects.get(id=1)
publish_lookup = {'t': 2, 'f': 1}
with open('db_export/blog_entry.csv', 'rb') as f:
reader = DictReader(f)
for row in reader:
post = BlogPost.objects.create(
user=user,
site_id=site_id,
title=row['title'],
slug=slugify(unicode(row['slug'])),
allow_comments=False,
content=row['body'],
in_sitemap=False,
status=publish_lookup[row['published']],
publish_date=parse_datetime(row['pub_date'])
)
post.categories=[category_lookup[row['category_id']]]
post.save()
开发者ID:dzwarg,项目名称:zwarg_com,代码行数:34,代码来源:import_blog_entries.py
示例2: __init__
def __init__(self, *args, **kwargs):
super(TicketAdminForm, self).__init__(*args, **kwargs)
# tipologies is filtered by current site if 'tipologies' in
# self.fields. If field is read_only isn't in self.fields
# for field, related_name in ('t')
if "content" in self.fields:
self.fields["content"].required = True
self.fields["content"].widget.attrs["class"] = "mceEditor"
if "source" in self.fields:
self.fields["source"].required = True
try:
self.fields["source"].initial = Source.get_default_obj()
except Source.DoesNotExist:
pass
if not self.instance.pk:
site = Site.objects.get(pk=current_site_id())
for field, related_name in [("tipologies", "helpdesk_tipologies"), ("source", "helpdesk_sources")]:
if field in self.fields:
relate_manager = getattr(site, related_name, None)
if relate_manager:
self.fields[field].queryset = relate_manager.all()
# The next code is tricky for ensure compatibility with django 1.5
if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] < 6: # django 1.5
if self.instance.pk: # change form
for field in ["tipologies", "priority", "content"]:
del self.fields[field]
if len(args) > 0: # the form is bound
form_data = args[0]
for field in self._ohp_only_operators_fields:
# if current field is not in buond data whereas is in
# self.fields therefore user is an "requester". We then
# remove field from form fields (self.fields)
if field not in form_data and field in self.fields:
del self.fields[field]
开发者ID:TicketHelpdesk,项目名称:TicketHelpdesk,代码行数:35,代码来源:forms.py
示例3: host_theme_media_path
def host_theme_media_path (suffix): # (instance, filename):
"""
Returns the name of the theme associated with the given host,
suffixed by a string (typically a field name) - called by
upload_to in model.
Patterned after mezzanine.utils.sites.host_theme_path
Does not follow the specs here:
https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.FileField.upload_to
as Mezzanine has apparently broken this, by mapping upload_to into FileBrowseField.directory,
which is called without parms.
Solution: Use function references with a 'suffix' attr, for example:
from apps.utils import host_theme_media_path
...
slider_path = host_theme_media_path
slider_path.suffix = 'slider'
...
class Slide (Orderable):
...
image = FileField (
verbose_name =_("Image"),
upload_to = slider_path, # NOTE: no parens!
format = "Image", max_length = 255, null = True, blank = True)
UPDATE: attrs don't work, and it uses the last one set at module load time, the fn references are not first-class objects, only refs.
Just use a one-line call in the model, and pass is a suffix, eg:
def slider_path(): return host_theme_media_path ('slider')
QED. KISS principle.
"""
# Nope. need to use attr
#print 'FUNCTION NAME', host_theme_media_path.__name__
#suffix = instance.__class__.__name__.tolower()
#suffix = host_theme_media_path.__name__.split ('_') [-1]
#suffix = host_theme_media_path.suffix
if trace: print 'SUFFIX', suffix
# Set domain to None, which we'll then query for in the first
# iteration of HOST_THEMES. We use the current site_id rather
# than a request object here, as it may differ for admin users.
domain = None
for (host, theme) in settings.HOST_THEMES:
if trace: print 'HOST THEME', host, theme
if domain is None:
domain = Site.objects.get(id=current_site_id()).domain
if trace: print 'DOMAIN', domain
if host.lower() == domain.lower():
if theme:
if theme.startswith ('apps.'):
theme = theme [5:]
return os.path.join (theme, suffix) #, filename)
return ""
开发者ID:jowolf,项目名称:tlg,代码行数:60,代码来源:__init__.py
示例4: get_queryset
def get_queryset(self, request):
version_tracker_model = self.get_site().get_version_tracker_model()
site_pages = version_tracker_model.objects.filter(widgypage__site_id=current_site_id())
site_nodes = Node.objects.filter(versiontracker__in=site_pages)
# This query seems like it could get slow. If that's the case,
# something along these lines might be helpful:
# Node.objects.all().extra(
# tables=[
# '"widgy_node" AS "root"',
# 'widgy_versiontracker',
# 'widgy_mezzanine_widgypage',
# 'pages_page',
# ],
# where=[
# 'root.path = SUBSTR(widgy_node.path, 1, 4)',
# 'widgy_versiontracker.id = widgy_mezzanine_widgypage.root_node_id',
# 'pages_page.id = widgy_mezzanine_widgypage.page_ptr_id',
# 'pages_page.site_id = 1',
# ]
# )
qs = super(MultiSiteFormAdmin, self).get_queryset(request).filter(
_nodes__path__path_root__in=site_nodes.values_list('path'),
)
return qs
开发者ID:DjangoBD,项目名称:django-widgy,代码行数:25,代码来源:admin.py
示例5: __init__
def __init__(self, *args, **kwargs):
super(TicketAdminForm, self).__init__(*args, **kwargs)
# tipologies is filtered by current site if 'tipologies' in
# self.fields. If field is read_only isn't in self.fields
# for field, related_name in ('t')
if 'content' in self.fields:
self.fields['content'].required = True
self.fields['content'].widget.attrs['class'] = 'mceEditor'
if 'source' in self.fields:
self.fields['source'].required = True
try:
self.fields['source'].initial = models.Source.get_default_obj()
except models.Source.DoesNotExist:
pass
if not self.instance.pk:
site = Site.objects.get(pk=current_site_id())
for field, related_name in [('tipologies', 'helpdesk_tipologies'),
('source', 'helpdesk_sources')]:
if field in self.fields:
relate_manager = getattr(site, related_name, None)
if relate_manager:
if ('initial' in kwargs and
field == 'tipologies' and
'__tipology_pks' in kwargs['initial']):
tipology_pks = kwargs['initial']['__tipology_pks']
self.fields[field].queryset = (
relate_manager.filter(pk__in=tipology_pks))
else:
self.fields[field].queryset = relate_manager.all()
开发者ID:simodalla,项目名称:open-helpdesk,代码行数:29,代码来源:forms.py
示例6: handle_noargs
def handle_noargs(self, **options):
if "conf_setting" not in connection.introspection.table_names():
createdb.Command.execute(**{'no_data': True})
for group_name, permission_codenames in [HELPDESK_REQUESTERS,
HELPDESK_OPERATORS,
HELPDESK_ADMINS]:
group, created = Group.objects.get_or_create(name=group_name)
self.stdout.write('Group {} {}.\n'.format(
group.name, 'created' if created else 'already exist'))
for permission in permission_codenames:
group.permissions.add(Permission.objects.get(
content_type__app_label=permission.split('.')[0],
codename=permission.split('.')[1]))
self.stdout.write('Add permissions to {}: {}.\n\n'.format(
group.name, permission_codenames))
site = Site.objects.get(pk=current_site_id())
for code, title, icon in DEFAULT_SOURCES:
source, created = Source.objects.get_or_create(
code=code, defaults={'title': title, 'icon': icon})
if created:
source.sites.add(site)
开发者ID:TicketHelpdesk,项目名称:TicketHelpdesk,代码行数:25,代码来源:inithelpdesk.py
示例7: choices_for_request
def choices_for_request(self):
user = HelpdeskUser.objects.get(pk=self.request.user.pk)
if user.is_requester():
self.choices = self.choices.filter(requester=user)
if user.is_operator():
self.choices = self.choices.filter(site__id=current_site_id())
return super(TicketAutocomplete, self).choices_for_request()
开发者ID:elopedev,项目名称:open-helpdesk,代码行数:7,代码来源:autocomplete_light_registry.py
示例8: _can_edit_content
def _can_edit_content(self, request, obj):
if isinstance(obj, Content):
owners = obj.get_root().node.versiontracker_set.get().owners
any_owner_in_current_site = any(current_site_id() == o.site_id for o in owners)
return has_site_permission(request.user) and any_owner_in_current_site
else:
return True
开发者ID:sigmundv,项目名称:django-widgy,代码行数:7,代码来源:site.py
示例9: save_form
def save_form(self, request, form, change):
"""
Assigns the current site to the redirect when first created.
"""
obj = form.save(commit=False)
if not obj.site_id:
obj.site_id = current_site_id()
return super(SiteRedirectAdmin, self).save_form(request, form, change)
开发者ID:christianwgd,项目名称:mezzanine,代码行数:8,代码来源:admin.py
示例10: admin_dropdown_menu
def admin_dropdown_menu(context):
"""
Renders the app list for the admin dropdown menu navigation.
"""
context["dropdown_menu_app_list"] = admin_app_list(context["request"])
context["dropdown_menu_sites"] = list(Site.objects.all())
context["dropdown_menu_selected_site_id"] = current_site_id()
return context
开发者ID:Donneker,项目名称:mezzanine,代码行数:8,代码来源:mezzanine_tags.py
示例11: get_tipologies
def get_tipologies(n_tipologies):
from django.contrib.sites.models import Site
from .factories import CategoryFactory, TipologyFactory
from mezzanine.utils.sites import current_site_id
category = CategoryFactory()
site = Site.objects.get(pk=current_site_id())
return [
TipologyFactory(sites=(site,), category=category)
for i in range(0, n_tipologies)]
开发者ID:elopedev,项目名称:open-helpdesk,代码行数:9,代码来源:conftest.py
示例12: insert_trans_page
def insert_trans_page(self):
# Ignore gen_description field
# It causes the description field to not be encoded to unicode
if 'gen_description' in self.page_json:
self.page_json['gen_description'] = False
if type(self.page_content_model.__base__) != type(Page):
self.page_json['site_id'] = current_site_id()
self.page = self.page_content_model(**self.page_json)
self.page.save()
开发者ID:Appdynamics,项目名称:mezzanine-smartling,代码行数:9,代码来源:admin.py
示例13: save
def save(self, update_site=False, *args, **kwargs):
"""
Set the site to the current site when the record is first
created, or the ``update_site`` argument is explicitly set
to ``True``.
"""
if update_site or (self.id is None and self.site_id is None):
self.site_id = current_site_id()
super(SiteRelated, self).save(*args, **kwargs)
开发者ID:JPWKU,项目名称:mezzanine,代码行数:9,代码来源:models.py
示例14: create_site_permission
def create_site_permission(sender, **kw):
sender_name = "%s.%s" % (sender._meta.app_label, sender._meta.object_name)
if sender_name.lower() != user_model_name.lower():
return
user = kw["instance"]
if user.is_staff and not user.is_superuser:
perm, created = SitePermission.objects.get_or_create(user=user)
if created or perm.sites.count() < 1:
perm.sites.add(current_site_id())
开发者ID:JPWKU,项目名称:mezzanine,代码行数:9,代码来源:models.py
示例15: save
def save(self, *args, **kwargs):
"""
Set the current site ID, and ``is_public`` based on the setting
``COMMENTS_DEFAULT_APPROVED``.
"""
if not self.id:
self.is_public = settings.COMMENTS_DEFAULT_APPROVED
self.site_id = current_site_id()
super(ThreadedComment, self).save(*args, **kwargs)
开发者ID:christianwgd,项目名称:mezzanine,代码行数:9,代码来源:models.py
示例16: get_query_set
def get_query_set(self):
if not self.__is_validated:
try:
# Django <= 1.6
self._validate_field_name()
except AttributeError:
pass
lookup = {self.__field_name + "__id__exact": current_site_id()}
return super(DjangoCSM, self).get_query_set().filter(**lookup)
开发者ID:jMyles,项目名称:mezzanine,代码行数:9,代码来源:managers.py
示例17: cache_key_prefix
def cache_key_prefix(request):
"""
Cache key for Mezzanine's cache middleware. Adds the current
device and site ID.
"""
return "%s.%s.%s." % (
settings.CACHE_MIDDLEWARE_KEY_PREFIX,
current_site_id(),
device_from_request(request) or "default",
)
开发者ID:skevy,项目名称:mezzanine,代码行数:10,代码来源:cache.py
示例18: get_or_create_user
def get_or_create_user(self, username, ldap_user):
user, create = super(MezzanineLDAPBackend, self).get_or_create_user(
username, ldap_user)
if create:
sp, _ = SitePermission.objects.get_or_create(user=user)
try:
sp.sites.add(Site.objects.get(pk=current_site_id()))
except Site.DoesNotExist:
pass
return user, create
开发者ID:simodalla,项目名称:pympa-utils,代码行数:10,代码来源:ldap_backends.py
示例19: upsert_relational_objects
def upsert_relational_objects(self):
for related_obj_name in self.related_object_names:
if related_obj_name == 'page_type':
continue
related_obj_model = get_content_model(related_obj_name)
# Is it a m2m object?
m2m_field_names = self.many_to_many_field_names(related_obj_model)
if len(m2m_field_names) > 0:
for m2m_fldname in m2m_field_names:
for m2m_json_obj in self.smrt_json[related_obj_name]:
# Attempt to find m2m object that exists
if 'id' in m2m_json_obj:
del m2m_json_obj['id']
m2m_obj = self.find_many_to_many_object(m2m_json_obj, related_obj_model)
if not m2m_obj:
site = Site.objects.get(id=current_site_id())
try:
m2m_json_obj['site'] = site
m2m_obj = related_obj_model(**m2m_json_obj)
m2m_obj.save()
del m2m_json_obj['site']
except TypeError:
del m2m_json_obj['site']
m2m_obj = related_obj_model(**m2m_json_obj)
m2m_obj.save()
getattr(self.page, m2m_fldname).add(m2m_obj)
else:
foreign_key_field = self.get_foreign_key_field(related_obj_model)
for foreign_json_object in self.smrt_json[related_obj_name]:
foreign_json_object[foreign_key_field] = self.page
self.upsert_follow_objects(foreign_json_object, related_obj_model)
try:
foreign_json_object['site'] = current_site_id()
fk_obj = related_obj_model(**foreign_json_object)
fk_obj.save()
except TypeError:
del foreign_json_object['site']
fk_obj = related_obj_model(**foreign_json_object)
fk_obj.save()
if foreign_key_field in foreign_json_object:
del foreign_json_object[foreign_key_field]
self.remove_related_follow_fields(foreign_json_object, related_obj_model)
开发者ID:Appdynamics,项目名称:mezzanine-smartling,代码行数:42,代码来源:admin.py
示例20: handle
def handle(self, *args, **options):
if options['truncate']:
print 'Deleting Gallery Categories:'
for gallery in Gallery.objects.filter(~Q(title='Gallery')):
print '\t{}'.format(gallery.title)
Gallery.objects.filter(~Q(title='Gallery')).delete()
site_id = current_site_id()
child_galleries = []
parent_lookup = {
'': Gallery.objects.get(title='Gallery').id
}
publish_lookup = {'t': 2, 'f': 1}
with open('db_export/gallery_category.csv', 'rb') as f:
reader = DictReader(f)
for row in reader:
options = {
'site_id':site_id,
'title':row['name'],
'content':row['description'],
'in_sitemap':True,
'in_menus': '',
'status':publish_lookup[row['published']]
}
if row['parent_id'] in parent_lookup:
options['parent_id'] = parent_lookup[row['parent_id']]
else:
options['parent_id'] = row['parent_id']
child_galleries.append(options)
continue
print 'Creating Gallery {}'.format(row['name'])
g = Gallery.objects.create(**options)
parent_lookup[row['id']] = g.id
# recursively add new galleries to parents that didn't exist in N-1 pass
while len(child_galleries) > 0:
orphaned = []
for child in child_galleries:
if child['parent_id'] in parent_lookup:
row_id = child['parent_id']
child['parent_id'] = Gallery.objects.get(id=parent_lookup[row_id]).id
print 'Creating Gallery {}'.format(child['title'])
g = Gallery.objects.create(**child)
parent_lookup[row_id] = g.id
else:
orphaned.append(child)
child_galleries = orphaned
开发者ID:dzwarg,项目名称:zwarg_com,代码行数:54,代码来源:import_gallery_categories.py
注:本文中的mezzanine.utils.sites.current_site_id函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论