Example #1
0
def theme_save_as(request, theme):
    if request.method == 'POST':
        # Theme
        new_theme = Theme()
        new_theme['verbose_name'] = request.POST['name']
        new_name = slugify(new_theme['verbose_name'])
        counter = 0
        while Theme.query().filter(name=new_name).exclude(pk=theme['pk']).count():
            counter += 1
            new_name = '%s-%s'%(slugify(theme['verbose_name']), counter)
        new_theme['name'] = new_name
        new_theme.save()

        # Templates
        for tpl in theme['templates']:
            new_tpl, new = new_theme['templates'].get_or_create(name=tpl['name'])
            new_tpl['notes'] = tpl['notes']
            new_tpl['content'] = tpl['content']
            new_tpl['engine'] = tpl['engine']
            new_tpl.save()

        """
        # FIXME
        # Static files
        for sf in theme['static_files']:
            try:
                new_sf, new = new_theme['static_files'].get_or_create(name=sf['name'])
                new_sf.url = sf.url
                new_sf.mimetype = sf.mimetype
                new_sf.save()

                if sf.file:
                    # Finds a name for the new file
                    root = sf.file.path.replace(sf.file.name, '')
                    name, ext = os.path.splitext(sf.file.name)
                    while os.path.exists(root + name + ext):
                        name += '_'

                    # Reads the old file to make a ContentFile instance
                    fp = file(sf.file.path)
                    content = ContentFile(fp.read())
                    fp.close()
                    
                    # Saves the new file for the new static file object
                    new_sf.file.save(name+ext, content)
            except BaseException as e:
                print(sf, e.__class__, e)
                raise
        """
        ret = {'new_url': reverse('themes_theme', kwargs={'name': new_theme['name']})}
    else:
        ret = {'result': 'error'}
    
    return JsonResponse(ret)
Example #2
0
    def clean(self):
        cleaned_data = super(PageForm, self).clean()
        cleaned_data['slug'] = cleaned_data['slug'] or slugify(cleaned_data['name'])
        
        all_pages = cleaned_data['site']['pages']
        pages = all_pages.filter(slug=cleaned_data['slug'])

        # Validation excludes current page
        if self.instance['pk']:
            pages = pages.exclude(pk=self.instance['pk'])

        # Validating duplicated slug
        if pages.count() > 0:
            raise forms.ValidationError('Another page with slug "%s" already exists for this site.' % cleaned_data['slug'],
                    field_name='slug')

        if 'is_home' in cleaned_data and cleaned_data['is_home']:
            try:
                home = all_pages.home('name')
                home = (home, cleaned_data['name'])[home is None]
            except:
                home = None
            if cleaned_data['name'] != home:
                raise forms.ValidationError('Page "%s" is already marked as home.' % cleaned_data['name'],
                        field_name='is_home')

        signals.page_form_clean.send(sender=self, cleaned_data=cleaned_data)
        return cleaned_data
Example #3
0
    def clean(self):
        cleaned_data = super(PageForm, self).clean()
        cleaned_data['slug'] = cleaned_data['slug'] or slugify(
            cleaned_data['name'])

        all_pages = cleaned_data['site']['pages']
        pages = all_pages.filter(slug=cleaned_data['slug'])

        # Validation excludes current page
        if self.instance['pk']:
            pages = pages.exclude(pk=self.instance['pk'])

        # Validating duplicated slug
        if pages.count() > 0:
            raise forms.ValidationError(
                'Another page with slug "%s" already exists for this site.' %
                cleaned_data['slug'],
                field_name='slug')

        if 'is_home' in cleaned_data and cleaned_data['is_home']:
            try:
                home = all_pages.home('name')
                home = (home, cleaned_data['name'])[home is None]
            except:
                home = None
            if cleaned_data['name'] != home:
                raise forms.ValidationError(
                    'Page "%s" is already marked as home.' %
                    cleaned_data['name'],
                    field_name='is_home')

        signals.page_form_clean.send(sender=self, cleaned_data=cleaned_data)
        return cleaned_data
Example #4
0
 def serialize_view(self, request, **kwargs):
     """FIXME: This function must be moved from here to the application "serialization" as part of a signal to customize admin
     without to make coupling (which is doing by this old way)."""
     objects = self.get_queryset(request)
     data = serialize(objects)
     serializer = get_serializer()
     file_name = '%s.%s'%(slugify(self.get_title()), serializer.extension)
     return HttpResponse(data, mime_type='application/octet-stream',
             headers={'Content-Disposition':'attachment; '+file_name})
Example #5
0
def theme_rename(request, theme):
    if request.method == 'POST':
        # Sets a new verbose name and its slugified name
        theme['verbose_name'] = request.POST['name']
        new_name = slugify(theme['verbose_name'])
        counter = 0
        while Theme.query().filter(name=new_name).exclude(pk=theme['pk']).count():
            counter += 1
            new_name = '%s-%s'%(slugify(theme['verbose_name']), counter)
        theme['name'] = new_name
        theme.save()

        ret = {'new_url': reverse('themes_theme', kwargs={'name': theme['name']})}
    else:
        ret = {'result': 'error'}
    
    # Returns a JSON with new URL to redirect it
    return JsonResponse(ret)
Example #6
0
def home(request):
    themes = Theme.query().order_by('verbose_name')
    previewing = request.COOKIES.get(app_settings.CURRENT_THEME_COOKIE, None)

    if request.POST.get('name', None):
        verbose_name = request.POST['name']
        name = slugify(request.POST['name'])
        counter = 0
        while Theme.query().filter(name=name).count():
            counter += 1
            name = '%s-%s'%(slugify(request.POST['name']), counter)
        theme = Theme.query().create(name=name, verbose_name=verbose_name)

        request.warning(_('New theme "%s" created.'))
        return HttpResponseRedirect(reverse('themes_theme', kwargs={'name': theme['name']}))
    return render_to_response(request,
            'themes/home.html',
            {'themes':themes, 'previewing':previewing},
            )
