django.contrib.contenttypes.models.ContentType.objects.get_for_model

Here are the examples of the python api django.contrib.contenttypes.models.ContentType.objects.get_for_model taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: pinax-wiki
Source File: receivers.py
View license
def handle_object_save(sender, **kwargs):
    created = kwargs.pop("created")
    obj = kwargs.pop("instance")
    if created:
        Wiki.objects.create(
            content_type=ContentType.objects.get_for_model(obj),
            object_id=obj.pk
        )

Example 2

Project: OpenSlides
Source File: signals.py
View license
def listen_to_related_object_post_delete(sender, instance, **kwargs):
    """
    Receiver function to delete agenda items. It is connected to the signal
    django.db.models.signals.post_delete during app loading.
    """
    if hasattr(instance, 'get_agenda_title'):
        content_type = ContentType.objects.get_for_model(instance)
        try:
            Item.objects.get(object_id=instance.pk, content_type=content_type).delete()
        except Item.DoesNotExist:
            # Item does not exist so we do not have to delete it.
            pass

Example 3

Project: django-hitcount
Source File: models.py
View license
    @property
    def hit_count(self):
        ctype = ContentType.objects.get_for_model(self.__class__)
        hit_count, created = HitCount.objects.get_or_create(
            content_type=ctype, object_pk=self.pk)
        return hit_count

Example 4

Project: dre
Source File: views.py
View license
def get_bookmark( user, obj ):
    content_type = ContentType.objects.get_for_model(obj)
    try:
        bookmark = Bookmark.objects.get( user = user,
                                         object_id  = obj.id,
                                         content_type = content_type )
        return bookmark
    except ObjectDoesNotExist:
        return False

Example 5

Project: timtec
Source File: views.py
View license
    def get_context_data(self, **kwargs):
        context = super(LessonDetailView, self).get_context_data(**kwargs)
        unit_content_type = ContentType.objects.get_for_model(Unit)
        course = self.object.course
        lessons = list(course.public_lessons)
        if lessons and self.object != lessons[-1]:
            index = lessons.index(self.object)
            context['next_url'] = reverse_lazy('lesson',
                                               args=[course.slug,
                                                     lessons[index + 1].slug])
        context['unit_content_type_id'] = unit_content_type.id
        return context

Example 6

Project: unisubs
Source File: forms.py
View license
    def __init__(self, obj, *args, **kwargs):
        if obj:
            ct = ContentType.objects.get_for_model(obj)
            kwargs.setdefault('initial', {})
            kwargs['initial']['object_pk'] = obj.pk
            kwargs['initial']['content_type'] = ct.pk
        super(CommentForm, self).__init__(*args, **kwargs)
        self.fields['reply_to'].widget = forms.HiddenInput()
        self.fields['object_pk'].widget = forms.HiddenInput()
        self.fields['content_type'].widget = forms.HiddenInput()

Example 7

Project: django-role-permissions
Source File: roles.py
View license
    @classmethod
    def get_or_create_permissions(cls, permission_names):
        user_ct = ContentType.objects.get_for_model(get_user_model())
        permissions = list(Permission.objects.filter(
            content_type=user_ct, codename__in=permission_names).all())

        if len(permissions) != len(permission_names):
            for permission_name in permission_names:
                permission, created = Permission.objects.get_or_create(
                    content_type=user_ct, codename=permission_name)
                if created:
                    permissions.append(permission)

        return permissions

Example 8

Project: django-gatekeeper
Source File: models.py
View license
    def get_for_instance(self, obj):
        ct = ContentType.objects.get_for_model(obj.__class__)
        try:
            mo = ModeratedObject.objects.get(content_type=ct, object_id=obj.pk)
            return mo
        except ModeratedObject.DoesNotExist:
            pass

Example 9

Project: django-tumblelog
Source File: base.py
View license
    def save(self, *args, **kwargs):
        """
        Overrides save method to either creates or updates the correspondant
        Post object when object is saved.
        """
        super(BasePostType, self).save(*args, **kwargs)
        content_type = ContentType.objects.get_for_model(self)
        post, created = Post.objects.get_or_create(
            post_type=content_type,
            object_id=self.id
        )
        post.status = self.status
        post.date_added = self.date_added
        post.date_modified = self.date_modified
        post.date_published = self.date_published
        post.slug = self.slug
        post.author = self.author
        post.save()

Example 10

Project: django-completion
Source File: db_backend.py
View license
    def store_object(self, obj, data):
        """
        Given a title & some data that needs to be stored, make it available
        for autocomplete via the suggest() method
        """
        self.remove_object(obj, data)
        
        title = data['title']
        for partial_title in partial_complete(title):
            key = create_key(partial_title)
            autocomplete_obj = AutocompleteObject(
                title=key,
                object_id=obj.pk,
                content_type=ContentType.objects.get_for_model(obj),
                pub_date=data['pub_date'],
                data=data['data']
            )
            autocomplete_obj.save()
            autocomplete_obj.sites = data['sites']

Example 11

Project: portal
Source File: test_models.py
View license
    def test_str(self):
        """Test Comment object str/unicode representation"""
        news = News.objects.create(slug="foonews", title="Bar",
                                   author=self.systers_user,
                                   content="Hi there!",
                                   community=self.community)
        related_object_type = ContentType.objects.get_for_model(news)
        comment = Comment.objects.create(author=self.systers_user, body="Bar",
                                         object_id=news.id,
                                         content_type=related_object_type)
        self.assertEqual(str(comment),
                         "Comment by foo to Bar of Foo Community")

Example 12

Project: django-flaggit
Source File: flaggit_tags.py
View license
    def render(self, context):
        obj = self.obj.resolve(context)
        content_type = ContentType.objects.get_for_model(obj)
        return template.loader.render_to_string(self.tpl, {
            'object': obj,
            'content_type': content_type,
        }, context_instance=context)

Example 13

Project: django-notification
Source File: models.py
View license
    def all_for(self, observed, signal):
        """
        Returns all ObservedItems for an observed object,
        to be sent when a signal is emited.
        """
        content_type = ContentType.objects.get_for_model(observed)
        observed_items = self.filter(content_type=content_type, object_id=observed.id, signal=signal)
        return observed_items

Example 14

Project: HealthStarter
Source File: fields.py
View license
    def get_content_type(self):
        """
        Return the content type associated with this field's model.
        """
        return ContentType.objects.get_for_model(self.model,
                                                 for_concrete_model=self.for_concrete_model)

Example 15

Project: django-goflow
Source File: models.py
View license
    def create_authorized_group_if_not_exists(self):
        g, created = Group.objects.get_or_create(name=self.title)
        if created:
            ptype = ContentType.objects.get_for_model(Process)
            cip = Permission.objects.get(content_type=ptype, codename='can_instantiate')
            g.permissions.add(cip)

Example 16

Project: oioioi
Source File: tests.py
View license
    def test_admin_changelist_view(self):
        self.client.login(username='test_admin')

        self.client.get('/c/c/')  # 'c' becomes the current contest
        url = reverse('oioioiadmin:problems_problem_changelist')

        response = self.client.get(url)
        self.assertContains(response, 'Sum')

        self.client.login(username='test_user')
        check_not_accessible(self, url)

        user = User.objects.get(username='test_user')
        content_type = ContentType.objects.get_for_model(Problem)
        permission = Permission.objects.get(content_type=content_type,
                                            codename='problems_db_admin')
        user.user_permissions.add(permission)
        response = self.client.get(url)
        self.assertContains(response, 'Sum')

Example 17

Project: sikteeri
Source File: models.py
View license
def _get_logs(self):
    '''Gets the log entries related to this object.
    Getter to be used as property instead of GenericRelation'''
    my_class = self.__class__
    ct = ContentType.objects.get_for_model(my_class)
    object_logs = ct.logentry_set.filter(object_id=self.id)
    return object_logs

Example 18

Project: django-flatcontent
Source File: test_admin.py
View license
    def _admin_url(self, model, obj=None):
        """ Utility method to get an admin url for a model """
        content_type = ContentType.objects.get_for_model(model)
        uri = "admin:%s_%s" % (content_type.app_label, content_type.model)
        args = ()
        if obj and not obj.id:
            uri += '_add'
        elif obj:
            uri += '_change'
            args = (obj.id,)
        else:
            uri += '_changelist'
        return reverse(uri, args=args)

Example 19

Project: django-sellmo
Source File: polymorphism.py
View license
    def get_child_type_choices(self, request, action):
        """
        Return a list of polymorphic types for which the user has the permission to perform the given action.
        """
        choices = []
        for model, _ in self.get_child_models():
            perm_function_name = 'has_{0}_permission'.format(action)
            model_admin = self._get_real_admin_by_model(model)
            perm_function = getattr(model_admin, perm_function_name)
            if not perm_function(request):
                continue
            ct = ContentType.objects.get_for_model(model, for_concrete_model=False)
            choices.append((ct.id, model._meta.verbose_name))
        return choices

Example 20

