Ejemplo n.º 1
0
 def formfield_for_dbfield(self, db_field, **kwargs):
     if is_category_fk(db_field):
         fld = super(GenericInlineModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)#FIXME get fld.queryset different way
         kwargs.update({
             'model': self.model,
             'user': self._magic_user
         })
         return fields.CategoryChoiceField(fld.queryset, **kwargs)
     return options.formfield_for_dbfield_factory(self, db_field, **kwargs)
Ejemplo n.º 2
0
 def formfield_for_dbfield(self, db_field, **kwargs):
     if is_category_fk(db_field):
         kwargs['super_field'] = super(NewmanModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
     kwargs.update({
         'model': self.model,
         'user': self.user,
         'instance': self.__dict__.get('_magic_instance', None),
     })
     return formfield_for_dbfield_factory(self, db_field, **kwargs)
Ejemplo n.º 3
0
 def formfield_for_dbfield(self, db_field, **kwargs):
     if is_category_fk(db_field):
         kwargs['super_field'] = super(NewmanInlineModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
     inst = None
     # Inlined object is requested by RichTextField (the field needs to lookup SrcText)
     if hasattr(self, '_magic_instance') and self._magic_instance:
         instances = self.model.objects.filter(**{self._magic_fk.name: self._magic_instance.pk})
         inst = None
         if instances:
             inst = list(instances)
     kwargs.update({
         'model': self.model,
         'user': self._magic_user,
         'instance': inst,
     })
     return formfield_for_dbfield_factory(self, db_field, **kwargs)
Ejemplo n.º 4
0
def formfield_for_dbfield_factory(cls, db_field, **kwargs):
    formfield_overrides = dict(FORMFIELD_FOR_DBFIELD_DEFAULTS, **cls.formfield_overrides)
    custom_param_names = ('request', 'user', 'model', 'super_field', 'instance')
    custom_params = {}
    # move custom kwargs from kwargs to custom_params
    for key in kwargs:
        if key not in custom_param_names:
            continue
        custom_params[key] = kwargs[key]
        if key == 'request':
            custom_params['user'] = custom_params[key].user
    for key in custom_param_names:
        kwargs.pop(key, None)

    if db_field.choices:
        return db_field.formfield(**kwargs)

    for css_class, rich_text_fields in getattr(cls, 'rich_text_fields', {}).iteritems():
        if db_field.name in rich_text_fields:
            kwargs.update({
                'required': not db_field.blank,
                'label': db_field.verbose_name,
                'field_name': db_field.name,
                'instance': custom_params.get('instance', None),
                'model': custom_params.get('model'),
            })
            rich_text_field = fields.NewmanRichTextField(**kwargs)
            if css_class:
                rich_text_field.widget.attrs['class'] += ' %s' % css_class
            return rich_text_field

    # date and datetime fields
    if isinstance(db_field, models.DateTimeField):
        kwargs.update({
            'widget': widgets.DateTimeWidget,
        })
        return db_field.formfield(**kwargs)
    elif isinstance(db_field, models.DateField):
        kwargs.update({
            'widget': widgets.DateWidget,
        })
        return db_field.formfield(**kwargs)

    if isinstance(db_field, models.ImageField):
        # we accept only (JPEG) images with RGB color profile.
        kwargs.update({
            'label': db_field.verbose_name,
        })
        return fields.RGBImageField(db_field, **kwargs)

    if db_field.name in cls.raw_id_fields and isinstance(db_field, models.ForeignKey):
        kwargs.update({
            'label': db_field.verbose_name,
            'widget': widgets.ForeignKeyRawIdWidget(db_field.rel),
            'required': not db_field.blank,
        })
        return fields.RawIdField(db_field.rel.to.objects.all(), **kwargs)

    if db_field.name in getattr(cls, 'suggest_fields', {}).keys() \
                        and isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
        kwargs.update({
            'required': not db_field.blank,
            'label': db_field.verbose_name,
            'model': cls.model,
            'lookup': cls.suggest_fields[db_field.name]
        })
        return fields.AdminSuggestField(db_field, **kwargs)

    if isinstance(db_field, models.ForeignKey) and issubclass(db_field.rel.to, ContentType):
        kwargs['widget'] = widgets.ContentTypeWidget
        return db_field.formfield(**kwargs)
    elif db_field.name in ('target_id', 'source_id', 'object_id', 'related_id', 'obj_id'):
        kwargs['widget'] = widgets.ForeignKeyGenericRawIdWidget
        return db_field.formfield(**kwargs)

    if db_field.name == 'order':
        kwargs['widget'] = widgets.OrderFieldWidget
        return db_field.formfield(**kwargs)

    # magic around restricting category choices in all ForeignKey (related to Category) fields
    if is_category_fk(db_field) and 'model' in custom_params:
        kwargs.update({
            'model': custom_params['model'],
            'user': custom_params['user']
        })
        super_qs = custom_params['super_field'].queryset
        return fields.CategoryChoiceField(super_qs, **kwargs)

    if db_field.__class__ in formfield_overrides:
        kwargs = dict(formfield_overrides[db_field.__class__], **kwargs)
        return db_field.formfield(**kwargs)

    return db_field.formfield(**kwargs)
Ejemplo n.º 5
0
        lookup_var = self.get_lookup_kwarg()
        for cat in user_category_filter(qs, self.user):
            link = ( cat, {lookup_var: cat.pk})
            self.links.append(link)
        return True

    def generate_choice(self, **lookup_kwargs):
        category_id = lookup_kwargs.get(self.get_lookup_kwarg(), '')
        if not category_id or not category_id.isdigit():
            return None
        try:
            thing = Category.objects.get( pk=int(category_id) )
        except (Category.MultipleObjectsReturned, Category.DoesNotExist):
            return None
        return thing.__unicode__()
NewmanCategoryFilter.register_insert(lambda field: is_category_fk(field), NewmanCategoryFilter)

"""
site_lookup = lambda fspec: '%s__%s__exact' % (fspec.f.name, fspec.f.rel.get_related_field().name)
@filter_spec(lambda field: is_site_fk(field), site_lookup)
def site_field_filter(fspec):
    category_ids = get_user_config(fspec.user, CATEGORY_FILTER)
    if not category_ids:
        if not fspec.user.is_superuser:
            category_ids = m.DenormalizedCategoryUserRole.objects.root_categories_by_user(fspec.user)
        else:
            category_ids = Category.objects.filter(tree_parent=None)
    qs = Category.objects.filter(pk__in=category_ids)
    sites = map(lambda c: c.site, qs)
    for site in sites:
        #category__site__id__exact=1
Ejemplo n.º 6
0
 def test_is_category_fk_title_not_fk(self):
     tools.assert_false(is_category_fk(self.article_fields['title']))
Ejemplo n.º 7
0
 def test_is_category_fk_success(self):
     tools.assert_true(is_category_fk(self.article_fields['category']))