Here are the examples of the python api django.contrib.contenttypes.models.ContentType.objects.get taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
84 Examples
3
Source : exportjob.py
with GNU Lesser General Public License v3.0
from auto-mat
with GNU Lesser General Public License v3.0
from auto-mat
def get_content_type(self):
if not self._content_type:
self._content_type = ContentType.objects.get(
app_label=self.app_label, model=self.model,
)
return self._content_type
def get_queryset(self):
3
Source : user_attendance.py
with GNU General Public License v3.0
from auto-mat
with GNU General Public License v3.0
from auto-mat
def notifications(self):
user_content_type = ContentType.objects.get(app_label="auth", model="user")
user_attendance_content_type = ContentType.objects.get(
app_label="dpnk", model="userattendance"
)
notifications = self.userprofile.user.notifications.filter(
Q(
actor_content_type=user_content_type.id,
actor_object_id=self.userprofile.user.id,
)
| Q(
actor_content_type=user_attendance_content_type.id,
actor_object_id=self.id,
),
)
return notifications
@receiver(post_save, sender=UserAttendance)
3
Source : tasks.py
with GNU General Public License v3.0
from auto-mat
with GNU General Public License v3.0
from auto-mat
def touch_items(self, pks, object_app_label, object_model_name):
for pk in pks:
content_type = contenttypes.models.ContentType.objects.get(
app_label=object_app_label, model=object_model_name
)
denorm.models.DirtyInstance.objects.create(
content_type=content_type,
object_id=pk,
)
denorm.flush()
return len(pks)
@shared_task(bind=True)
3
Source : views.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def get_queryset(self):
flight_content_type = ContentType.objects.get(
app_label='flights', model='flight')
qs = Tag.objects.filter(
taggit_taggeditem_items__content_type=flight_content_type)
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs.distinct().order_by('name')
class MatingChartView(TemplateView):
3
Source : contracts.py
with GNU Affero General Public License v3.0
from elixir-luxembourg
with GNU Affero General Public License v3.0
from elixir-luxembourg
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
the_user = self.request.user
can_edit = the_user.can_edit_contract(self.object)
context['can_edit'] = can_edit
pk = ContentType.objects.get(model='contract').pk
context['content_type'] = pk
context['object_id'] = self.object.pk
context['datafiles'] = [d for d in self.object.legal_documents.all()]
return context
class ContractEditView(UpdateView):
3
Source : projects.py
with GNU Affero General Public License v3.0
from elixir-luxembourg
with GNU Affero General Public License v3.0
from elixir-luxembourg
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['is_admin'] = self.request.user.is_admin_of_project(self.object)
context['can_edit'] = self.request.user.can_edit_project(self.object)
context['company_name'] = COMPANY
pk = ContentType.objects.get(model='project').pk
context['content_type'] = pk
context['object_id'] = self.object.pk
context['datafiles'] = [d for d in self.object.legal_documents.all()]
return context
class ProjectEditView(CheckerMixin, UpdateView):
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def edit_comment(before_text: str, comment_obj: Comment, user: User, reason):
return ModerationLogEntry.objects.create(
user=user,
action="Edited comment",
reason=reason,
change=json.dumps(
{
"before": before_text,
"after": comment_obj.text_to_plain_text,
}
),
content_type=ContentType.objects.get(app_label="tade", model="comment"),
object_id=str(comment_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def delete_comment(comment_obj: Comment, user: User, reason):
return ModerationLogEntry.objects.create(
user=user,
action="Deleted comment",
reason=reason,
content_type=ContentType.objects.get(app_label="tade", model="comment"),
object_id=str(comment_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def edit_story_title(before_text: str, story_obj: Story, user: User, reason):
return ModerationLogEntry.objects.create(
user=user,
action=f"Set story title to {story_obj.title}",
reason=reason,
change=json.dumps(
{
"before": before_text,
"after": story_obj.title,
}
),
content_type=ContentType.objects.get(app_label="tade", model="story"),
object_id=str(story_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def edit_story_desc(before_text: str, story_obj: Story, user: User, reason):
return ModerationLogEntry.objects.create(
user=user,
action=f"Set story description to {story_obj.description}",
reason=reason,
change=json.dumps(
{
"before": before_text,
"after": story_obj.description,
}
),
content_type=ContentType.objects.get(app_label="tade", model="story"),
object_id=str(story_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def edit_story_url(before_text: str, story_obj: Story, user: User, reason):
return ModerationLogEntry.objects.create(
user=user,
action=f"Set story url to {story_obj.url}",
reason=reason,
change=json.dumps(
{
"before": before_text,
"after": story_obj.url,
}
),
content_type=ContentType.objects.get(app_label="tade", model="story"),
object_id=str(story_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def edit_story_cw(before_text: str, story_obj: Story, user: User, reason):
return ModerationLogEntry.objects.create(
user=user,
action=f"""Set story's content warning to "{story_obj.content_warning}" """,
reason=reason,
change=json.dumps(
{
"before": before_text,
"after": story_obj.content_warning,
}
),
content_type=ContentType.objects.get(app_label="tade", model="story"),
object_id=str(story_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def edit_story_pubdate(
before_date: datetime.datetime, story_obj: Story, user: User, reason
):
return ModerationLogEntry.objects.create(
user=user,
action=f"Set story's publish date to {story_obj.publish_date}",
reason=reason,
change=json.dumps(
{
"before": before_date,
"after": story_obj.publish_date,
}
),
content_type=ContentType.objects.get(app_label="tade", model="story"),
object_id=str(story_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def edit_story_tags(tags_before, story_obj: Story, user: User, reason):
tags_after = list(story_obj.tags.all())
return ModerationLogEntry.objects.create(
user=user,
action=f"""Edited story tags from ("{'", "'.join(t.name for t in tags_before)}") to ("{'", "'.join(t.name for t in tags_after)}")""",
reason=reason,
change=json.dumps(
{
"before": [t.id for t in tags_before],
"after": [t.id for t in tags_after],
}
),
content_type=ContentType.objects.get(app_label="tade", model="story"),
object_id=str(story_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def edit_story_kind(kinds_before, story_obj: Story, user: User, reason):
kinds_after = list(story_obj.kind.all())
return ModerationLogEntry.objects.create(
user=user,
action=f"""Edited story kind from ("{'", "'.join(k.name for k in kinds_before)}") to ("{'", "'.join(k.name for k in kinds_after)}")""",
reason=reason,
change=json.dumps(
{
"before": [k.id for k in kinds_before],
"after": [k.id for k in kinds_after],
}
),
content_type=ContentType.objects.get(app_label="tade", model="story"),
object_id=str(story_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def delete_story(story_obj: Story, user: User, reason):
return ModerationLogEntry.objects.create(
user=user,
action="Deleted story",
reason=reason,
content_type=ContentType.objects.get(app_label="tade", model="story"),
object_id=str(story_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def edit_tag_name(name_before: str, tag_obj: Tag, user: User, reason):
return ModerationLogEntry.objects.create(
user=user,
action=f"""Edited tag name from "{name_before}" to "{tag_obj.name}" """,
reason=reason,
change=json.dumps(
{
"before": name_before,
"after": tag_obj.name,
}
),
content_type=ContentType.objects.get(app_label="tade", model="tag"),
object_id=str(tag_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def edit_tag_parents(parents_before, tag_obj: Tag, user: User, reason):
parents_after = list(tag_obj.parents.all())
return ModerationLogEntry.objects.create(
user=user,
action=f"""Edited tag parents from ("{'", "'.join(t.name for t in parents_before)}") to ("{'", "'.join(t.name for t in parents_after)}")""",
reason=reason,
change=json.dumps(
{
"before": [t.id for t in parents_before],
"after": [t.id for t in parents_after],
}
),
content_type=ContentType.objects.get(app_label="tade", model="tag"),
object_id=str(tag_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def create_tag(tag_obj: Tag, user: User):
return ModerationLogEntry.objects.create(
user=user,
action=f"""Created tag: {tag_obj.name} with parents: ("{'", "'.join(t.name for t in tag_obj.parents.all())}")""",
reason="",
change="",
content_type=ContentType.objects.get(app_label="tade", model="tag"),
object_id=str(tag_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def changed_user_status(user_obj: User, user: User, action, reason):
return ModerationLogEntry.objects.create(
user=user,
action=action,
reason=reason,
content_type=ContentType.objects.get(app_label="tade", model="user"),
object_id=str(user_obj.pk),
)
@staticmethod
3
Source : moderation.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def changed_story_status(story_obj: Story, user: User, action: str, reason: str):
return ModerationLogEntry.objects.create(
user=user,
action=action,
reason=reason,
content_type=ContentType.objects.get(app_label="tade", model="story"),
object_id=str(story_obj.pk),
)
def get_edited_object(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_verbose_name(self):
company_type = ContentType.objects.get(app_label='i18n', model='company')
with translation.override('en'):
self.assertEqual(six.text_type(company_type), 'Company')
with translation.override('fr'):
self.assertEqual(six.text_type(company_type), 'Société')
3
Source : django_db_util.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def remove_content_type(app_label, model_name):
"""
Delete from the Django ContentType table, as applications delete
old unused tables.
See django.contrib.contenttypes.management.update_contenttypes().
If applications don't delete their stale content types, users will
be prompted with a question as they run syncdb.
"""
try:
ct = ContentType.objects.get(app_label=app_label, model=model_name.lower())
ct.delete()
except ContentType.DoesNotExist:
pass
3
Source : models.py
with BSD 2-Clause "Simplified" License
from getmetamapper
with BSD 2-Clause "Simplified" License
from getmetamapper
def get_content_type_from_name(cls, model):
model = model.lower()
if model not in Comment.SUPPORTED_MODELS:
raise ValueError('That resource does not support custom fields.')
return ContentType.objects.get(model=model)
@classmethod
3
Source : models.py
with BSD 2-Clause "Simplified" License
from getmetamapper
with BSD 2-Clause "Simplified" License
from getmetamapper
def get_content_type_from_name(cls, model):
model = model.lower()
if model not in CustomField.SUPPORTED_MODELS:
return None
return ContentType.objects.get(model=model)
@property
3
Source : sites.py
with BSD 3-Clause "New" or "Revised" License
from GrappleGQL
with BSD 3-Clause "New" or "Revised" License
from GrappleGQL
def resolve_pages(self, info, **kwargs):
pages = WagtailPage.objects.in_site(self).live().public().specific()
content_type = kwargs.pop("content_type", None)
if content_type:
app_label, model = content_type.strip().lower().split(".")
try:
ctype = ContentType.objects.get(app_label=app_label, model=model)
except ContentType.DoesNotExist:
return (
WagtailPage.objects.none()
) # something not quite right here, bail out early
else:
pages = pages.filter(content_type=ctype)
return resolve_queryset(pages, info, **kwargs)
def resolve_page(self, info, **kwargs):
3
Source : views.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def referenced_types(request):
content_types = BibliographyItem.objects.exclude(
content_type=None
).order_by().values_list(
'content_type'
).distinct().annotate(num=Count('content_type')).order_by('-num')
return render(request, 'bibliography/referenced_types.html', {
'types': [
(ContentType.objects.get(pk=type_id), count)
for type_id, count in content_types
]
})
def referenced_objects(request, content_type_id):
3
Source : views.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def referenced_objects(request, content_type_id):
content_type = ContentType.objects.get(pk=content_type_id)
object_ids = BibliographyItem.objects.filter(
content_type=content_type_id
).order_by().values_list('object_id').distinct().annotate(
num=Count('object_id')
).order_by('-num')
return render(request, 'bibliography/referenced_objects.html', {
'title': content_type._meta.verbose_name,
'content_type_id': content_type_id,
'objects': [
(content_type.get_object_for_this_type(id=object_id), count)
for object_id, count in object_ids
]
})
def referencing_pages(request, content_type_id, object_id):
3
Source : views.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def referencing_pages(request, content_type_id, object_id):
content_type = ContentType.objects.get(pk=content_type_id)
obj = content_type.get_object_for_this_type(id=object_id)
page_ids = BibliographyItem.objects.filter(
content_type=content_type_id,
object_id=object_id
).values_list('page', flat=True)
pages = Page.objects.filter(pk__in=page_ids)
return render(request, 'bibliography/referencing_pages.html', {
'title': obj.__str__(),
'pages': pages
})
3
Source : handlers.py
with GNU General Public License v3.0
from jonaswinkler
with GNU General Public License v3.0
from jonaswinkler
def set_log_entry(sender, document=None, logging_group=None, **kwargs):
ct = ContentType.objects.get(model="document")
user = User.objects.get(username="consumer")
LogEntry.objects.create(
action_flag=ADDITION,
action_time=timezone.now(),
content_type=ct,
object_id=document.pk,
user=user,
object_repr=document.__str__(),
)
def add_to_index(sender, document, **kwargs):
3
Source : test_api_views.py
with MIT License
from LowerDeez
with MIT License
from LowerDeez
def setUp(self):
self.content_type = ContentType.objects.get(model="user")
self.username = 'john'
self.password = 'secret123'
self.user = User.objects.create_user(
username=self.username,
password=self.password,
email='[email protected]'
)
self.test_user = User.objects.create(username='test')
self.like = toggle(
user=self.user,
content_type=self.content_type,
object_id=self.test_user.pk
)[0]
def tearDown(self):
3
Source : test_models.py
with MIT License
from LowerDeez
with MIT License
from LowerDeez
def setUp(self):
self.user_1 = User.objects.create(username="user 1")
self.user_2 = User.objects.create(username="user 2")
self.content_type = ContentType.objects.get(model="user")
def tearDown(self):
3
Source : test_tags.py
with MIT License
from LowerDeez
with MIT License
from LowerDeez
def setUp(self):
self.user = User.objects.create(username="user")
self.users = []
for i in range(6):
self.users.append(
User.objects.create(username=str(i))
)
Like.objects.create(
sender=self.user,
content_type=ContentType.objects.get(model="user"),
object_id=self.users[0].pk
)
def test_likes_count(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_verbose_name(self):
company_type = ContentType.objects.get(app_label='i18n', model='company')
with translation.override('en'):
self.assertEqual(six.text_type(company_type), 'Company')
with translation.override('fr'):
self.assertEqual(six.text_type(company_type), 'Société')
def test_field_override(self):
3
Source : django_db_util.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def remove_content_type(app_label, model_name):
"""
Delete from the Django ContentType table, as applications delete
old unused tables.
See django.contrib.contenttypes.management.update_contenttypes().
If applications don't delete their stale content types, users will
be prompted with a question as they run syncdb.
"""
try:
ct = ContentType.objects.get(app_label=app_label,
model=model_name.lower())
ct.delete()
except ContentType.DoesNotExist:
pass
3
Source : filters.py
with MIT License
from propublica
with MIT License
from propublica
def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
"""
Model = model_admin.model
meta_name = "%smetadata" % (Model._meta.object_name)
ct = ContentType.objects.get(
app_label="django_models_from_csv", model=meta_name
)
tags = Tag.objects.filter(
taggit_taggeditem_items__content_type=ct
).values_list("name", "slug").distinct()
return tags
def queryset(self, request, queryset):
3
Source : permissions.py
with MIT License
from propublica
with MIT License
from propublica
def get_permission_models():
Permission = ContentType.objects.get(
app_label="auth", model="permission"
).model_class()
Group = ContentType.objects.get(
app_label="auth", model="group"
).model_class()
return Permission, Group
def build_tag_permission_group():
3
Source : updater.py
with MIT License
from propublica
with MIT License
from propublica
def user_has_access(content_type, requestor):
Permission = ContentType.objects.get(
app_label="auth", model="permission"
).model_class()
logger.debug("Permission Model: %s" % str(Permission))
logger.debug("Requestor ID: %s" % (requestor.pk))
perms = Permission.objects.filter(
content_type=content_type,
codename__startswith="change_",
user__pk=requestor.pk
).count()
logger.debug("Matching permission groups: %s" % (perms))
if perms:
return True
return False
def field_updater(request):
3
Source : cache.py
with GNU General Public License v2.0
from puncoder
with GNU General Public License v2.0
from puncoder
def cached_entities(ctype_name):
'''
Some entities are frequently used.\n
Cache them for reuse.\n
Retrieve using model names.
'''
ctype_key = 'ctt_type_' + ctype_name
c_type = cache.get(ctype_key)
if not c_type:
c_type = ContentType.objects.get(model__iexact=ctype_name)
cache.set(ctype_key, c_type)
model_class = c_type.model_class()
key = 'cached_' + ctype_name
entities = cache.get(key)
if not entities:
entities = model_class._default_manager.all()
cache.set(key, entities)
return entities
3
Source : base.py
with MIT License
from Radi85
with MIT License
from Radi85
def _create_data(self):
self.user = User.objects.create_user(username="tester-1")
self.post = Post.objects.create(
author=self.user,
title="post 3",
body="third post body"
)
content_type = ContentType.objects.get(model='post')
self.ct_object = content_type.get_object_for_this_type(id=self.post.id)
class BaseCommentMixinTest(BaseCommentTest):
3
Source : utils.py
with MIT License
from Radi85
with MIT License
from Radi85
def get_model_obj(app_name, model_name, model_id):
content_type = ContentType.objects.get(app_label=app_name, model=model_name.lower())
model_object = content_type.get_object_for_this_type(id=model_id)
return model_object
def is_gravatar_enabled():
3
Source : utils.py
with MIT License
from Radi85
with MIT License
from Radi85
def get_profile_content_type():
profile_app_name = getattr(settings, 'PROFILE_APP_NAME', None)
profile_model_name = getattr(settings, 'PROFILE_MODEL_NAME', None)
if not profile_app_name or not profile_model_name:
return None
try:
content_type = ContentType.objects.get(
app_label=profile_app_name,
model=profile_model_name.lower()
)
except ContentType.DoesNotExist:
return None
return content_type
def get_profile_instance(user):
3
Source : validators.py
with MIT License
from Radi85
with MIT License
from Radi85
def validate_content_type_object(self, app_name, model_name):
try:
ct_object = ContentType.objects.get(model=model_name, app_label=app_name)
except ContentType.DoesNotExist:
self.error = ContentTypeError.MODEL_NAME_INVALID.format(model_name=model_name)
raise CommentBadRequest(self.error)
return ct_object
def validate_model_id(self, model_id):
3
Source : acl.py
with Apache License 2.0
from silverbackhq
with Apache License 2.0
from silverbackhq
def get_content_type(self, label, model):
try:
content_type = ContentType.objects.get(app_label=label, model=model)
return False if content_type.pk is None else content_type
except Exception:
return False
def get_user_content_type(self):
3
Source : acl.py
with Apache License 2.0
from silverbackhq
with Apache License 2.0
from silverbackhq
def get_content_type_id(self, label, model):
try:
content_type = ContentType.objects.get(app_label=label, model=model)
return False if content_type.pk is None else content_type.id
except Exception:
return False
def truncate_default_permissions(self):
3
Source : forms.py
with Apache License 2.0
from stormsha
with Apache License 2.0
from stormsha
def clean(self):
# 判断用户是否登陆
if self.user.is_authenticated:
self.cleaned_data['user'] = self.user
else:
raise forms.ValidationError('用户尚未登陆')
content_type = self.cleaned_data['content_type']
object_id = self.cleaned_data['object_id']
try:
model_class = ContentType.objects.get(model=content_type).model_class()
model_obj = model_class.objects.get(pk=object_id)
self.cleaned_data['content_object'] = model_obj
except ObjectDoesNotExist:
raise forms.ValidationError('评论对象不存在')
return self.cleaned_data
def clean_reply_comment_id(self):
3
Source : tests.py
with MIT License
from theriverman
with MIT License
from theriverman
def setUp(self):
ct = ContentType.objects.get(app_label='auth', model='user') # PublicAttachment is generic so this is needed
with open(test_file_path, 'rb') as f:
# noinspection PyUnresolvedReferences
self.obj = PublicAttachment.objects.create()
self.obj.ct = ct
self.obj.object_id = 1 # we associate this uploaded file to user with pk=1
self.obj.file.save(name=self.filename, content=File(f), save=True)
def test_url_generation_works(self):
3
Source : api.py
with BSD 3-Clause "New" or "Revised" License
from torchbox
with BSD 3-Clause "New" or "Revised" License
from torchbox
def get_object(self):
app_label, model = self.request.GET["content_type"].split(".")
content_type = ContentType.objects.get(app_label=app_label, model=model)
page_preview = PagePreview.objects.get(
content_type=content_type, token=self.request.GET["token"]
)
page = page_preview.as_page()
if not page.pk:
# fake primary key to stop API URL routing from complaining
page.pk = 0
return page
api_router.register_endpoint("page_preview", PagePreviewAPIEndpoint)
3
Source : administration.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def _get_recipients_from_choices(self):
tags = self.object.managed_tags.all()
assignments = CosinnusManagedTagAssignment.objects.filter(managed_tag__in=tags)
group_type = ContentType.objects.get(
app_label='cosinnus', model='cosinnusgroup')
profile_type = ContentType.objects.get(
app_label='cosinnus', model='userprofile')
group_ids = assignments.filter(
content_type=group_type).values_list('object_id', flat=True)
profile_ids = assignments.filter(
content_type=profile_type).values_list('object_id', flat=True)
tag_users = get_user_model().objects.filter(
Q(cosinnus_groups__id__in=group_ids) | Q(cosinnus_profile__id__in=profile_ids)).distinct()
return tag_users
def _copy_newsletter(self):
0
Source : views.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
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 Http404(
_("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 Http404(
_("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 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://', 'https://', '//')):
return HttpResponseRedirect(absurl)
# Otherwise, we need to introspect the object's relationships for a
# relation to the Site object
object_domain = None
if apps.is_installed('django.contrib.sites'):
Site = apps.get_model('sites.Site')
opts = obj._meta
# First, look for a many-to-many relationship to Site.
for field in opts.many_to_many:
if field.remote_field.model 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.remote_field and field.remote_field.model is Site:
try:
site = getattr(obj, field.name)
except Site.DoesNotExist:
continue
if site is not None:
object_domain = site.domain
if object_domain is not None:
break
# Fall back to the current site (if possible).
if object_domain is None:
try:
object_domain = Site.objects.get_current(request).domain
except Site.DoesNotExist:
pass
else:
# Fall back to the current request's site.
object_domain = RequestSite(request).domain
# 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.scheme
return HttpResponseRedirect('%s://%s%s' % (protocol, object_domain, absurl))
else:
return HttpResponseRedirect(absurl)
See More Examples