Example #7
0
    def save(self, **kwargs):
        # TODO: slug field should be unique with site/articles
        if not self.get('slug', False):
            self['slug'] = slugify(self['name'])

        source = self.get('source', None)
        source = image_compiler.render(source) or source
        if source is not None:
            self['text'] = markdown2.markdown(source)
        self['date'] = datetime.now()

        return super(Post, self).save(**kwargs)
Example #8
0
    def save(self, **kwargs):
        # TODO: slug field should be unique with site/articles
        if not self.get("slug", False):
            self["slug"] = slugify(self["name"])

        source = self.get("source", None)
        source = image_compiler.render(source) or source
        if source is not None:
            self["text"] = markdown2.markdown(source)
        self["date"] = datetime.now()

        return super(Post, self).save(**kwargs)
Example #9
0
    def register_module(self, module_class):
        # Gets the name or the module name
        if not module_class.name:
            module_class.name = module_class.model.__name__.lower()
        name = module_class.name

        # Validates modules already registered
        if self.modules.get(name, module_class) != module_class:
            raise ApplicationAlreadyRegistered('There is already another module registered with the name '+name)
        elif slugify(name) != name:
            raise InvalidApplicationName('The name "%s" should be "%s" to be valid'%(name, slugify(name)))

        self.modules[name] = module_class
Example #10
0
    def register_application(self, app_class):
        # Gets the name or the module name
        if app_class.name:
            name = app_class.name
        else:
            name = app_class.__module__.split('.')[-2]
            app_class.name = name

        # Validates application already registered
        if self.applications.get(name, app_class) != app_class:
            raise ApplicationAlreadyRegistered('There is already another application registered with the name '+name)
        elif slugify(name) != name:
            raise InvalidApplicationName('The name "%s" should be "%s" to be valid'%(name, slugify(name)))

        self.applications[name] = app_class
Example #11
0
from london.utils.safestring import mark_safe
from london.urls import reverse
from london.apps.collections.models import Collection

from datetime import datetime

try:
    from images.render import ImagesRender
    image_compiler = ImagesRender()
except:
    image_compiler = None

import markdown2

try:
    SITES = [(slugify(site['name']), site['name']) for site in Site.query()]
except:
    SITES = []


class Category(models.Model):
    class Meta:
        ordering = ('name', )

    name = models.CharField(max_length=50)


class PostQuerySet(models.QuerySet):
    def published(self):
        return self.filter(is_draft=False)
    def execute(self, *args, **kwargs):
        load_apps()

        from london.apps.auth.models import User

        if kwargs.get('username', None):
            if User.query().filter(username=kwargs['username']).count():
                sys.exit('User "%s" already exists.'%kwargs['username'])
        elif kwargs.get('email', None):
            if User.query().filter(email=kwargs['email']).count():
                sys.exit('User with e-mail "%s" already exists.'%kwargs['email'])
            kwargs['username'] = slugify(kwargs['email'])

        fields = {}

        # Username
        if kwargs.get('username', None):
            fields['username'] = kwargs['username']
        else:
            fields['username'] = raw_input('Username: '******'username'].strip():
                print('Invalid username.')
                sys.exit(1)

        # Password
        if kwargs.get('password', None):
            fields['password'] = kwargs['password']
        else:
            fields['password'] = raw_input('Password (empty for random generation): ')
            if not fields['password']:
                fields['password'] = get_random_string()
                print('The password "%s" was generated.'%fields['password'])
            elif fields['password'] != raw_input('... again, for confirmation: '):
                print('Password not apropriately confirmed.')
                sys.exit(1)

        # E-mail address
        if kwargs.get('email', None):
            fields['email'] = kwargs['email']
        else:
            fields['email'] = raw_input('E-mail address: ')
            if not fields['email'].strip():
                print('Invalid e-mail address.')
                sys.exit(1)

        # Is staff?
        if kwargs['is_staff']:
            fields['is_staff'] = kwargs['is_staff']
        else:
            fields['is_staff'] = raw_input('Can access admin (staff)?: ').lower() == 'yes'

        # Is superuser?
        if kwargs['is_superuser']:
            fields['is_superuser'] = kwargs['is_superuser']
        else:
            fields['is_superuser'] = raw_input('Superuser?: ').lower() == 'yes'

        # Checks if a user with that username already exists.
        if User.query().filter(username=fields['username']).count():
            print('Another user exists with the username "%s".'%fields['username'])
            sys.exit(1)
        
        user = User.query().create(**fields)
        print('The user "%s" was created with password "%s"'%(fields['username'], fields['password']))
def product_pre_save(instance, **kwargs):
    instance['slug'] = instance['slug'] or slugify(instance['name'])
def style_pre_save(instance, **kwargs):
    instance['slug'] = instance['slug'] or slugify(instance['name'])
def category_pre_save(instance, **kwargs):
    instance['slug'] = instance['slug'] or slugify(instance['name'])
Example #16
0
 def clean_value(self, inst, value):
     return slugify(value) if value else value
Example #17
0
from london.urls import reverse
from london.apps.collections.models import Collection

from datetime import datetime

try:
    from images.render import ImagesRender

    image_compiler = ImagesRender()
except:
    image_compiler = None

import markdown2

try:
    SITES = [(slugify(site["name"]), site["name"]) for site in Site.query()]
except:
    SITES = []


class Category(models.Model):
    class Meta:
        ordering = ("name",)

    name = models.CharField(max_length=50)


class PostQuerySet(models.QuerySet):
    def published(self):
        return self.filter(is_draft=False)