Пример #1
0
    def save(self, *args, **kwargs):
        data = self.cleaned_data
        counter = 0

        files = data.get('files')
        tags = data.get('tags')
        group = data.get('group')
        file_cat = data.get('file_cat', None)
        file_sub_cat = data.get('file_sub_cat', None)
        is_public = data.get('allow_anonymous_view', False)

        for new_file in files:
            file = File(
                file=new_file,
                tags=tags,
                group=group,
                allow_anonymous_view=is_public,
                file_cat=file_cat,
                file_sub_cat=file_sub_cat)

            file.save()

            # update all permissions and save the model
            file = update_perms_and_save(self.request, self, file)

            #setup categories
            category = Category.objects.get_for_object(file, 'category')
            sub_category = Category.objects.get_for_object(file, 'sub_category')

            ## update the category of the file
            category_removed = False
            category = file.file_cat.name if file.file_cat else u''

            if category:
                Category.objects.update(file, category, 'category')
            else:  # remove
                category_removed = True
                Category.objects.remove(file, 'category')
                Category.objects.remove(file, 'sub_category')

            if not category_removed:
                # update the sub category of the file
                sub_category = file.file_sub_cat.name if file.file_sub_cat else u''
                if sub_category:
                    Category.objects.update(file, sub_category, 'sub_category')
                else:  # remove
                    Category.objects.remove(file, 'sub_category')

            #Save relationships
            file.save()
            counter += 1

        return counter
Пример #2
0
def save_settings_form(self):
    """
        Save the updated settings in the database
        Setting's save will trigger a cache update.
        If the field type is 'file' a file entry will be created.
    """
    for setting in self.settings:
        old_value = setting.get_value()
        try:
            field_value = self.cleaned_data[setting.name]
            if setting.input_type == "file":
                if field_value:
                    # save a file object and set the value at that file object's id.
                    from tendenci.apps.files.models import File as TendenciFile
                    uploaded_file = TendenciFile()
                    uploaded_file.owner = self.user
                    uploaded_file.owner_username = self.user.username
                    uploaded_file.creator = self.user
                    uploaded_file.creator_username = self.user.username
                    uploaded_file.content_type = ContentType.objects.get(
                        app_label="site_settings", model="setting")
                    uploaded_file.file.save(field_value.name,
                                            File(field_value))
                    uploaded_file.save()
                    field_value = uploaded_file.pk
                else:
                    #retain the old file if no file is set
                    field_value = setting.get_value()

            # update value if changed and save
            if old_value != field_value:
                setting.set_value(field_value)
                setting.save()  # save updates the cash automatically

            # update the django site value in the contrib backend
            if setting.name == "siteurl" and setting.scope == "site":
                if field_value:
                    django_site = Site.objects.get(pk=1)
                    if urlparse(field_value).scheme == "":
                        # prefix http:// if no scheme
                        field_value = 'http://%s' % field_value
                    netloc = urlparse(field_value).netloc
                    django_site.domain = netloc
                    django_site.name = netloc
                    django_site.save()

            # update checklist for theme logo
            if setting.name == 'logo' and setting.scope_category == 'theme':
                checklist_update('upload-logo')

            # update checklist for contact form
            if setting.name == 'contact_form' and setting.scope == "site":
                checklist_update('update-contact')

        except KeyError:
            pass
Пример #3
0
    def save(self, *args, **kwargs):
        photo_upload = kwargs.pop('photo', None)

        super(Chapter, self).save(*args, **kwargs)
        if photo_upload and self.pk:
            image = File(content_type=ContentType.objects.get_for_model(self.__class__),
                         object_id=self.pk,
                         creator=self.creator,
                         creator_username=self.creator_username,
                         owner=self.owner,
                         owner_username=self.owner_username)
            photo_upload.file.seek(0)
            image.file.save(photo_upload.name, photo_upload)
            image.save()

            self.featured_image = image
            self.save()