Project: Wooey
Source File: wooey_tags.py
View license
@register.filter
def app_model_id(obj):
    """
    Returns a app-model-id string for a given object
    :param obj:
    :return:
    """
    ct = ContentType.objects.get_for_model(obj)

    return '%s-%s-%s' % (ct.app_label, ct.model, obj.id)

Example 21

Project: django-compositepks
Source File: __init__.py
View license
def create_permissions(app, created_models, verbosity, **kwargs):
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth.models import Permission
    app_models = get_models(app)
    if not app_models:
        return
    for klass in app_models:
        ctype = ContentType.objects.get_for_model(klass)
        for codename, name in _get_all_permissions(klass._meta):
            p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id,
                defaults={'name': name, 'content_type': ctype})
            if created and verbosity >= 2:
                print "Adding permission '%s'" % p

Example 22

View license
def group_get_objects_with_permission(self, model, permission):
    """
    Return all objects of type model where the group has the passed permissions
    """
    ctype = ContentType.objects.get_for_model(model)
    perms = model.perms.as_int(permission)
    obj_ids = self.grouppermission_set.filter(content_type=ctype).extra(
                where=['permission & %s > 0'], params=[perms]
                ).values_list('object_id', flat=True)
    return model.objects.filter(pk__in=obj_ids)

Example 23

Project: qualitio
Source File: bound_reports_menu.py
View license
@register.inclusion_tag('report/bound_reports_menu.html', takes_context=True)
def bound_reports_menu(context, obj, current_view):

    content_type =  ContentType.objects.get_for_model(obj)
    reports = Report.objects.filter(bound_type=content_type)

    return {"reports": reports,
            "current_view": current_view,
            "model_name": content_type.model,
            "obj": obj}

Example 24

Project: pinax-eventlog
Source File: tests.py
View license
    def test_log_content_object(self):
        user = get_user_model().objects.create(
            date_joined=(timezone.now() - timedelta(days=100))
        )
        event = log(user=None, action="FOO", obj=user)
        self.assertEquals(event.object_id, user.pk)
        self.assertEquals(event.content_type, ContentType.objects.get_for_model(user))

Example 25

Project: tendenci
Source File: managers.py
View license
    def assign_group(self, group_or_groups, object, perms=None):
        """
        Assigns permissions to group or multiple groups
        assign_group(self, group_or_groups, object, perms=None)

        -- group_or_groups: can be a single group object, list, queryset
        or tuple. Although tuples may work differently:
        You can pass permissions individual permissions along with the tuple
        like so: ((instance,'view',),(instance,'change',))

        -- object: is the instance of a model class

        -- perms: a list of individual permissions to assign to each group
           leave blank for all permissions.
           Note: If you are using the tuple/perm approach this does nothing.
        """
        multi_group = False
        group_with_perms = False

        # nobody to give permissions too
        if not group_or_groups:
            return
        # check perms
        if not isinstance(perms, list):
            perms = None
        # check for multi_groups
        if isinstance(group_or_groups, list):
            multi_group = True
        if isinstance(group_or_groups, QuerySet):
            multi_group = True
        if isinstance(group_or_groups, tuple):
            multi_group = True
            if len(group_or_groups[0]) == 2:
                group_with_perms = True

        # treat the tuples differently. They are passed in as
        # ((group,perm,),(group,perm,) ..... (group,perm.))
        if group_with_perms:
            from tendenci.apps.user_groups.models import Group
            for group, perm in group_or_groups:
                if isinstance(group, unicode):
                    if group.isdigit():
                        try:
                            group = Group.objects.get(pk=group)
                        except:
                            group = None

                codename = '%s_%s' % (perm, object._meta.object_name.lower())
                content_type = ContentType.objects.get_for_model(object)

                perm = Permission.objects.get(codename=codename,
                                              content_type=content_type)

                defaults = {
                    "codename": codename,
                    "object_id": object.pk,
                    "content_type": perm.content_type,
                    "group": group,
                }
                self.get_or_create(**defaults)
            return  # get out

        if multi_group:
            for group in group_or_groups:
                if perms:
                    for perm in perms:
                        codename = '%s_%s' % (perm, object._meta.object_name.lower())
                        content_type = ContentType.objects.get_for_model(object)

                        perm = Permission.objects.get(codename=codename,
                                                      content_type=content_type)

                        defaults = {
                            "codename": codename,
                            "object_id": object.pk,
                            "content_type": perm.content_type,
                            "group": group,
                        }
                        self.get_or_create(**defaults)
                else:  # all default permissions
                    content_type = ContentType.objects.get_for_model(object)
                    perms = Permission.objects.filter(content_type=content_type)
                    for perm in perms:
                        defaults = {
                            "codename": perm.codename,
                            "object_id": object.pk,
                            "content_type": content_type,
                            "group": group,
                        }
                        self.get_or_create(**defaults)
        else:  # not multi_group
            if perms:
                for perm in perms:
                    codename = '%s_%s' % (perm, object._meta.object_name.lower())
                    content_type = ContentType.objects.get_for_model(object)

                    perm = Permission.objects.get(codename=codename,
                                                  content_type=content_type)
                    defaults = {
                        "codename": codename,
                        "object_id": object.pk,
                        "content_type": perm.content_type,
                        "group": group_or_groups,
                    }
                    self.get_or_create(**defaults)
            else:  # all default permissions
                content_type = ContentType.objects.get_for_model(object)
                perms = Permission.objects.filter(content_type=content_type)
                for perm in perms:
                    defaults = {
                        "codename": perm.codename,
                        "object_id": object.pk,
                        "content_type": content_type,
                        "group": group_or_groups,
                    }
                    self.get_or_create(**defaults)

Example 26

Project: django-seo2
Source File: base.py
View license
def create_metadata_instance(metadata_class, instance):
    # If this instance is marked as handled, don't do anything
    # This typically means that the django admin will add metadata
    # using eg an inline.
    if getattr(instance, '_MetadataFormset__seo_metadata_handled', False):
        return

    metadata = None
    content_type = ContentType.objects.get_for_model(instance)

    # If this object does not define a path, don't worry about automatic update
    try:
        path = instance.get_absolute_url()
    except AttributeError:
        return

    # Look for an existing object with this path
    language = getattr(instance, '_language', None)
    site = getattr(instance, '_site', None)
    for md in metadata_class.objects.get_instances(path, site, language):
        # If another object has the same path, remove the path.
        # It's harsh, but we need a unique path and will assume the other
        # link is outdated.
        if md._content_type != content_type or md._object_id != instance.pk:
            if md._content_object is None:
                return
            md._path = md._content_object.get_absolute_url()
            md.save()
            # Move on, this metadata instance isn't for us
            md = None
        else:
            # This is our instance!
            metadata = md

    # If the path-based search didn't work, look for (or create) an existing
    # instance linked to this object.
    if not metadata:
        metadata, md_created = metadata_class.objects.get_or_create(
            _content_type=content_type, _object_id=instance.pk)
        metadata._path = path
        metadata.save()

Example 27

Project: django-cropduster
Source File: __init__.py
View license
@csrf_exempt
@login_required
def upload(request):
    if request.method == 'GET':
        return index(request)

    # The data we'll be returning as JSON
    data = {
        'warning': [],
    }

    form = UploadForm(request.POST, request.FILES)

    if not form.is_valid():
        errors = form['image'].errors or form.errors
        return json_error(request, 'upload', action="uploading file",
                errors=[force_unicode(errors)])

    form_data = form.cleaned_data
    is_standalone = bool(form_data.get('standalone'))

    orig_file_path = form_data['image'].name
    if six.PY2 and isinstance(orig_file_path, unicode):
        orig_file_path = orig_file_path.encode('utf-8')
    orig_image = get_relative_media_url(orig_file_path)
    img = PIL.Image.open(orig_file_path)
    (w, h) = (orig_w, orig_h) = img.size

    if is_animated_gif(img) and not has_animated_gif_support():
        data['warning'].append(
            u"This server does not have animated gif support; your uploaded image "
            u"has been made static.")

    tmp_image = Image(image=orig_image)
    preview_w = form_data.get('preview_width') or PREVIEW_WIDTH
    preview_h = form_data.get('preview_height') or PREVIEW_HEIGHT

    # First pass resize if it's too large
    resize_ratio = min(preview_w / w, preview_h / h)

    def fit_preview(im):
        (w, h) = im.size
        if resize_ratio < 1:
            w = int(round(w * resize_ratio))
            h = int(round(h * resize_ratio))
            preview_img = im.resize((w, h), PIL.Image.ANTIALIAS)
        else:
            preview_img = im
        return preview_img

    if not is_standalone:
        preview_file_path = tmp_image.get_image_path('_preview')
        process_image(img, preview_file_path, fit_preview)

    data.update({
        'crop': {
            'orig_image': orig_image,
            'orig_w': orig_w,
            'orig_h': orig_h,
            'image_id': None,
        },
        'url': tmp_image.get_image_url('_preview'),
        'orig_image': orig_image,
        'orig_w': orig_w,
        'orig_h': orig_h,
        'width': w,
        'height': h,
    })
    if not is_standalone:
        return HttpResponse(json.dumps(data), content_type='application/json')

    size = Size('crop', w=img.size[0], h=img.size[1])

    md5 = form_data.get('md5')
    try:
        standalone_image = StandaloneImage.objects.get(md5=md5)
    except StandaloneImage.DoesNotExist:
        standalone_image = StandaloneImage(md5=md5, image=orig_image)
        standalone_image.save()
    cropduster_image, created = Image.objects.get_or_create(
        content_type=ContentType.objects.get_for_model(StandaloneImage),
        object_id=standalone_image.pk)

    if not cropduster_image.image:
        cropduster_image.image = orig_image
        cropduster_image.save()
    elif cropduster_image.image.name != orig_image:
        data['crop']['orig_image'] = data['orig_image'] = cropduster_image.image.name
        data['url'] = cropduster_image.get_image_url('_preview')

    img = PIL.Image.open(cropduster_image.image.path)
    preview_file_path = cropduster_image.get_image_path('_preview')
    if not os.path.exists(preview_file_path):
        process_image(img, preview_file_path, fit_preview)

    thumb = cropduster_image.save_size(size, standalone=True)

    sizes = form_data.get('sizes') or []
    if len(sizes) == 1:
        size = sizes[0]
    else:
        size = Size('crop')

    data.update({
        'thumbs': [{
            'crop_x': thumb.crop_x,
            'crop_y': thumb.crop_y,
            'crop_w': thumb.crop_w,
            'crop_h': thumb.crop_h,
            'width':  thumb.width,
            'height': thumb.height,
            'id': None,
            'changed': True,
            'size': json.dumps(size),
            'name': thumb.name,
        }]
    })
    data['crop'].update({
        'image_id': cropduster_image.pk,
        'sizes': json.dumps([size]),
    })
    return HttpResponse(json.dumps(data), content_type='application/json')

