Beispiel #1
0
    def test_modelform_factory_exclude_name(self):
        self.form = autocomplete_light.modelform_factory(self.model_class,
                exclude=['name'])()

        self.assertNotInForm('name')
        self.assertExpectedFormField()
        self.assertIsAutocomplete('noise')
Beispiel #2
0
    def test_modelform_factory_fields_name(self):
        self.form = autocomplete_light.modelform_factory(self.model_class,
                fields=['name'])()

        self.assertInForm('name')
        self.assertNotInForm('relation')
        self.assertNotInForm('noise')
Beispiel #3
0
    def test_modelform_factory_autocomplete_exclude_relation(self):
        self.form = autocomplete_light.modelform_factory(self.model_class,
                autocomplete_exclude=['relation'])()

        self.assertNotInForm('relation')
        self.assertInForm('name')
        self.assertIsAutocomplete('noise')
Beispiel #4
0
    def test_modelform_factory_fields_relation(self):
        self.form = autocomplete_light.modelform_factory(self.model_class,
                fields=['relation'])()

        self.assertExpectedFormField()
        self.assertNotInForm('name')
        self.assertNotInForm('noise')
Beispiel #5
0
 def get_changelist_form(self, request, **kwargs):
     defaults = {
         "form": self.form,
         "formfield_callback": curry(self.formfield_for_dbfield,
             request=request),
         }
     defaults.update(kwargs)
     return autocomplete_light.modelform_factory(self.model, **defaults)
Beispiel #6
0
    def test_modelform_factory_does_not_warn(self):
        # fix for #257
        with mock.patch('warnings.warn') as warn:
            self.form = autocomplete_light.modelform_factory(self.model_class,
                    fields='__all__')()
            self.assertEqual(warn.call_count, 0)

        self.assertExpectedFormField()
Beispiel #7
0
    def test_modelform_factory_autocomplete_fields_relation(self):
        if VERSION < (1, 7):
            fields = None
        else:
            fields = '__all__'

        self.form = autocomplete_light.modelform_factory(self.model_class,
                autocomplete_fields=['relation'], fields=fields)()

        self.assertExpectedFormField()
        self.assertNotIsAutocomplete('noise')
        self.assertInForm('name')
Beispiel #8
0
    def test_modelform_factory_autocomplete_names(self):
        SpecialAutocomplete = self.get_new_autocomplete_class()
        autocomplete_light.registry.register(SpecialAutocomplete)

        ModelForm = autocomplete_light.modelform_factory(self.model_class,
            autocomplete_names={'relation': 'SpecialAutocomplete'})

        self.form = ModelForm()

        self.assertInForm('name')
        self.assertIsAutocomplete('relation')
        self.assertIsAutocomplete('noise')

        self.assertTrue(issubclass(self.form.fields['relation'].autocomplete,
                                   SpecialAutocomplete))
Beispiel #9
0
    def inline_instances(self):
        inline_instances = []

        for name, value in self.model_class.__dict__.items():
            if not isinstance(value, ForeignRelatedObjectsDescriptor):
                continue

            model = getattr(self.model_class, name).related.model

            cls = inlineformset_factory(self.model_class, model, form=modelform_factory(model), extra=25)

            instance = cls(prefix=name, *self.inline_args, **self.inline_kwargs)
            instance.name = instance.model._meta.verbose_name_plural
            inline_instances.append(instance)

        return inline_instances
Beispiel #10
0
    def form_class(self):
        attributes = self.form_model.enabled_field_set

        form = modelform_factory(self.form_model.contenttype.model_class(), fields=[a.name for a in attributes])

        for attribute in attributes:
            name = attribute.name

            if attribute.verbose_name:
                form.base_fields[name].label = attribute.verbose_name

            if attribute.help_text:
                form.base_fields[name].help_text = attribute.help_text

        form.helper = FormHelper()
        form.helper.layout = self.form_model.to_crispy()
        form.helper.form_tag = False
        return form