Пример #4
0
def save_settings_form(self):
    """
        Save the updated settings in the database
        Setting's save will trigger a cache update.
        If the field type is 'file' a file entry will be created.
    """
    for setting in self.settings:
        old_value = setting.get_value()
        try:
            field_value = self.cleaned_data[setting.name]
            if setting.input_type == "file":
                if field_value:
                    # save a file object and set the value at that file object's id.
                    from tendenci.apps.files.models import File as TendenciFile
                    uploaded_file = TendenciFile()
                    uploaded_file.owner = self.user
                    uploaded_file.owner_username = self.user.username
                    uploaded_file.creator = self.user
                    uploaded_file.creator_username = self.user.username
                    uploaded_file.content_type = ContentType.objects.get(app_label="site_settings", model="setting")
                    uploaded_file.file.save(field_value.name, File(field_value))
                    uploaded_file.save()
                    field_value = uploaded_file.pk
                else:
                    #retain the old file if no file is set
                    field_value = setting.get_value()

            # update value if changed and save
            if old_value != field_value:
                setting.set_value(field_value)
                setting.save()  # save updates the cash automatically

            # update the django site value in the contrib backend
            if setting.name == "siteurl" and setting.scope == "site":
                if field_value:
                    django_site = Site.objects.get(pk=1)
                    if urlparse(field_value).scheme == "":
                        # prefix http:// if no scheme
                        field_value = 'http://%s' % field_value
                    netloc = urlparse(field_value).netloc
                    django_site.domain = netloc
                    django_site.name = netloc
                    django_site.save()

            # update checklist for theme logo
            if setting.name == 'logo' and setting.scope_category == 'theme':
                checklist_update('upload-logo')

            # update checklist for contact form
            if setting.name == 'contact_form' and setting.scope == "site":
                checklist_update('update-contact')

        except KeyError:
            pass
Пример #5
0
    def save_file_from_url(self, url, instance):
        file_name = os.path.basename(urllib.unquote(url).replace(' ', '_'))
        tfile = TFile()
        tfile.name = file_name
        tfile.content_type = ContentType.objects.get_for_model(instance)
        tfile.object_id = instance.id
        if hasattr(instance, 'creator'):
            tfile.creator = instance.creator
        if hasattr(instance, 'creator_username'):
            tfile.creator_username = instance.creator_username
        if hasattr(instance, 'owner'):
            tfile.owner = instance.owner
        if hasattr(instance, 'owner_username'):
            tfile.owner_username = instance.owner_username

        #file_path = file_directory(tfile, tfile.name)
        tfile.file.save(file_name, ContentFile(urllib2.urlopen(url).read()))
        tfile.save()
        return tfile
Пример #6
0
    def save_file_from_url(self, url, instance):
        file_name = os.path.basename(urllib.unquote(url).replace(' ', '_'))
        tfile = TFile()
        tfile.name = file_name
        tfile.content_type = ContentType.objects.get_for_model(instance)
        tfile.object_id = instance.id
        if hasattr(instance, 'creator'):
            tfile.creator = instance.creator
        if hasattr(instance, 'creator_username'):
            tfile.creator_username = instance.creator_username
        if hasattr(instance, 'owner'):
            tfile.owner = instance.owner
        if hasattr(instance, 'owner_username'):
            tfile.owner_username = instance.owner_username

        #file_path = file_directory(tfile, tfile.name)
        tfile.file.save(file_name, ContentFile(urllib2.urlopen(url).read()))
        tfile.save()
        return tfile
Пример #7
0
def get_media(item, user):
    """
    Find any URL contained in an "attachment."
    If that File has already been created, skip it.
    If not, go to the URL, and save the media there as a File.
    Loop through Articles and Pages and replace links.
    """
    media_url_in_attachment = item.find('wp:attachment_url').string
    media_url = urlparse(media_url_in_attachment).file
    media_url = os.path.join(settings.MEDIA_ROOT, media_url)

    post_id = item.find('wp:post_parent').string
    post_id = int(post_id)

    alreadyThere = False

    for url in File.objects.all():
        if media_url == url.file:
            alreadyThere = True
            # This assignment will make sure the file gets replaced in the HTML even if
            # it's an old file that already exists in the database.
            new_media = url
            break

    if not alreadyThere:
        source = urllib2.urlopen(media_url_in_attachment).read()

        with open(media_url, 'wb') as f:
            f.write(source)
            file_path = f.name

        new_media = File(guid=unicode(uuid.uuid1()),
                         file=file_path,
                         creator=user,
                         owner=user)
        new_media.save()

    temporary = AssociatedFile(post_id=post_id, file=new_media)
    temporary.save()