Example 28

Project: tendenci
Source File: views.py
View license
@is_enabled('pages')
@login_required
def add(request, form_class=PageForm, meta_form_class=MetaForm,
        category_form_class=CategoryForm,
        template_name="pages/add.html"):
    if not has_perm(request.user, 'pages.add_page'):
        raise Http403

    content_type = get_object_or_404(ContentType,
                                     app_label='pages',
                                     model='page')

    if request.method == "POST":
        form = form_class(request.POST, request.FILES, user=request.user)
        metaform = meta_form_class(request.POST, prefix='meta')
        categoryform = category_form_class(content_type,
                                           request.POST,)
        if form.is_valid() and metaform.is_valid() and categoryform.is_valid():
            page = form.save()

            # handle header image
            f = form.cleaned_data['header_image']
            if f:
                header = HeaderImage()
                header.content_type = ContentType.objects.get_for_model(Page)
                header.object_id = page.id
                header.creator = request.user
                header.creator_username = request.user.username
                header.owner = request.user
                header.owner_username = request.user.username
                filename = "%s-%s" % (page.slug, f.name)
                f.file.seek(0)
                header.file.save(filename, f)
                page.header_image = header

            #save meta
            meta = metaform.save()
            page.meta = meta

            ## update the category and subcategory
            page.update_category_subcategory(
                                    categoryform.cleaned_data['category'],
                                    categoryform.cleaned_data['sub_category']
                                    )

            # add all permissions
            page = update_perms_and_save(request, form, page)

            messages.add_message(request, messages.SUCCESS,
                                 _('Successfully added %(p)s' % {'p': unicode(page)}))

            checklist_update('add-page')

            if not request.user.profile.is_superuser:
                # send notification to administrators
                recipients = get_notice_recipients('module',
                                                   'pages',
                                                    'pagerecipients')
                if recipients:
                    if notification:
                        extra_context = {
                            'object': page,
                            'request': request,
                        }
                        notification.send_emails(recipients, 'page_added', extra_context)
            if page.status and page.status_detail == 'active':
                return HttpResponseRedirect(reverse('page', args=[page.slug]))
            return HttpResponseRedirect(reverse('page.search'))
    else:
        initial_category_form_data = {
            'app_label': 'pages',
            'model': 'page',
            'pk': 0,
        }
        form = form_class(user=request.user)
        metaform = meta_form_class(prefix='meta')
        categoryform = category_form_class(content_type,
                                           initial=initial_category_form_data,)
    return render_to_response(template_name,
            {
                'form': form,
                'metaform': metaform,
                'categoryform': categoryform,
            },
            context_instance=RequestContext(request))

Example 29

View license
    def _create_objects(self):
        with externals.watson.context_manager("update_index")():
            self.date = now()
            self.date_str = '/{}/{}/{}'.format(
                self.date.strftime('%Y'),
                self.date.strftime('%b').lower(),
                self.date.strftime('%d').lstrip('0'),
            )

            content_type = ContentType.objects.get_for_model(NewsFeed)

            self.page = Page.objects.create(
                title="News Feed",
                content_type=content_type,
            )

            self.feed = NewsFeed.objects.create(
                page=self.page,
            )

            self.category = Category.objects.create(
                slug='foo'
            )

            self.article = Article.objects.create(
                news_feed=self.feed,
                title='Foo',
                slug='foo',
                date=self.date,
            )
            self.article.categories.add(self.category)

            self.article_2 = Article.objects.create(
                news_feed=self.feed,
                title='Foo 2',
                slug='foo2',
                date=self.date + timedelta(days=10)
            )

            self.article_3 = Article.objects.create(
                news_feed=self.feed,
                title='Foo 3',
                slug='foo3',
                status='approved',
                date=self.date,
            )

Example 30

Project: tendenci
Source File: managers.py
View license
    def assign(self, user_or_users, object, perms=None):
        """
        Assigns permissions to user or multiple users
        assign_group(self, user_or_users, object, perms=None)

        -- user_or_users: can be a single user object, list, queryset
        or tuple.

        -- object: is the instance of a model class

        -- perms: a list of individual permissions to assign to each user
           leave blank for all permissions.
        """
        multi_user = False

        # nobody to give permissions too
        if not user_or_users:
            return
        # check perms
        if not isinstance(perms, list):
            perms = None
        # check for multi_users
        if isinstance(user_or_users, list):
            multi_user = True
        if isinstance(user_or_users, QuerySet):
            multi_user = True
        if isinstance(user_or_users, tuple):
            multi_user = True

        if multi_user:
            for user in user_or_users:
                if perms:
                    for perm in perms:
                        codename = '%s_%s' % (perm, object._meta.object_name.lower())
                        content_type = ContentType.objects.get_for_model(object)

                        perm = Permission.objects.get(codename=codename,
                                                      content_type=content_type)

                        defaults = {
                            "codename": codename,
                            "object_id": object.pk,
                            "content_type": perm.content_type,
                            "user": user,
                        }
                        try:
                            self.get_or_create(**defaults)
                        except self.model.MultipleObjectsReturned as e:
                            pass

                else:  # all default permissions
                    content_type = ContentType.objects.get_for_model(object)
                    perms = Permission.objects.filter(content_type=content_type)
                    for perm in perms:
                        defaults = {
                            "codename": perm.codename,
                            "object_id": object.pk,
                            "content_type": content_type,
                            "user": user,
                        }
                        try:
                            self.get_or_create(**defaults)
                        except self.model.MultipleObjectsReturned as e:
                            pass

        else:  # not muli_user
            if perms:
                for perm in perms:
                    codename = '%s_%s' % (perm, object._meta.object_name.lower())
                    content_type = ContentType.objects.get_for_model(object)

                    perm = Permission.objects.get(codename=codename,
                                                  content_type=content_type)
                    defaults = {
                        "codename": codename,
                        "object_id": object.pk,
                        "content_type": perm.content_type,
                        "user": user_or_users,
                    }
                    try:
                        self.get_or_create(**defaults)
                    except self.model.MultipleObjectsReturned as e:
                        pass

            else:  # all default permissions
                content_type = ContentType.objects.get_for_model(object)
                perms = Permission.objects.filter(content_type=content_type)
                for perm in perms:
                    defaults = {
                        "codename": perm.codename,
                        "object_id": object.pk,
                        "content_type": content_type,
                        "user": user_or_users,
                    }
                    try:
                        self.get_or_create(**defaults)
                    except self.model.MultipleObjectsReturned as e:
                        pass

Example 31