Beispiel #11
0
class UserContactAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(UserContact)
Beispiel #12
0
class ProfileAdmin(admin.ModelAdmin):
    list_display = ('id', 'username', 'organization',)
    search_fields = ('username', 'organization', 'profile', )
    autocomplete_light.modelform_factory(Profile, fields='__all__')
    add_form_template = 'admin/auth/user/add_form.html'
    change_user_password_template = None
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
        (_('Extended profile'), {'fields': ('organization', 'profile',
                                            'position', 'voice', 'fax',
                                            'delivery', 'city', 'area',
                                            'zipcode', 'country',
                                            'keywords')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'password1', 'password2')}
         ),
    )
    form = ProfileChangeForm
    add_form = ProfileCreationForm
    change_password_form = AdminPasswordChangeForm
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
    search_fields = ('username', 'first_name', 'last_name', 'email')
    ordering = ('username',)
    filter_horizontal = ('groups', 'user_permissions',)

    def get_fieldsets(self, request, obj=None):
        if not obj:
            return self.add_fieldsets
        return super(ProfileAdmin, self).get_fieldsets(request, obj)

    def get_form(self, request, obj=None, **kwargs):
        """
        Use special form during user creation
        """
        defaults = {}
        if obj is None:
            defaults.update({
                'form': self.add_form,
                'fields': admin.utils.flatten_fieldsets(self.add_fieldsets),
            })
        defaults.update(kwargs)
        return super(ProfileAdmin, self).get_form(request, obj, **defaults)

    def get_urls(self):
        from django.conf.urls import patterns
        return patterns('',
                        (r'^(\d+)/password/$',
                         self.admin_site.admin_view(self.user_change_password))
                        ) + super(ProfileAdmin, self).get_urls()

    def lookup_allowed(self, lookup, value):
        # See #20078: we don't want to allow any lookups involving passwords.
        if lookup.startswith('password'):
            return False
        return super(ProfileAdmin, self).lookup_allowed(lookup, value)

    @sensitive_post_parameters_m
    @csrf_protect_m
    @transaction.atomic
    def add_view(self, request, form_url='', extra_context=None):
        # It's an error for a user to have add permission but NOT change
        # permission for users. If we allowed such users to add users, they
        # could create superusers, which would mean they would essentially have
        # the permission to change users. To avoid the problem entirely, we
        # disallow users from adding users if they don't have change
        # permission.
        if not self.has_change_permission(request):
            if self.has_add_permission(request) and settings.DEBUG:
                # Raise Http404 in debug mode so that the user gets a helpful
                # error message.
                raise Http404(
                    'Your user does not have the "Change user" permission. In '
                    'order to add users, Django requires that your user '
                    'account have both the "Add user" and "Change user" '
                    'permissions set.')
            raise PermissionDenied
        if extra_context is None:
            extra_context = {}
        username_field = self.model._meta.get_field(self.model.USERNAME_FIELD)
        defaults = {
            'auto_populated_fields': (),
            'username_help_text': username_field.help_text,
        }
        extra_context.update(defaults)
        return super(ProfileAdmin, self).add_view(request, form_url,
                                                  extra_context)

    @sensitive_post_parameters_m
    def user_change_password(self, request, id, form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = get_object_or_404(self.get_queryset(request), pk=id)
        if request.method == 'POST':
            form = self.change_password_form(user, request.POST)
            if form.is_valid():
                form.save()
                change_message = self.construct_change_message(
                    request,
                    form,
                    None)
                self.log_change(request, user, change_message)
                msg = ugettext('Password changed successfully.')
                messages.success(request, msg)
                return HttpResponseRedirect('..')
        else:
            form = self.change_password_form(user)

        fieldsets = [(None, {'fields': list(form.base_fields)})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'title': _('Change password: %s') % escape(user.get_username()),
            'adminForm': adminForm,
            'form_url': form_url,
            'form': form,
            'is_popup': IS_POPUP_VAR in request.REQUEST,
            'add': True,
            'change': False,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_absolute_url': False,
            'opts': self.model._meta,
            'original': user,
            'save_as': False,
            'show_save': True,
        }
        return TemplateResponse(request,
                                self.change_user_password_template or
                                'admin/auth/user/change_password.html',
                                context, current_app=self.admin_site.name)

    def response_add(self, request, obj, post_url_continue=None):
        """
        Determines the HttpResponse for the add_view stage. It mostly defers to
        its superclass implementation but is customized because the User model
        has a slightly different workflow.
        """
        # We should allow further modification of the user just added i.e. the
        # 'Save' button should behave like the 'Save and continue editing'
        # button except in two scenarios:
        # * The user has pressed the 'Save and add another' button
        # * We are adding a user in a popup
        if '_addanother' not in request.POST and IS_POPUP_VAR not in request.POST:
            request.POST['_continue'] = 1
        return super(ProfileAdmin, self).response_add(request, obj,
                                                      post_url_continue)
Beispiel #13
0
class PledgedItemInline(admin.TabularInline):
    form = autocomplete_light.modelform_factory(PledgedItem)
    model = PledgedItem
    exclude = ['pledge_particulars']
    extra = 3
    formset = PledgedItemInlineFormset
Beispiel #14
0
 def get_form_class(self,*args,**kwargs):
     form = autocomplete_light.modelform_factory(self.model)
     #raise Exception(dir(form))
     if 'summary' in form.base_fields:
         form.base_fields['summary'].widget = CKEditorWidget()
     return form
Beispiel #15
0
class UserProfileInline(AdminImageMixin, admin.StackedInline):
    """UserProfile Inline model for UserAdmin."""
    model = UserProfile
    readonly_fields = ['date_vouched', 'vouched_by', 'basket_token']
    form = autocomplete_light.modelform_factory(UserProfile)
Beispiel #16
0
class IssueReportAdmin(BaseAdmin):
    form = autocomplete_light.modelform_factory(IssueReport, fields="__all__")
    fields = [('name', 'status'), 'type', 'report', 'report_duplicate', 'description',
              ('created_by', 'created_at'), ('reviewed_by', 'reviewed_at'), 'resolve_reason']
    readonly_fields = ['name', 'status', 'created_by', 'created_at', 'reviewed_by', 'reviewed_at', 'resolve_reason']
    list_display = ['name', 'type', 'created_by', 'created_at', 'status',]
    search_fields = ['name', 'created_by__name']
    list_filter = ['type', 'status']
    date_hierarchy = 'created_at'


    def get_fields(self, request, obj=None):
        """ Override to hide the 'usecase_duplicate' if type is not 'duplicate' """
        fields = super(IssueReportAdmin, self).get_fields(request, obj)

        if obj and obj.type != 'duplicate' and 'report_duplicate' in fields:
            fields.remove('report_duplicate')

        return fields


    def response_change(self, request, obj, *args, **kwargs):
        '''
        Override response_change method of admin/options.py to handle the click of
        newly added buttons
        '''

        # Get the metadata about self (it tells you app and current model)
        opts = self.model._meta

        # Get the primary key of the model object i.e. Issue Report
        pk_value = obj._get_pk_val()

        preserved_filters = self.get_preserved_filters(request)

        redirect_url = reverse('admin:%s_%s_change' %
                                   (opts.app_label, opts.model_name),
                                   args=(pk_value,))
        redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)

        # Check which button is clicked, handle accordingly.
        try:
            if "_investigate" in request.POST:
                obj.action_investigate(request.user)
                msg = "The issue is now being investigated."

            elif "_resolve" in request.POST:
                resolve_reason = request.POST.get('resolve_reason_text', '')
                obj.action_resolve(resolve_reason,request.user)
                msg = "The issue is now resolved because  " + resolve_reason

            elif "_reopen" in request.POST:
                obj.action_reopen(request.user)
                msg = "The issue has been re-opened."

            elif "_open" in request.POST:
                obj.action_open(request.user)
                msg = "The issue is now opened."

        except ValueError as e:
            # In case the state of the object is not suitable for the corresponding action,
            # model will raise the value exception with the appropriate message. Catch the
            # exception and show the error message to the user
            msg = e.message
            self.message_user(request, msg, messages.ERROR)

        self.message_user(request, msg, messages.SUCCESS)
        return HttpResponseRedirect(redirect_url)