Пример #8
0
    def save(self, *args, **kwargs):
        self.guid = self.guid or unicode(uuid.uuid1())

        # update latitude and longitude
        if not all((self.latitude, self.longitude)):
            self.latitude, self.longitude = get_coordinates(self.get_address())

        photo_upload = kwargs.pop('photo', None)
        super(Location, self).save(*args, **kwargs)

        if photo_upload and self.pk:
            image = File(content_type=ContentType.objects.get_for_model(self.__class__),
                         object_id=self.pk,
                         creator=self.creator,
                         creator_username=self.creator_username,
                         owner=self.owner,
                         owner_username=self.owner_username)
            photo_upload.file.seek(0)
            image.file.save(photo_upload.name, photo_upload)
            image.save()

            self.logo = image
            self.save()
Пример #9
0
    def save(self, *args, **kwargs):
        self.guid = self.guid or unicode(uuid.uuid1())

        # update latitude and longitude
        if not all((self.latitude, self.longitude)):
            self.latitude, self.longitude = get_coordinates(self.get_address())

        photo_upload = kwargs.pop('photo', None)
        super(Location, self).save(*args, **kwargs)

        if photo_upload and self.pk:
            image = File(content_type=ContentType.objects.get_for_model(self.__class__),
                         object_id=self.pk,
                         creator=self.creator,
                         creator_username=self.creator_username,
                         owner=self.owner,
                         owner_username=self.owner_username)
            photo_upload.file.seek(0)
            image.file.save(photo_upload.name, photo_upload)
            image.save()

            self.logo = image
            self.save()
Пример #10
0
def get_media(item, user):
    """
    Find any URL contained in an "attachment."
    If that File has already been created, skip it.
    If not, go to the URL, and save the media there as a File.
    Loop through Articles and Pages and replace links.
    """
    media_url_in_attachment = item.find('wp:attachment_url').string
    media_url = urlparse(media_url_in_attachment).file
    media_url = os.path.join(settings.MEDIA_ROOT, media_url)

    post_id = item.find('wp:post_parent').string
    post_id = int(post_id)

    alreadyThere = False

    for url in File.objects.all():
        if media_url == url.file:
            alreadyThere = True
            # This assignment will make sure the file gets replaced in the HTML even if
            # it's an old file that already exists in the database.
            new_media = url
            break

    if not alreadyThere:
        source = urllib2.urlopen(media_url_in_attachment).read()

        with open(media_url, 'wb') as f:
            f.write(source)
            file_path = f.name

        new_media = File(guid=unicode(uuid.uuid1()), file=file_path, creator=user, owner=user)
        new_media.save()

    temporary = AssociatedFile(post_id=post_id, file=new_media)
    temporary.save()
Пример #11
0
 def save_header_image(self, request, job):
     if self.is_valid():
         f = self.cleaned_data['header_image']
         if f:
             header_image = File()
             header_image.content_type = ContentType.objects.get_for_model(Job)
             header_image.object_id = job.id
             header_image.creator = request.user
             header_image.creator_username = request.user.username
             header_image.owner = request.user
             header_image.owner_username = request.user.username
             filename = "%s-%s" % (job.slug, f.name)
             f.file.seek(0)
             header_image.file.save(filename, f)
             job.header_image = header_image
             job.save()
             assign_files_perms(job, files=[job.header_image])
Пример #12
0
    def save(self, *args, **kwargs):
        data = self.cleaned_data
        counter = 0

        files = data.get('files')
        tags = data.get('tags')
        group = data.get('group')
        file_cat = data.get('file_cat', None)
        file_sub_cat = data.get('file_sub_cat', None)
        is_public = data.get('allow_anonymous_view', False)

        for new_file in files:
            file = File(file=new_file,
                        tags=tags,
                        group=group,
                        allow_anonymous_view=is_public,
                        file_cat=file_cat,
                        file_sub_cat=file_sub_cat)

            file.save()

            # update all permissions and save the model
            file = update_perms_and_save(self.request, self, file)

            #setup categories
            category = Category.objects.get_for_object(file, 'category')
            sub_category = Category.objects.get_for_object(
                file, 'sub_category')

            ## update the category of the file
            category_removed = False
            category = file.file_cat.name if file.file_cat else u''

            if category:
                Category.objects.update(file, category, 'category')
            else:  # remove
                category_removed = True
                Category.objects.remove(file, 'category')
                Category.objects.remove(file, 'sub_category')

            if not category_removed:
                # update the sub category of the file
                sub_category = file.file_sub_cat.name if file.file_sub_cat else u''
                if sub_category:
                    Category.objects.update(file, sub_category, 'sub_category')
                else:  # remove
                    Category.objects.remove(file, 'sub_category')

            #Save relationships
            file.save()
            counter += 1

        return counter