Project: jmbo
Source File: admin.py
View license
    def __init__(self, *args, **kwargs):
        super(ModelBaseAdminForm, self).__init__(*args, **kwargs)

        self.fields['image'].help_text = """An image can be in format JPG, \
PNG or GIF. Images are scaled to the appropriate size when people browse to \
the site on mobile browsers, so always upload an image that will look good on \
normal web browsers. In general an image with an aspect ratio of 4:3 will \
yield best results."""

        self.fields['crop_from'].help_text = """If you upload an image in an \
aspect ratio that may require it to be cropped then you can adjust from where \
the cropping takes place. This is useful to prevent peoples' heads from being \
chopped off."""

        self.fields['effect'].help_text = """Apply an effect to the image."""

        # We want image to be optional, unlike photologue
        self.fields['image'].required = False

        # Add relations fields
        content_type = ContentType.objects.get_for_model(self._meta.model)
        relations = Relation.objects.filter(source_content_type=content_type)
        for relation in relations:
            name = relation.name
            if name not in self.fields:
                self.fields[name] = forms.ModelMultipleChoiceField(
                    ModelBase.objects.filter(content_type=relation.target_content_type).order_by('title', 'subtitle'),
                    required=False,
                    label=forms.forms.pretty_name(name),
                )

        instance = kwargs.get('instance', None)
        if instance is not None:
            # Set relations
            for relation in relations:
                name = relation.name
                initial = Relation.objects.filter(
                    source_content_type=instance.content_type,
                    source_object_id=instance.id,
                    name=name
                )
                self.fields[name].initial = [o.target for o in initial]

        if (instance is None) and not self.is_bound:
            # Select all sites initially
            self.fields['sites'].initial = Site.objects.all()

Example 32

Project: hubplus
Source File: models.py
View license
        @transaction.commit_on_success
        def delete(self) :
            from apps.microblogging.models import Following

            sc = self.get_security_context()
            ref = self.get_ref()

            # remove members
            for m in self.get_members() :
                self.remove_member(m)
            
            # remove tags, now moved to GenericReference.delete()

            content_type = ContentType.objects.get_for_model(self)

            # remove statuses
            for f in Following.objects.filter(follower_content_type=content_type,follower_object_id=self.id) :
                f.delete()
            for f in Following.objects.filter(followed_content_type=content_type,followed_object_id=self.id) :
                f.delete() 
            
            # and new FeedItems
            from apps.plus_feed.models import FeedItem
            for x in FeedItem.feed_manager.get_from(self) :
                x.delete()


            # remove comments
            from threadedcomments.models import ThreadedComment
            for c in ThreadedComment.objects.filter(content_type=content_type, object_id=self.id) :
                c.delete()

            # remove resource (WikiPage)
                
            from apps.plus_wiki.models import WikiPage
            for p in WikiPage.objects.filter(in_agent=ref) :
                p.delete()

            # remove resource (Uploads)
            from apps.plus_resources.models import Resource
            for r in Resource.objects.filter(in_agent=ref) :
                r.delete()

            # XXX remove associated invites and applications

            # permissions
            
            sc.target.clear()

            # a) delete security tags
            for t in sc.get_tags() :
                t.delete()
                # does this delete the relation between other GenRefs and the tag?

            # b) delete this agent as security_context
            sc.delete()

            # remove the genref to this
            ref.delete()

            # remove the group
            super(TgGroup,self).delete()

Example 33

Project: scielo-manager
Source File: tests_helpers.py
View license
    def test_POST_valid_formdata_do_log(self):
        # with:
        perm_journal_change = _makePermission(perm='change_journal', model='journal', app_label='journalmanager')
        perm_journal_list = _makePermission(perm='list_journal', model='journal', app_label='journalmanager')
        self.user.user_permissions.add(perm_journal_change)
        self.user.user_permissions.add(perm_journal_list)

        sponsor = jm_modelfactories.SponsorFactory.create()
        use_license = jm_modelfactories.UseLicenseFactory.create()
        language = jm_modelfactories.LanguageFactory.create()
        subject_category = jm_modelfactories.SubjectCategoryFactory.create()
        study_area = jm_modelfactories.StudyAreaFactory.create()

        form = self.app.get(reverse('journal.add'), user=self.user).forms['journal-form']
        form['journal-sponsor'] = [sponsor.pk]
        form['journal-study_areas'] = [study_area.pk]
        form['journal-ctrl_vocabulary'] = 'decs'
        form['journal-frequency'] = 'Q'
        form['journal-final_num'] = ''
        form['journal-eletronic_issn'] = '0102-6720'
        form['journal-init_vol'] = '1'
        form['journal-title'] = u'ABCD. Arquivos Brasileiros de Cirurgia Digestiva (São Paulo)'
        form['journal-title_iso'] = u'ABCD. Arquivos B. de C. D. (São Paulo)'
        form['journal-short_title'] = u'ABCD.(São Paulo)'
        form['journal-editorial_standard'] = 'vancouv'
        form['journal-scielo_issn'] = 'print'
        form['journal-init_year'] = '1986'
        form['journal-acronym'] = 'ABCD'
        form['journal-pub_level'] = 'CT'
        form['journal-init_num'] = '1'
        form['journal-final_vol'] = ''
        form['journal-subject_descriptors'] = 'MEDICINA, CIRURGIA, GASTROENTEROLOGIA, GASTROENTEROLOGIA'
        form['journal-print_issn'] = '0102-6720'
        form['journal-copyrighter'] = 'Texto do copyrighter'
        form['journal-publisher_name'] = 'Colégio Brasileiro de Cirurgia Digestiva'
        form['journal-publisher_country'] = 'BR'
        form['journal-publisher_state'] = 'SP'
        form['journal-publication_city'] = 'São Paulo'
        form['journal-editor_name'] = 'Colégio Brasileiro de Cirurgia Digestiva'
        form['journal-editor_address'] = 'Av. Brigadeiro Luiz Antonio, 278 - 6° - Salas 10 e 11'
        form['journal-editor_address_city'] = 'São Paulo'
        form['journal-editor_address_state'] = 'SP'
        form['journal-editor_address_zip'] = '01318-901'
        form['journal-editor_address_country'] = 'BR'
        form['journal-editor_phone1'] = '(11) 3288-8174'
        form['journal-editor_phone2'] = '(11) 3289-0741'
        form['journal-editor_email'] = '[email protected]'
        form['journal-use_license'] = use_license.pk
        form['journal-languages'] = [language.pk]
        form['journal-abstract_keyword_languages'] = [language.pk]
        form.set('journal-subject_categories', [str(subject_category.pk),])
        form['journal-is_indexed_scie'] = True
        form['journal-is_indexed_ssci'] = False
        form['journal-is_indexed_aehci'] = True

        # when:
        response = form.submit().follow()

        # then:
        self.assertIn('Saved.', response.body)
        self.assertIn('ABCD.(São Paulo)', response.body)
        self.assertTemplateUsed(response, 'journalmanager/journal_dash.html')

        self.assertEqual(audit_models.AuditLogEntry.objects.count(), 1)
        log_entry = audit_models.AuditLogEntry.objects.all()[0]
        audited_object = log_entry.get_audited_object()
        # inspect audited log entry data:
        self.assertEqual(log_entry.action_flag, audit_models.ADDITION)
        self.assertEqual(log_entry.object_id, unicode(audited_object.pk))
        self.assertEqual(log_entry.content_type, ContentType.objects.get_for_model(audited_object))
        self.assertEqual(log_entry.old_values, None)
        self.assertEqual(log_entry.user, self.user)

        fields_edited = [
            'sponsor',
            'use_license',
            'languages',
            'abstract_keyword_languages',
            'subject_categories',
            'study_areas',
            'title',
            'title_iso',
            'short_title',
            'acronym',
            'scielo_issn',
            'print_issn',
            'eletronic_issn',
            'subject_descriptors',
            'init_year',
            'init_vol',
            'init_num',
            'frequency',
            'editorial_standard',
            'ctrl_vocabulary',
            'pub_level',
            'copyrighter',
            'editor_name',
            'editor_address',
            'editor_address_city',
            'editor_address_state',
            'editor_address_zip',
            'editor_address_country',
            'editor_phone1',
            'editor_phone2',
            'editor_email',
            'publisher_name',
            'publisher_country',
            'publisher_state',
            'publication_city',
            'is_indexed_scie',
            'is_indexed_aehci',
        ]

        self.assertEqual(log_entry.new_values.keys(), [u'form_data', u'formsets_data'])
        for field_edited in fields_edited:
            # all edited fields are in "new_values"-dict
            self.assertIn(field_edited, log_entry.new_values['form_data'].keys())
            # all edited fields are in the "change message" field
            self.assertIn(field_edited, log_entry.change_message)

        # compare form data and stored new_values data
        for k,v in log_entry.new_values['form_data'].iteritems():
            form_value = form['journal-%s' % k].value
            self.assertEqual(log_entry.new_values['form_data'][k], force_unicode(v))

Example 34