Beispiel #17
0
class ResourceBaseAdmin(admin.ModelAdmin):
    list_display = ('id', 'title', 'date', 'category')
    list_display_links = ('id', )

    form = autocomplete_light.modelform_factory(ResourceBase)
Beispiel #18
0
class MyUserAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(User, fields='__all__')
Beispiel #19
0
 def get_form_class(self, **kwargs):
     return autocomplete_light.modelform_factory(self.model)
Beispiel #20
0
class DeviceAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(Device, fields='__all__')
import autocomplete_light

from .models import NonAdminAddAnotherModel

NonAdminAddAnotherModelForm = autocomplete_light.modelform_factory(
    NonAdminAddAnotherModel)
Beispiel #22
0
class PhotoAdmin(ModelAdmin):
    @staticmethod
    def _distance_between_two_points_on_sphere(lon_1, lat_1, lon_2, lat_2):
        import math

        rad = math.pi / 180.0
        equatorial_radius_meters = 6378137
        lon_1_rad = lon_1 * rad
        lat_1_rad = lat_1 * rad
        lon_2_rad = lon_2 * rad
        lat_2_rad = lat_2 * rad
        cos_angle = math.sin(lat_1_rad) * math.sin(lat_2_rad) + math.cos(
            lat_1_rad) * math.cos(lat_2_rad) * math.cos(lon_2_rad - lon_1_rad)

        if cos_angle >= 1:
            return 0

        angle = math.acos(cos_angle)
        return angle * equatorial_radius_meters

    def save_model(self, request, obj, form, change):
        if obj.lat and obj.lon and obj.bounding_circle_radius:
            # If an administrator sets a bounding circle, invalidate GeoTags outside of it
            all_photo_geo_tags = GeoTag.objects.filter(photo_id=obj.id)
            for geo_tag in all_photo_geo_tags:
                d = self._distance_between_two_points_on_sphere(
                    obj.lon, obj.lat, geo_tag.lon, geo_tag.lat)
                if d > obj.bounding_circle_radius:
                    geo_tag.is_correct = False
                else:
                    geo_tag.is_correct = True
                geo_tag.save()
        obj.save()

    def _invertcolors(self, id):
        from django.http.response import HttpResponse
        photo = Photo.objects.filter(pk=id).first()
        if photo:
            photo_path = settings.MEDIA_ROOT + "/" + str(photo.image)
            img = Image.open(photo_path)
            inverted_grayscale_image = ImageOps.invert(img).convert('L')
            inverted_grayscale_image.save(photo_path)
            photo.invert = not photo.invert
            sorl_delete(photo.image, delete_file=False)
            photo.light_save()
            return HttpResponse(u'Photo inverted!')

        return HttpResponse(u'Failed to invert photo!')

    extra_buttons = [
        {
            'url': '_invertcolors',
            'textname': _('Invert colors'),
            'func': _invertcolors
        },
    ]

    def change_view(self, request, object_id, form_url='', extra_context={}):
        extra_context['extra_buttons'] = self.extra_buttons
        return super(PhotoAdmin, self).change_view(request,
                                                   object_id,
                                                   form_url,
                                                   extra_context=extra_context)

    def get_urls(self):
        from django.conf.urls import url
        urls = super(PhotoAdmin, self).get_urls()
        my_urls = list((url(r'^(.+)/%(url)s/$' % b,
                            self.admin_site.admin_view(b['func']))
                        for b in self.extra_buttons))
        return my_urls + urls

    inlines = (AlbumPhotoInline, )

    form = autocomplete_light.modelform_factory(Photo, fields='__all__')
