def validate(self, attrs): """ Ensure that the media being attached is legit """ from localground.apps.site.models import Base view = self.context.get('view') object_id = attrs.get('entity_id') or view.kwargs.get('id') try: object_id = int(object_id) except Exception: raise serializers.ValidationError('%s must be a whole number' % object_id) try: # get access to URL params throught the view cls = Base.get_model( model_name_plural=view.kwargs.get('entity_name_plural') ) except: raise serializers.ValidationError( '\"%s\" is not a valid media type' % view.kwargs.get('entity_type')) try: cls.objects.get(id=object_id) except cls.DoesNotExist: raise serializers.ValidationError( '%s #%s does not exist in the system' % (cls.model_name, object_id)) return attrs
def validate(self, attrs): """ Ensure that the media being attached is legit """ from localground.apps.site.models import Base view = self.context.get('view') object_id = attrs.get('entity_id') or view.kwargs.get('id') try: object_id = int(object_id) except Exception: raise serializers.ValidationError('%s must be a whole number' % object_id) try: # get access to URL params throught the view cls = Base.get_model( model_name_plural=view.kwargs.get('entity_name_plural')) except Exception: raise serializers.ValidationError( '\"%s\" is not a valid media type' % view.kwargs.get('entity_type')) try: cls.objects.get(id=object_id) except cls.DoesNotExist: raise serializers.ValidationError( '%s #%s does not exist in the system' % (cls.model_name, object_id)) return attrs
def delete_batch(request, object_type_plural): from django.http import HttpResponse import json r = request.POST ModelClass = Base.get_model(model_name_plural=object_type_plural) object_ids = r.getlist('id') projects = [] num_deletes = 0 message = '' if len(object_ids) > 0: groups = list(ModelClass.objects.filter(id__in=object_ids)) for g in groups: g.delete() num_deletes = num_deletes + 1 message = message + \ '%s %s(s) were deleted.' % (num_deletes, ModelClass.model_name) return HttpResponse(json.dumps({'message': message}))
def to_internal_value(self, value): ''' This is a hack to do some pre-validation. The building of the GenericRelations must be done in the view itself b/c it needs access to the saved instance. ''' import json if value: try: entities = json.loads(value) except Exception: raise serializers.ValidationError('Error parsing JSON') for child in entities: try: overlay_type = child['overlay_type'] ids = child['ids'] except Exception: raise serializers.ValidationError( '%s must have an overlay_type and an ids attribute' % child) if not isinstance(ids, list): raise serializers.ValidationError( '%s must be a list' % ids ) for id in ids: # ensure that the requested child item exists: from localground.apps.site.models import Base try: obj = Base.get_model( model_name=overlay_type ).objects.get(id=id) except Exception: raise serializers.ValidationError( 'No %s object exists with id=%s' % ( overlay_type, id) ) # this exception prevents the 'entities' dictionary from being # directly applied to the entities many-to-many (which is impossible) # to specify before the object has been created. raise serializers.SkipField()
def to_internal_value(self, value): ''' This is a hack to do some pre-validation. The building of the GenericRelations must be done in the view itself b/c it needs access to the saved instance. ''' import json if value: try: entities = json.loads(value) except Exception: raise serializers.ValidationError('Error parsing JSON') for child in entities: try: overlay_type = child['overlay_type'] ids = child['ids'] except Exception: raise serializers.ValidationError( '%s must have an overlay_type and an ids attribute' % child) if not isinstance(ids, list): raise serializers.ValidationError('%s must be a list' % ids) for id in ids: # ensure that the requested child item exists: from localground.apps.site.models import Base try: obj = Base.get_model( model_name=overlay_type).objects.get(id=id) except Exception: raise serializers.ValidationError( 'No %s object exists with id=%s' % (overlay_type, id)) # this exception prevents the 'entities' dictionary from being # directly applied to the entities many-to-many (which is impossible) # to specify before the object has been created. raise serializers.SkipField()
def to_internal_value(self, data): from localground.apps.site.models import Base cls = Base.get_model(model_name=data) return cls.get_content_type()
def object_list_form( request, object_type_plural, return_message=None, embed=False): context = RequestContext(request) ModelClass = Base.get_model(model_name_plural=object_type_plural) template_name = 'profile/%s.html' % ModelClass.model_name_plural.replace( ' ', '-') r = request.POST or request.GET objects = ModelClass.objects.get_objects( user=request.user, request=request, context=context ) #return HttpResponse(objects.query) per_page = 10 def getModelClassFormSet(**kwargs): # uses Django 1.2 workaround documented here: # https://groups.google.com/forum/?fromgroups=#!topic/django-users/xImbCAbmfuc from django.forms.models import modelformset_factory def create_formfield(f, **kwargs): return f.formfield(**kwargs) return modelformset_factory( ModelClass, max_num=0, formfield_callback=create_formfield, **kwargs ) ModelClassFormSet = getModelClassFormSet( form=ModelClass.inline_form( request.user)) if request.method == "POST": modelformset = ModelClassFormSet( request.POST, queryset=objects) # objects if modelformset.is_valid(): num_updates = 0 for form in modelformset.forms: if form.has_changed(): instance = form.instance instance.last_updated_by = request.user instance.time_stamp = datetime.now() instance.save() num_updates += 1 if num_updates > 0: context.update({'message': '%s %s have been updated' % ( num_updates, ModelClass.model_name_plural)}) else: context.update({'warning_message': '%s %s have been updated' % ( num_updates, ModelClass.model_name_plural)}) else: context.update({ 'error_message': 'There was an error updating the %s' % ModelClass.model_name_plural }) else: start = 0 if r.get('page') is not None: start = (int(r.get('page')) - 1) * per_page # Hack: somehow, calling the ".all()" method slices the queryset (LIMIT BY), # rather than converting the queryset to a list (which we don't want). modelformset = ModelClassFormSet( queryset=objects[ start:start + per_page]) #modelformset = ModelClassFormSet(queryset=objects[start:start+per_page]) context.update({ 'formset': modelformset, 'embed': embed, 'page_title': 'My %s' % ModelClass.model_name_plural.capitalize(), 'username': request.user.username, 'url': '%s?1=1' % ModelClass.listing_url(), 'delete_url': ModelClass.batch_delete_url(), 'create_url': ModelClass.create_url() + 'embed/', 'page_title': 'My %s' % ModelClass.model_name_plural.capitalize(), 'user': request.user, 'object_name_plural': ModelClass.model_name_plural, 'object_type': ModelClass.model_name }) if context.get('filter_fields'): context.update({'url': '%s?query=%s' % (ModelClass.listing_url(), context.get('sql')), }) else: context.update({ 'filter_fields': ModelClass.get_filter_fields(), 'sql': '', 'has_filters': False }) context.update(prep_paginator(request, objects, per_page=per_page)) if request.user.is_superuser: context.update({'users': Project.get_users()}) return render_to_response(template_name, context)
def create_update_group_with_sharing( request, action, object_type_plural, object_id=None, embed=False, template="profile/create_update_group.html", base_template="base/profile.html", ): """ This view creates and updates permissions for views and projects. Parameters: object_type: valid values are 'projects' or 'views' object_id: Integer -- primary key to a Project or View object embed: Whether or not it's an iframe: In addition, this view also processes a UserAuthorityObject formset, which applies user-level permissions to a particular project. This form uses the contenttypes framework (so object-user permissions can be arbitrarily assigned to more than one object). Helpful links here: * http://hdknr.github.com/docs/django/modules/django/contrib/contenttypes/generic.html * http://weispeaks.wordpress.com/2009/11/04/overcoming-limitations-in-django-using-generic-foreign-keys/ """ from django.forms import models, formsets from django.contrib.contenttypes import generic from localground.apps.site.models import Base, UserAuthorityObject, UserAuthority from localground.apps.site.forms import UserAuthorityObjectForm from django.http import HttpResponseRedirect r = request.POST or request.GET ModelClass = Base.get_model(model_name_plural=object_type_plural) GroupForm = ModelClass.get_form() if action == "share": GroupForm = ModelClass.sharing_form() if embed: base_template = "base/iframe.html" prefix = "groupuser" source_object = None no_shared_users = True extra = 0 # query for model object to update (if object_id is specified): try: if object_id is not None: source_object = ModelClass.objects.get(id=object_id) no_shared_users = len(source_object.users.all()) == 0 except ModelClass.DoesNotExist: pass if no_shared_users: extra = 1 UserAuthorityObjectFormset = generic.generic_inlineformset_factory( UserAuthorityObject, form=UserAuthorityObjectForm, formset=generic.BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", extra=extra, can_delete=True, ) extras = {} if request.method == "POST": form = GroupForm(request.POST, instance=source_object) formset = UserAuthorityObjectFormset(request.POST, instance=source_object, prefix=prefix) if formset.is_valid() and form.is_valid(): from django.contrib.contenttypes.models import ContentType # ---------------------------- # PROJECT FORM POST-PROCESSING # ---------------------------- instance = form.instance instance.time_stamp = get_timestamp_no_milliseconds() # determine ContentType: app_label = instance._meta.app_label model_name = ModelClass.__name__.lower() content_type = ContentType.objects.get(app_label=app_label, model=model_name) if instance.access_authority.id != 2: instance.access_key = None if instance.pk is None: instance.owner = request.user is_new = True else: orig = ModelClass.objects.get(id=object_id) if orig.owner != instance.owner: # ensure there's a UserAuthorityObject entry for the old owner for # this object: is_object_user = ( len( UserAuthorityObject.objects.filter(user=orig.owner) .filter(content_type=content_type) .filter(object_id=object_id) ) == 1 ) if not is_object_user: previous_owner = UserAuthorityObject() previous_owner.user = orig.owner previous_owner.content_type = content_type previous_owner.object_id = orig.id previous_owner.authority = UserAuthority.objects.get(id=3) previous_owner.granted_by = request.user previous_owner.time_stamp = get_timestamp_no_milliseconds() previous_owner.save() instance.last_updated_by = request.user instance.save() source_object = instance # ----------------------------------- # PROJECTUSER FORM(S) POST-PROCESSING # ----------------------------------- marked_for_delete = formset.deleted_forms for form in formset.forms: if form.has_changed(): instance = form.instance if not instance in formset.deleted_forms: instance.granted_by = request.user instance.time_stamp = get_timestamp_no_milliseconds() instance.content_type = content_type instance.object_id = source_object.id instance.save() if len(marked_for_delete) > 0: formset.save() # If success, determine which URL to redirect to (either update project or # update permissions) so that form doesn't post twice: # url = '{0}{1}/?success=true'.format(request.path, source_object.id) # url = url.replace('create', 'update') #create URL should redirect # to update URL url = source_object.update_url() if action == "share": url = source_object.share_url() if embed: url += "embed/" url += "?success=true" return HttpResponseRedirect(url) else: extras.update( { "success": False, "error_message": "There were errors when updating the %s information. \ Please review message(s) below." % ModelClass.model_name, } ) else: form = GroupForm(instance=source_object) formset = UserAuthorityObjectFormset(instance=source_object, prefix=prefix) extras.update( { "form": form, "no_users": str(no_shared_users).lower(), "formset": formset, "prefix": prefix, "source_object": source_object, "object_name": ModelClass.model_name, "parent_id": object_id, "show_hidden_fields": True, "base_template": base_template, "embed": embed, } ) if source_object: extras.update({"owner": source_object.owner.username}) if r.get("success", "false") in ["1", "true", "True"]: extras.update( {"success": True, "message": "The %s information was successfully updated." % ModelClass.model_name} ) return render_to_response(template, extras, context_instance=RequestContext(request))