Project: hubplus
Source File: views.py
View license
def profile(request, username, template_name="profiles/profile.html"):
    #trellis.callInEventLoop(hello, "Tom")

    is_me = False
    user = request.user


    if request.user.is_authenticated() :
        if user.username == username :
            is_me = True
    else :
        user = get_anon_user()

    other_user = secure_wrap(get_object_or_404(User, username=username),user)

    is_following = Following.objects.is_following(request.user, other_user.get_inner())

    p = other_user.get_inner().get_profile()
    profile = secure_wrap(p,user)
    profile.user # trigger permission exception if no access
 
    can_change_avatar = False
    
    try :
        profile.change_avatar
        can_change_avatar = True
    except PlusPermissionsNoAccessException :
        pass

    interests = get_tags(tagged=other_user.get_inner().get_profile(), 
                         tagged_for=other_user.get_inner(), tag_type='interest')
    skills = get_tags(tagged = other_user.get_inner().get_profile(), 
                      tagged_for=other_user.get_inner(), tag_type='skill')
    needs = get_tags(tagged = other_user.get_inner().get_profile(), 
                     tagged_for=other_user.get_inner(), tag_type='need')

    user_type = ContentType.objects.get_for_model(other_user)

    # new style statuses
    tweets = FeedItem.feed_manager.get_from(other_user.get_inner()).order_by("-sent")
    if tweets :
        latest_status = tweets[0]
        status_since = defaultfilters.timesince(latest_status.sent)
    else:
        status_since = ''
    status_type = 'profile'

    try:
        profile.get_all_sliders
        perms_bool = True
    except PlusPermissionsNoAccessException:
        perms_bool = False

    profile = TemplateSecureWrapper(profile)

    search_type = 'profile_list' 
    search_types = narrow_search_types()
    search_types_len = len(search_types)
    search_type_label = search_types[0][1][2]


    host_info = p.get_host_info()
    host_info = secure_wrap(host_info, user, interface_names=['Viewer', 'Editor'])

    see_host_info = False
    try :
        host_info.user 
        see_host_info = True
    except :
        pass # can't see host_info
    host_info = TemplateSecureWrapper(host_info)
    
    hubs = other_user.get_inner().hubs()
    non_hub_groups = [(g.group_app_label() + ':group', g) for g in 
                      other_user.get_inner().groups.filter(level='member').exclude(id__in=hubs)]
    hubs = [(g.group_app_label() + ':group', g) for g in hubs]

    see_about = is_me or show_section(profile, ('about',))
    see_contacts = is_me or show_section(profile,('mobile','home','work','fax','website','address','email_address'))
    
    see_links = is_me
    links = get_links_for(other_user,RequestContext(request))
    if links :
        see_links = True

    can_tag = profile.has_interface('Profile.Editor')


    template_args = {
            "is_me": is_me,
            "is_following": is_following,
            "other_user": other_user.get_inner(), # XXX - should fix this get_inner
            "profile":profile,
            "can_change_avatar":can_change_avatar,

            "head_title" : "%s" % profile.get_display_name(),
            "status_type" : status_type,
            "status_since" : status_since,
            "host_info" : host_info,
            "skills" : skills,
            "needs" : needs,
            "interests" : interests,
            "other_user_tweets" : tweets,
            "permissions":perms_bool,
            "non_hub_groups":non_hub_groups,
            "hubs":hubs,
            "search_type":search_type,
            "search_types":search_types,
            "search_type_label":search_type_label,
            "search_types_len":search_types_len,
            "host_info":host_info, 
            "see_host_info":see_host_info,
            "see_about":see_about,
            "see_contacts":see_contacts,
            "see_links":see_links,
            "other_user_class":user_type.id,
            "other_user_id":other_user.id,
            "can_tag":can_tag,
            }
    labels = {'MAIN_HUB_LABEL':_('Main %s')%settings.HUB_NAME,
              'MAIN_HUB_DEFAULT':_("No %s selected")%settings.HUB_NAME}
    template_args.update(labels)

    return render_to_response(template_name, template_args, context_instance=RequestContext(request))

Example 35

Project: hubplus
Source File: decommission_hub.py
View license
def hide_user(user) :
    user.username = mangle(user.username)
    user.email_address = mangle(user.email_address)

    user.active = False

    user.description = ''
    user.organization = ''
    user.mobile = ''
    user.home = ''
    user.work = ''
    user.fax = ''
    user.place = ''
    user.skype_id = ''
    user.website = ''
    user.address = ''
    user.country = ''
    user.homehub = None
    user.post_or_zip = ''

    # remove FeedItem
    for fi in FeedItem.feed_manager.get_from(user) :
        fi.source = removed_user.get_ref()
        fi.save()


    # creator of pages
    from apps.plus_resources.models import Resource
    from apps.plus_wiki.models import WikiPage

    for p in WikiPage.objects.created_by(user) :
        p.created_by = removed_user
        p.save()
    
    # uploads
    for r in Resource.objects.created_by(user) :
        r.created_by = removed.user
        r.save()

    # remove following statuses
        for f in Following.objects.filter(follower_content_type=content_type,follower_object_id=self.id) :
            f.delete()
        for f in Following.objects.filter(followed_content_type=content_type,followed_object_id=self.id) :
            f.delete()

            
    # remove comments                                                                                                
    from threadedcomments.models import ThreadedComment
    content_type = ContentType.objects.get_for_model(user)
    for c in ThreadedComment.objects.filter(content_type=content_type, object_id=user.id) :
        c.user = removed_user
        c.save()


    user.save()

Example 36

Project: django-object-tools
Source File: __init__.py
View license
def _create_permissions(**kwargs):
    """
    Almost exactly the same as django.contrib.auth.management.__init__.py
    """
    from django.contrib.contenttypes.models import ContentType

    object_tools.autodiscover()
    tools = object_tools.tools._registry

    # This will hold the permissions we're looking for as
    # (content_type, (codename, name))
    searched_perms = list()
    # The codenames and ctypes that should exist.
    ctypes = set()
    for model, tools in tools.iteritems():
        ctype = ContentType.objects.get_for_model(model)
        ctypes.add(ctype)
        for perm in _get_all_permissions(model._meta, tools):
            searched_perms.append((ctype, perm))

    # Find all the Permissions that have a context_type for a model we're
    # looking for.  We don't need to check for codenames since we already have
    # a list of the ones we're going to create.
    all_perms = set(auth_app.Permission.objects.filter(
        content_type__in=ctypes,
    ).values_list(
        "content_type", "codename"
    ))

    for ctype, (codename, name) in searched_perms:
        # If the permissions exists, move on.
        if (ctype.pk, codename) in all_perms:
            continue
        p = auth_app.Permission.objects.create(
            codename=codename,
            name=name,
            content_type=ctype
        )
        if kwargs.get("verbosity", 2) >= 2:
            print "Adding permission '%s'" % p

Example 37

Project: jmbo
Source File: jmbo_inclusion_tags.py
View license
    def render(self, context):
        obj = self.obj.resolve(context)
        # Fallback handling because object_* tags now defer to render_object
        try:
            type = self.type.resolve(context)
        except template.VariableDoesNotExist:
            type = self.type

        # Update context
        context.push()
        context['object'] = obj

        # Template names follow typical Django naming convention but also
        # provides legacy handling.
        ctype = ContentType.objects.get_for_model(obj)
        template_names = (
            "%s/inclusion_tags/%s_%s.html" % (ctype.app_label, ctype.model, type),
            "%s/%s/inclusion_tags/object_%s.html" % (ctype.app_label, ctype.model, type),
            "%s/inclusion_tags/object_%s.html" % (ctype.app_label, type),
            "jmbo/inclusion_tags/object_%s.html" % type,
            "jmbo/inclusion_tags/modelbase_%s.html" % type
        )
        rendered = False
        for template_name in template_names:
            try:
                response = render_to_string(template_name, context)
                rendered = True
                break
            except TemplateDoesNotExist:
                pass

        context.pop()

        if not rendered:
            if settings.TEMPLATE_DEBUG:
                raise TemplateDoesNotExist({
                    'content_type': ctype.app_label,
                    'model': ctype.model,
                    'type': type
                })
            else:
                response = ''

        return response

Example 38

Project: django-softdelete
Source File: models.py
View license
    def delete(self, *args, **kwargs):
        if self.deleted_at:
            logging.debug("HARD DELETEING type %s, %s", type(self), self)
            try:
                cs = ChangeSet.objects.get(
                    content_type=ContentType.objects.get_for_model(self),
                    object_id=self.pk)
                cs.delete()
                super(SoftDeleteObject, self).delete(*args, **kwargs)
            except:
                try:
                    cs = kwargs.get('changeset') or _determine_change_set(self)
                    rs = SoftDeleteRecord.objects.get(
                        changeset=cs,
                        content_type=ContentType.objects.get_for_model(self),
                        object_id=self.pk)
                    if rs.changeset.soft_delete_records.count() == 1:
                        cs.delete()
                    else:
                        rs.delete()
                    super(SoftDeleteObject, self).delete(*args, **kwargs)
                except:
                    pass
        else:
            using = kwargs.get('using', settings.DATABASES['default'])
            models.signals.pre_delete.send(sender=self.__class__,
                                           instance=self,
                                           using=using)
            pre_soft_delete.send(sender=self.__class__,
                                 instance=self,
                                 using=using)
            logging.debug('SOFT DELETING type: %s, %s', type(self), self)
            cs = kwargs.get('changeset') or _determine_change_set(self)
            SoftDeleteRecord.objects.get_or_create(
                changeset=cs,
                content_type=ContentType.objects.get_for_model(self),
                object_id=self.pk)
            self.deleted_at = timezone.now()
            self.save()
            all_related = [
                f for f in self._meta.get_fields()
                if (f.one_to_many or f.one_to_one)
                and f.auto_created and not f.concrete
            ]
            for x in all_related:
                self._do_delete(cs, x)
            logging.debug("FINISHED SOFT DELETING RELATED %s", self)
            models.signals.post_delete.send(sender=self.__class__,
                                            instance=self,
                                            using=using)
            post_soft_delete.send(sender=self.__class__,
                                  instance=self,
                                  using=using)