Beispiel #23
0
class DatingConfirmationAdmin(ModelAdmin):
    form = autocomplete_light.modelform_factory(DatingConfirmation,
                                                fields='__all__')
Beispiel #24
0
class MapLayerAdmin(admin.ModelAdmin):
    list_display = ('id', 'map', 'name')
    list_filter = ('map',)
    search_fields = ('map__title', 'name',)
    form = autocomplete_light.modelform_factory(MapLayer)
Beispiel #25
0
    def test_modelform_factory(self):
        self.form = autocomplete_light.modelform_factory(self.model_class)()

        self.assertExpectedFormField()
class VisitedCitiesAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(VisitedCities)
Beispiel #27
0
class PcaGrantInlineAdmin(admin.TabularInline):
    form = autocomplete_light.modelform_factory(Grant)
    model = PCAGrant
    verbose_name = 'Grant'
    verbose_name_plural = 'Grants'
    extra = 0
Beispiel #28
0
class NonAdminAddAnotherModelAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(NonAdminAddAnotherModel)
Beispiel #29
0
class VolunteerSiteAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(VolunteerSite)
    list_display = ('volunteer', 'supervisor', 'site_approval', 'contract',
                    'hours_confirmed', 'inactive')
    actions = [approve_site, reject_site, time_fulfilled]
    inlines = [HoursInline]