Пример #13
0
def bulk_add(request, template_name="files/bulk-add.html"):
    if not has_perm(request.user, 'files.add_file'):
        raise Http403

    FileFormSet = modelformset_factory(
        File,
        form=FileForm,
        can_delete=True,
        fields=(
            'name',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status',
        ),
        extra=0
    )
    if request.method == "POST":
        # Setup formset html for json response
        file_list = []
        file_formset = FileFormSet(request.POST)
        if file_formset.is_valid():
            file_formset.save()
        else:
            # Handle formset errors
            return render_to_response(template_name, {
                'file_formset': file_formset,
            }, context_instance=RequestContext(request))

        formset_edit = True

        # Handle existing files.  Instance returned by file_formset.save() is not enough
        for num in xrange(file_formset.total_form_count()):
            key = 'form-' + str(num) + '-id'
            if request.POST.get(key):
                file_list.append(request.POST.get(key))
        # Handle new file uploads
        for file in request.FILES.getlist('files'):
            newFile = File(file=file)
            # set up the user information
            newFile.creator = request.user
            newFile.creator_username = request.user.username
            newFile.owner = request.user
            newFile.owner_username = request.user.username
            newFile.save()
            file_list.append(newFile.id)
            formset_edit = False
        # Redirect if form_set is edited i.e. not a file select or drag event
        if formset_edit:
            return HttpResponseRedirect(reverse('file.search'))

        # Handle json response
        file_qs = File.objects.filter(id__in=file_list)
        file_formset = FileFormSet(queryset=file_qs)
        html = render_to_response(
            'files/file-formset.html', {
                'file_formset': file_formset,
            }, context_instance=RequestContext(request)).content

        data = {'form_set': html}
        response = JSONResponse(data, {}, "application/json")
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response
    else:
        file_formset = FileFormSet({
            'form-TOTAL_FORMS': u'0',
            'form-INITIAL_FORMS': u'0',
            'form-MAX_NUM_FORMS': u'',
        })

    return render_to_response(
        template_name, {
            'file_formset': file_formset,
        }, context_instance=RequestContext(request))
Пример #14
0
def bulk_add(request, template_name="files/bulk-add.html"):
    if not has_perm(request.user, 'files.add_file'):
        raise Http403

    FileFormSet = modelformset_factory(File,
                                       form=FileForm,
                                       can_delete=True,
                                       fields=(
                                           'name',
                                           'allow_anonymous_view',
                                           'user_perms',
                                           'member_perms',
                                           'group_perms',
                                           'status',
                                       ),
                                       extra=0)
    if request.method == "POST":
        # Setup formset html for json response
        file_list = []
        file_formset = FileFormSet(request.POST)
        if file_formset.is_valid():
            file_formset.save()
        else:
            # Handle formset errors
            return render_to_response(template_name, {
                'file_formset': file_formset,
            },
                                      context_instance=RequestContext(request))

        formset_edit = True

        # Handle existing files.  Instance returned by file_formset.save() is not enough
        for num in xrange(file_formset.total_form_count()):
            key = 'form-' + str(num) + '-id'
            if request.POST.get(key):
                file_list.append(request.POST.get(key))
        # Handle new file uploads
        for file in request.FILES.getlist('files'):
            newFile = File(file=file)
            # set up the user information
            newFile.creator = request.user
            newFile.creator_username = request.user.username
            newFile.owner = request.user
            newFile.owner_username = request.user.username
            newFile.save()
            file_list.append(newFile.id)
            formset_edit = False
        # Redirect if form_set is edited i.e. not a file select or drag event
        if formset_edit:
            return HttpResponseRedirect(reverse('file.search'))

        # Handle json response
        file_qs = File.objects.filter(id__in=file_list)
        file_formset = FileFormSet(queryset=file_qs)
        html = render_to_response(
            'files/file-formset.html', {
                'file_formset': file_formset,
            },
            context_instance=RequestContext(request)).content

        data = {'form_set': html}
        response = JSONResponse(data, {}, "application/json")
        response['Content-Disposition'] = 'inline; filename="files.json"'
        return response
    else:
        file_formset = FileFormSet({
            'form-TOTAL_FORMS': u'0',
            'form-INITIAL_FORMS': u'0',
            'form-MAX_NUM_FORMS': u'',
        })

    return render_to_response(template_name, {
        'file_formset': file_formset,
    },
                              context_instance=RequestContext(request))