Example 39

View license
    def import_comments(self, post_id, slug, *args, **options):
        try:
            mysite = Site.objects.get_current()
            self.site_id = mysite.id
        except Site.DoesNotExist:
            print('site does not exist')
            return
        comments = self.get_posts_data(
            self.url, post_id, get_comments=True)
        imported_comments = []
        for comment in comments:
            try:
                blog_post = BlogPage.objects.get(slug=slug)
                blog_post_type = ContentType.objects.get_for_model(blog_post)
            except BlogPage.DoesNotExist:
                print('cannot find this blog post')
                continue
            comment_text = self.convert_html_entities(comment.get('content'))
            date = datetime.strptime(comment.get('date'), '%Y-%m-%dT%H:%M:%S')
            status = comment.get('status')
            if status != 'approved':
                continue
            comment_author = comment.get('author')
            new_comment = self.create_comment(
                blog_post_type, blog_post.pk, comment_text, date)
            new_comment.wordpress_id = comment.get('ID')
            new_comment.parent_wordpress_id = comment.get('parent')
            if type(comment_author) is int:
                pass
            else:
                if 'username' in comment_author:
                    user_name = comment['author']['username']
                    user_url = comment['author']['URL']
                    try:
                        current_user = User.objects.get(username=user_name)
                        new_comment.user = current_user
                    except User.DoesNotExist:
                        pass

                    new_comment.user_name = user_name
                    new_comment.user_url = user_url

            new_comment.save()
            imported_comments.append(new_comment)
        # Now assign parent comments
        for comment in imported_comments:
            if comment.parent_wordpress_id != "0":
                for sub_comment in imported_comments:
                    if sub_comment.wordpress_id == comment.parent_wordpress_id:
                        comment.parent_id = sub_comment.id
                        try:
                            comment._calculate_thread_data()
                            comment.save()
                        except MaxThreadLevelExceededException:
                            print("Warning, max thread level exceeded on {}"
                                  .format(comment.id))
                        break

Example 40

Project: modoboa
Source File: lib.py
View license
def get_identities(user, searchquery=None, idtfilter=None, grpfilter=None):
    """Return all the identities owned by a user.

    :param user: the desired user
    :param str searchquery: search pattern
    :param list idtfilter: identity type filters
    :param list grpfilter: group names filters
    :return: a queryset
    """
    accounts = []
    if idtfilter is None or not idtfilter or idtfilter == "account":
        ids = user.objectaccess_set \
            .filter(content_type=ContentType.objects.get_for_model(user)) \
            .values_list('object_id', flat=True)
        q = Q(pk__in=ids)
        if searchquery is not None:
            q &= Q(username__icontains=searchquery) \
                | Q(email__icontains=searchquery)
        if grpfilter is not None and grpfilter:
            if grpfilter == "SuperAdmins":
                q &= Q(is_superuser=True)
            else:
                q &= Q(groups__name=grpfilter)
        accounts = User.objects.filter(q).prefetch_related("groups")

    aliases = []
    if idtfilter is None or not idtfilter \
            or (idtfilter in ["alias", "forward", "dlist"]):
        alct = ContentType.objects.get_for_model(Alias)
        ids = user.objectaccess_set.filter(content_type=alct) \
            .values_list('object_id', flat=True)
        q = Q(pk__in=ids, internal=False)
        if searchquery is not None:
            q &= (
                Q(address__icontains=searchquery) |
                Q(domain__name__icontains=searchquery)
            )
        aliases = Alias.objects.select_related("domain").filter(q)
        if idtfilter is not None and idtfilter:
            aliases = [al for al in aliases if al.type == idtfilter]
    return chain(accounts, aliases)

Example 41

Project: wagtail
Source File: pages.py
View license
def edit(request, page_id):
    latest_revision = get_object_or_404(Page, id=page_id).get_latest_revision()
    page = get_object_or_404(Page, id=page_id).get_latest_revision_as_page()
    parent = page.get_parent()

    content_type = ContentType.objects.get_for_model(page)
    page_class = content_type.model_class()

    page_perms = page.permissions_for_user(request.user)
    if not page_perms.can_edit():
        raise PermissionDenied

    for fn in hooks.get_hooks('before_edit_page'):
        result = fn(request, page)
        if hasattr(result, 'status_code'):
            return result

    edit_handler_class = page_class.get_edit_handler()
    form_class = edit_handler_class.get_form_class(page_class)

    next_url = get_valid_next_url_from_request(request)

    errors_debug = None

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES, instance=page,
                          parent_page=parent)

        if form.is_valid() and not page.locked:
            page = form.save(commit=False)

            is_publishing = bool(request.POST.get('action-publish')) and page_perms.can_publish()
            is_submitting = bool(request.POST.get('action-submit'))
            is_reverting = bool(request.POST.get('revision'))

            # If a revision ID was passed in the form, get that revision so its
            # date can be referenced in notification messages
            if is_reverting:
                previous_revision = get_object_or_404(page.revisions, id=request.POST.get('revision'))

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()
                # Need to reload the page because the URL may have changed, and we
                # need the up-to-date URL for the "View Live" button.
                page = page.specific_class.objects.get(pk=page.pk)

            # Notifications
            if is_publishing:
                if page.go_live_at and page.go_live_at > timezone.now():
                    # Page has been scheduled for publishing in the future

                    if is_reverting:
                        message = _(
                            "Revision from {0} of page '{1}' has been scheduled for publishing."
                        ).format(
                            previous_revision.created_at.strftime("%d %b %Y %H:%M"),
                            page.get_admin_display_title()
                        )
                    else:
                        message = _(
                            "Page '{0}' has been scheduled for publishing."
                        ).format(
                            page.get_admin_display_title()
                        )

                    messages.success(request, message, buttons=[
                        messages.button(
                            reverse('wagtailadmin_pages:edit', args=(page.id,)),
                            _('Edit')
                        )
                    ])

                else:
                    # Page is being published now

                    if is_reverting:
                        message = _(
                            "Revision from {0} of page '{1}' has been published."
                        ).format(
                            previous_revision.created_at.strftime("%d %b %Y %H:%M"),
                            page.get_admin_display_title()
                        )
                    else:
                        message = _(
                            "Page '{0}' has been published."
                        ).format(
                            page.get_admin_display_title()
                        )

                    messages.success(request, message, buttons=[
                        messages.button(
                            page.url,
                            _('View live')
                        ),
                        messages.button(
                            reverse('wagtailadmin_pages:edit', args=(page_id,)),
                            _('Edit')
                        )
                    ])

            elif is_submitting:

                message = _(
                    "Page '{0}' has been submitted for moderation."
                ).format(
                    page.get_admin_display_title()
                )

                messages.success(request, message, buttons=[
                    messages.button(
                        reverse('wagtailadmin_pages:view_draft', args=(page_id,)),
                        _('View draft')
                    ),
                    messages.button(
                        reverse('wagtailadmin_pages:edit', args=(page_id,)),
                        _('Edit')
                    )
                ])

                if not send_notification(page.get_latest_revision().id, 'submitted', request.user.pk):
                    messages.error(request, _("Failed to send notifications to moderators"))

            else:  # Saving

                if is_reverting:
                    message = _(
                        "Page '{0}' has been replaced with revision from {1}."
                    ).format(
                        page.get_admin_display_title(),
                        previous_revision.created_at.strftime("%d %b %Y %H:%M")
                    )
                else:
                    message = _(
                        "Page '{0}' has been updated."
                    ).format(
                        page.get_admin_display_title()
                    )

                messages.success(request, message)

            for fn in hooks.get_hooks('after_edit_page'):
                result = fn(request, page)
                if hasattr(result, 'status_code'):
                    return result

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                if next_url:
                    # redirect back to 'next' url if present
                    return redirect(next_url)
                # redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                target_url = reverse('wagtailadmin_pages:edit', args=[page.id])
                if next_url:
                    # Ensure the 'next' url is passed through again if present
                    target_url += '?next=%s' % urlquote(next_url)
                return redirect(target_url)
        else:
            if page.locked:
                messages.error(request, _("The page could not be saved as it is locked"))
            else:
                messages.error(request, _("The page could not be saved due to validation errors"))

            edit_handler = edit_handler_class(instance=page, form=form)
            errors_debug = (
                repr(edit_handler.form.errors) +
                repr([
                    (name, formset.errors)
                    for (name, formset) in edit_handler.form.formsets.items()
                    if formset.errors
                ])
            )
            has_unsaved_changes = True
    else:
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)
        has_unsaved_changes = False

    # Check for revisions still undergoing moderation and warn
    if latest_revision and latest_revision.submitted_for_moderation:
        messages.warning(request, _("This page is currently awaiting moderation"))

    return render(request, 'wagtailadmin/pages/edit.html', {
        'page': page,
        'content_type': content_type,
        'edit_handler': edit_handler,
        'errors_debug': errors_debug,
        'preview_modes': page.preview_modes,
        'form': form,
        'next': next_url,
        'has_unsaved_changes': has_unsaved_changes,
    })