Beispiel #30
0
class GroupMembershipInline(admin.TabularInline):
    model = GroupMembership
    extra = 1
    form = autocomplete_light.modelform_factory(GroupMembership)
Beispiel #31
0
    def test_modelform_factory(self):
        self.form = autocomplete_light.modelform_factory(self.model_class)()

        self.assertExpectedFormField()
Beispiel #32
0
class CityAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(City)
    list_display = ('name', 'pincode', 'post')
    list_per_page = 25
    ordering = ['name']
    search_fields = ['name', 'pincode']
Beispiel #33
0
class AreaAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(Area, fields='__all__')
from django.views import generic
from django.forms.models import modelformset_factory

import autocomplete_light

from models import OutsideAdmin


OutsideAdminModelForm = autocomplete_light.modelform_factory(OutsideAdmin, widgets={
    'tags': autocomplete_light.TextWidget('TagAutocomplete'),})
OutsideAdminModelFormset = modelformset_factory(OutsideAdmin, form=OutsideAdminModelForm)


class FormsetView(generic.FormView):
    form_class = OutsideAdminModelFormset
    template_name = 'inlines_outside_admin/formset.html'
    success_url = '/inlines_outside_admin/'

    def form_valid(self, form):
        form.save()
        return super(FormsetView, self).form_valid(form)
Beispiel #35
0
class AlbumPhotoAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(AlbumPhoto, fields='__all__')
Beispiel #36
0
 def get_form_class(self,**kwargs):
     return autocomplete_light.modelform_factory(self.model)
Beispiel #37
0
class AlbumAdmin(ModelAdmin):
    form = autocomplete_light.modelform_factory(Album, fields='__all__')
Beispiel #38
0
class TransactionCommentPlaceInline(admin.TabularInline):
    model = Transaction.comment_places.through
    form = autocomplete_light.modelform_factory(Place, exclude=[])
    extra = 10
Beispiel #39
0
class PointsAdmin(ModelAdmin):
    form = autocomplete_light.modelform_factory(Points, fields='__all__')
Beispiel #40
0
import autocomplete_light

from .models import NonAdminAddAnotherModel

NonAdminAddAnotherModelForm = autocomplete_light.modelform_factory(
    NonAdminAddAnotherModel)
Beispiel #41
0
class ProfileAdmin(ModelAdmin):
    form = autocomplete_light.modelform_factory(Profile, fields='__all__')
Beispiel #42
0
class ContactRoleAdmin(admin.ModelAdmin):
    model = ContactRole
    list_display_links = ('id', )
    list_display = ('id', 'contact', 'resource', 'role')
    list_editable = ('contact', 'resource', 'role')
    form = autocomplete_light.modelform_factory(ContactRole)
Beispiel #43
0
class GeoTagAdmin(ModelAdmin):
    form = autocomplete_light.modelform_factory(GeoTag, fields='__all__')
Beispiel #44
0
class ItemModelAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(ItemModel)
Beispiel #45
0
class VideoAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(Video, fields='__all__')