Example 42

Project: PyClassLessons
Source File: tests.py
View license
    def test_get_for_concrete_models(self):
        """
        Make sure the `for_concrete_models` kwarg correctly works
        with concrete, proxy and deferred models.
        """
        concrete_model_ct = ContentType.objects.get_for_model(ConcreteModel)

        cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel)
        self.assertEqual(cts, {
            ConcreteModel: concrete_model_ct,
            ProxyModel: concrete_model_ct,
        })

        proxy_model_ct = ContentType.objects.get_for_model(ProxyModel,
                                                           for_concrete_model=False)
        cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel,
                                                 for_concrete_models=False)
        self.assertEqual(cts, {
            ConcreteModel: concrete_model_ct,
            ProxyModel: proxy_model_ct,
        })

        # Make sure deferred model are correctly handled
        ConcreteModel.objects.create(name="Concrete")
        DeferredConcreteModel = ConcreteModel.objects.only('pk').get().__class__
        DeferredProxyModel = ProxyModel.objects.only('pk').get().__class__

        cts = ContentType.objects.get_for_models(DeferredConcreteModel,
                                                 DeferredProxyModel)
        self.assertEqual(cts, {
            DeferredConcreteModel: concrete_model_ct,
            DeferredProxyModel: concrete_model_ct,
        })

        cts = ContentType.objects.get_for_models(DeferredConcreteModel,
                                                 DeferredProxyModel,
                                                 for_concrete_models=False)
        self.assertEqual(cts, {
            DeferredConcreteModel: concrete_model_ct,
            DeferredProxyModel: proxy_model_ct,
        })

Example 43

Project: splunk-webframework
Source File: tests.py
View license
    def test_get_for_concrete_models(self):
        """
        Make sure the `for_concrete_models` kwarg correctly works
        with concrete, proxy and deferred models.
        """
        concrete_model_ct = ContentType.objects.get_for_model(ConcreteModel)

        cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel)
        self.assertEqual(cts, {
            ConcreteModel: concrete_model_ct,
            ProxyModel: concrete_model_ct,
        })

        proxy_model_ct = ContentType.objects.get_for_model(ProxyModel,
                                                           for_concrete_model=False)
        cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel,
                                                 for_concrete_models=False)
        self.assertEqual(cts, {
            ConcreteModel: concrete_model_ct,
            ProxyModel: proxy_model_ct,
        })

        # Make sure deferred model are correctly handled
        ConcreteModel.objects.create(name="Concrete")
        DeferredConcreteModel = ConcreteModel.objects.only('pk').get().__class__
        DeferredProxyModel = ProxyModel.objects.only('pk').get().__class__

        cts = ContentType.objects.get_for_models(DeferredConcreteModel,
                                                 DeferredProxyModel)
        self.assertEqual(cts, {
            DeferredConcreteModel: concrete_model_ct,
            DeferredProxyModel: concrete_model_ct,
        })

        cts = ContentType.objects.get_for_models(DeferredConcreteModel,
                                                 DeferredProxyModel,
                                                 for_concrete_models=False)
        self.assertEqual(cts, {
            DeferredConcreteModel: concrete_model_ct,
            DeferredProxyModel: proxy_model_ct,
        })

Example 44

View license
    def setUp(self):
        # Permissions
        document_content_type = ContentType.objects.get_for_model(Document)
        add_doc_permission = Permission.objects.get(
            content_type=document_content_type, codename='add_document'
        )
        change_doc_permission = Permission.objects.get(
            content_type=document_content_type, codename='change_document'
        )

        # Collections
        self.root_collection = Collection.get_first_root_node()
        self.reports_collection = self.root_collection.add_child(name="Reports")

        # Groups
        doc_changers_group = Group.objects.create(name="Document changers")
        GroupCollectionPermission.objects.create(
            group=doc_changers_group,
            collection=self.root_collection,
            permission=change_doc_permission
        )

        report_changers_group = Group.objects.create(name="Report changers")
        GroupCollectionPermission.objects.create(
            group=report_changers_group,
            collection=self.reports_collection,
            permission=change_doc_permission
        )

        report_adders_group = Group.objects.create(name="Report adders")
        GroupCollectionPermission.objects.create(
            group=report_adders_group,
            collection=self.reports_collection,
            permission=add_doc_permission
        )

        # Users
        User = get_user_model()

        self.superuser = User.objects.create_superuser(
            'superuser', '[email protected]', 'password'
        )
        self.inactive_superuser = User.objects.create_superuser(
            'inactivesuperuser', '[email protected]', 'password', is_active=False
        )

        # a user with change_document permission through the 'Document changers' group
        self.doc_changer = User.objects.create_user(
            'docchanger', '[email protected]', 'password'
        )
        self.doc_changer.groups.add(doc_changers_group)

        # a user that has change_document permission, but is inactive
        self.inactive_doc_changer = User.objects.create_user(
            'inactivedocchanger', '[email protected]', 'password', is_active=False
        )
        self.inactive_doc_changer.groups.add(doc_changers_group)

        # a user with change_document permission on reports via the report_changers group
        self.report_changer = User.objects.create_user(
            'reportchanger', '[email protected]', 'password'
        )
        self.report_changer.groups.add(report_changers_group)

        # a user with add_document permission on reports via the report_adders group
        self.report_adder = User.objects.create_user(
            'reportadder', '[email protected]', 'password'
        )
        self.report_adder.groups.add(report_adders_group)

        # a user with no permissions
        self.useless_user = User.objects.create_user(
            'uselessuser', '[email protected]', 'password'
        )

        self.anonymous_user = AnonymousUser()

        # Documents

        # a document in the root owned by 'reportchanger'
        self.changer_doc = Document.objects.create(
            title="reportchanger's document", collection=self.root_collection,
            uploaded_by_user=self.report_changer
        )

        # a document in reports owned by 'reportchanger'
        self.changer_report = Document.objects.create(
            title="reportchanger's report", collection=self.reports_collection,
            uploaded_by_user=self.report_changer
        )

        # a document in reports owned by 'reportadder'
        self.adder_report = Document.objects.create(
            title="reportadder's report", collection=self.reports_collection,
            uploaded_by_user=self.report_adder
        )

        # a document in reports owned by 'uselessuser'
        self.useless_report = Document.objects.create(
            title="uselessuser's report", collection=self.reports_collection,
            uploaded_by_user=self.useless_user
        )

        # a document with no owner
        self.anonymous_report = Document.objects.create(
            title="anonymous report", collection=self.reports_collection
        )

Example 45

Project: transifex
Source File: models.py
View license
def action_logging(user, object_list, action_type, message=None, context=None):
    """
    Add ActionLog using a set of parameters.

    user:
      The user that did the action.
    object_list:
      A list of objects that should be created the actionlog for.
    action_type:
      Label of a type of action from the NoticeType model.
    message:
      A message to be included at the actionlog. If no message is passed
      it will try do render a message using the notice.html from the
      notification application.
    context:
      To render the message using the notification files, sometimes it is
      necessary to pass some vars by using a context.

    Usage::

        al = 'project_added'
        context = {'project': object}
        action_logging(request.user, [object], al , context=context):
    """
    if not getattr(settings, 'ACTIONLOG_ENABLED', None):
        return

    if context is None:
        context = {}

    if message is None:
        message = _get_formatted_message(action_type, context)

    action_type_obj = NoticeType.objects.get(label=action_type)

    time = datetime.datetime.now()

    try:
        for object in object_list:
            l = LogEntry(
                    user_id = user.pk,
                    content_type = ContentType.objects.get_for_model(object),
                    object_id = object.pk,
                    object_name = force_unicode(object)[:200],
                    action_type = action_type_obj,
                    action_time = time,
                    message = message)
            l.save()
            if settings.USE_REDIS:
                log_to_queues(object, user, time, action_type_obj, message)
    except TypeError:
        raise TypeError("The 'object_list' parameter must be iterable")

Example 46

Project: xadmin
Source File: bookmark.py
View license
    def get_context(self, context):
        if not self.show_bookmarks:
            return context

        bookmarks = []

        current_qs = '&'.join(['%s=%s' % (k, v) for k, v in sorted(
            filter(lambda i: bool(i[1] and (i[0] in (COL_LIST_VAR, ORDER_VAR, SEARCH_VAR) or i[0].startswith(FILTER_PREFIX)
                                            or i[0].startswith(RELATE_PREFIX))), self.request.GET.items()))])

        model_info = (self.opts.app_label, self.opts.model_name)
        has_selected = False
        menu_title = _(u"Bookmark")
        list_base_url = reverse('xadmin:%s_%s_changelist' %
                                model_info, current_app=self.admin_site.name)

        # local bookmarks
        for bk in self.list_bookmarks:
            title = bk['title']
            params = dict(
                [(FILTER_PREFIX + k, v) for (k, v) in bk['query'].items()])
            if 'order' in bk:
                params[ORDER_VAR] = '.'.join(bk['order'])
            if 'cols' in bk:
                params[COL_LIST_VAR] = '.'.join(bk['cols'])
            if 'search' in bk:
                params[SEARCH_VAR] = bk['search']
            def check_item(i):
                return bool(i[1]) or i[1] == False
            bk_qs = '&'.join(['%s=%s' % (k, v) for k, v in sorted(filter(check_item, params.items()))])

            url = list_base_url + '?' + bk_qs
            selected = (current_qs == bk_qs)

            bookmarks.append(
                {'title': title, 'selected': selected, 'url': url})
            if selected:
                menu_title = title
                has_selected = True

        content_type = ContentType.objects.get_for_model(self.model)
        bk_model_info = (Bookmark._meta.app_label, Bookmark._meta.model_name)
        bookmarks_queryset = Bookmark.objects.filter(
            content_type=content_type,
            url_name='xadmin:%s_%s_changelist' % model_info
        ).filter(Q(user=self.user) | Q(is_share=True))

        for bk in bookmarks_queryset:
            selected = (current_qs == bk.query)

            if self.has_change_permission(bk):
                change_or_detail = 'change'
            else:
                change_or_detail = 'detail'

            bookmarks.append({'title': bk.title, 'selected': selected, 'url': bk.url, 'edit_url':
                              reverse('xadmin:%s_%s_%s' % (bk_model_info[0], bk_model_info[1], change_or_detail),
                                      args=(bk.id,))})
            if selected:
                menu_title = bk.title
                has_selected = True

        post_url = reverse('xadmin:%s_%s_bookmark' % model_info,
                           current_app=self.admin_site.name)

        new_context = {
            'bk_menu_title': menu_title,
            'bk_bookmarks': bookmarks,
            'bk_current_qs': current_qs,
            'bk_has_selected': has_selected,
            'bk_list_base_url': list_base_url,
            'bk_post_url': post_url,
            'has_add_permission_bookmark': self.admin_view.request.user.has_perm('xadmin.add_bookmark'),
            'has_change_permission_bookmark': self.admin_view.request.user.has_perm('xadmin.change_bookmark')
        }
        context.update(new_context)
        return context

Example 47

Project: pootle
Source File: config.py
View license
@pytest.mark.django_db
def test_config_set(no_config_env):

    # set site-wide config
    Config.objects.set_config("foo")
    _test_config_ob(
        key=u"foo",
        value="",
        content_type=None,
        object_pk=None)
    Config.objects.set_config("foo", "bar")
    _test_config_ob(
        key=u"foo",
        value="bar",
        content_type=None,
        object_pk=None)

    project = Project.objects.get(code="project0")
    project_pk = project.pk
    project_ct = ContentType.objects.get_for_model(project)

    # set config for all projects
    Config.objects.set_config(key="foo", model=Project)
    _test_config_ob(
        key="foo",
        value="",
        content_type=project_ct,
        object_pk=None,
        content_object=None)
    Config.objects.set_config(key="foo", value="bar", model=Project)
    _test_config_ob(
        key="foo",
        value="bar",
        content_type=project_ct,
        object_pk=None,
        content_object=None)

    # set config for project
    Config.objects.set_config(key="foo", model=project)
    _test_config_ob(
        key="foo",
        value="",
        content_type=project_ct,
        object_pk=str(project_pk),
        content_object=project)
    # reset config for project
    Config.objects.set_config(key="foo", value="bar", model=project)
    _test_config_ob(
        key="foo",
        value="bar",
        content_type=project_ct,
        object_pk=str(project_pk),
        content_object=project)

Example 48

Project: django-expando
Source File: models.py
View license
    def save(self, *args, **kwargs):
        """ Saves the instance and all its expando fields (possible opt-out).
        """
        skip_expando_fields = kwargs.pop('skip_expando_fields', False)

        # Original save, assigns the primary key
        r = super(ExpandoModel, self).save(*args, **kwargs)

        if not skip_expando_fields:
            assert self._get_safe_pk()

            names, db_names = self.get_expando_names(), set()

            # For all expando fields in the db...
            for ef in self.get_expando_qs():

                # register their names...
                db_names.add(ef.key)
                if ef.key in self.__dict__:

                    # do they need update to db?
                    val = smart_unicode(self.__dict__[ef.key])
                    if val != ef.value:
                        ef.value = val
                        ef.save()
                else:
                    # or they were deleted in the instance?
                    ef.delete()

            ct = ContentType.objects.get_for_model(self)

            # Add all instance's expandos not present in the db.
            for key in names - db_names:
                Expando(
                    content_type = ct,
                    object_pk = smart_unicode(self._get_safe_pk()),
                    key = key,
                    value = smart_unicode(self.__dict__[key])
                ).save(force_insert=True)

        return r

Example 49

Project: pinax-likes
Source File: utils.py
View license
def widget_context(user, obj):
    ct = ContentType.objects.get_for_model(obj)
    config = get_config(obj)
    like_count = Like.objects.filter(
        receiver_content_type=ct,
        receiver_object_id=obj.pk
    ).count()
    if like_count == 1:
        counts_text = config["count_text_singular"]
    else:
        counts_text = config["count_text_plural"]

    can_like = user.has_perm("likes.can_like", obj)

    ctx = {
        "can_like": can_like,
        "like_count": like_count,
        "counts_text": counts_text,
        "object": obj,
    }

    if can_like:
        liked = Like.objects.filter(
            sender=user,
            receiver_content_type=ct,
            receiver_object_id=obj.pk
        ).exists()

        if liked:
            like_text = config["like_text_on"]
            like_class = config["css_class_on"]
        else:
            like_text = config["like_text_off"]
            like_class = config["css_class_off"]

        ctx.update({
            "like_url": reverse("pinax_likes:like_toggle", kwargs={
                "content_type_id": ct.id,
                "object_id": obj.pk
            }),
            "liked": liked,
            "like_text": like_text,
            "like_class": like_class
        })
    else:
        ctx.update({
            "like_text": config["like_text_off"],
            "like_class": config["css_class_off"],
        })

    return ctx

Example 50

Project: django-sharing
Source File: tests.py
View license
    def test_has_perm(self):
        # Return False if 'view' permission is not found for user.
        self.failIf(self.user.has_perm('view', self.obj))
        
        # Return False if 'change' permission is not found for user.
        self.failIf(self.user.has_perm('change', self.obj))
        
        # Return False if 'delete' permission is not found for user.
        self.failIf(self.user.has_perm('delete', self.obj))
        
        # Return False if 'view' permission is not found for group user.
        self.failIf(self.group_user.has_perm('view', self.obj))
        
        # Return False if 'change' permission is not found for group user.
        self.failIf(self.group_user.has_perm('change', self.obj))
        
        # Return False if 'delete' permission is not found for group user.
        self.failIf(self.group_user.has_perm('delete', self.obj))
       
        # Setup user share.
        UserShare.objects.create(
            user=self.user,
            can_view=True,
            can_change=True,
            can_delete=True,
            content_type=ContentType.objects.get_for_model(self.obj),
            object_id=self.obj.id,
        )
        
        # Return True if 'view' permission is found for user.
        self.failUnless(self.user.has_perm('view', self.obj))
        
        # Return True if 'change' permission is found for user.
        self.failUnless(self.user.has_perm('change', self.obj))
        
        # Return True if 'delete' permission is found for user.
        self.failUnless(self.user.has_perm('delete', self.obj))
       
       # Group share has not yet been setup, so should all still be unpermitted.
        # Return False if 'view' permission is not found for group user.
        self.failIf(self.group_user.has_perm('view', self.obj))
        
        # Return False if 'change' permission is not found for group user.
        self.failIf(self.group_user.has_perm('change', self.obj))
        
        # Return False if 'delete' permission is not found for group user.
        self.failIf(self.group_user.has_perm('delete', self.obj))
        
        # Setup group share.
        GroupShare.objects.create(
            group=self.group,
            can_view=True,
            can_change=True,
            can_delete=True,
            content_type=ContentType.objects.get_for_model(self.obj),
            object_id=self.obj.id,
        )
        
        # Return True if 'view' permission is found for group user.
        self.failUnless(self.group_user.has_perm('view', self.obj))
        
        # Return True if 'change' permission is found for group user.
        self.failUnless(self.group_user.has_perm('change', self.obj))
        
        # Return True if 'delete' permission is found for group user.
        self.failUnless(self.group_user.has_perm('delete', self.obj))