Exemplo n.º 1
0
def view_chapter(request, tutorial_pk, tutorial_slug, part_slug,
                 chapter_slug):
    """Display a chapter.

    Returns:
        HttpResponse

    """

    chapter = get_object_or_404(Chapter,
                                slug=chapter_slug,
                                part__slug=part_slug,
                                part__tutorial__pk=tutorial_pk)

    tutorial = chapter.get_tutorial()
    if not tutorial.is_visible \
       and not request.user.has_perm('tutorial.modify_chapter') \
       and request.user not in tutorial.authors.all():
        if not (tutorial.is_beta and request.user.is_authenticated()):
            raise PermissionDenied

    if not tutorial_slug == slugify(tutorial.title)\
        or not part_slug == slugify(chapter.part.title)\
            or not chapter_slug == slugify(chapter.title):
        return redirect(chapter.get_absolute_url())

    return render_template('tutorial/view_chapter.html', {
        'chapter': chapter
    })
Exemplo n.º 2
0
def new_image(request, gal_pk):
    """Add a new image to a gallery.

    Returns:
        HttpResponse

    """
    gal = get_object_or_404(Gallery, pk=gal_pk)

    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid() \
           and request.FILES['physical'].size < settings.IMAGE_MAX_SIZE:
            img = Image()
            img.physical = request.FILES['physical']
            img.gallery = gal
            img.title = request.POST['title']
            img.slug = slugify(request.FILES['physical'])
            img.legend = request.POST['legend']
            img.pubdate = datetime.now()

            img.save()

            # Redirect to the document list after POST
            return redirect(gal.get_absolute_url())
    else:
        form = ImageForm()  # A empty, unbound form

    return render_template('gallery/new_image.html', {
        'form': form,
        'gallery': gal
    })
Exemplo n.º 3
0
def new_gallery(request):
    """Create a new gallery.

    Returns:
        HttpResponse

    """
    if request.method == 'POST':
        form = GalleryForm(request.POST)
        if form.is_valid():
            data = form.data
            # Creating the gallery
            gal = Gallery()
            gal.title = data['title']
            gal.subtitle = data['subtitle']
            gal.slug = slugify(data['title'])
            gal.pubdate = datetime.now()
            gal.save()

            # Attach user
            userg = UserGallery()
            userg.gallery = gal
            userg.mode = 'W'
            userg.user = request.user
            userg.save()

            return redirect(gal.get_absolute_url())
    else:
        form = GalleryForm()

    return render_template('gallery/new_gallery.html', {'form': form})
Exemplo n.º 4
0
    def save(self, force_update=False, force_insert=False,
             thumb_size=(IMAGE_MAX_HEIGHT, IMAGE_MAX_WIDTH)):
        """Save the article.

        This will save thumbnail on disk and then save the model in database.

        """
        self.slug = slugify(self.title)

        if has_changed(self, 'image') and self.image:
            # TODO : delete old image

            image = Image.open(self.image)

            if image.mode not in ('L', 'RGB'):
                image = image.convert('RGB')

            image.thumbnail(thumb_size, Image.ANTIALIAS)

            # save the thumbnail to memory
            temp_handle = StringIO()
            image.save(temp_handle, 'png')
            temp_handle.seek(0)  # rewind the file

            # save to the thumbnail field
            suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
                                     temp_handle.read(),
                                     content_type='image/png')
            self.thumbnail.save('{}.png'.format(suf.name), suf, save=False)

            # save the image object
            super().save(force_update, force_insert)
        else:
            super().save()
Exemplo n.º 5
0
    def save(self, *args, **kwargs):
        """Save a part.

        This will compute the slug field from title field and then save the
        model.

        """
        self.slug = slugify(self.title)
        super().save(*args, **kwargs)
Exemplo n.º 6
0
    def get_absolute_url(self):
        """Get URL to view this tutorial.

        Returns:
            string

        """
        return reverse('pdp.tutorial.views.view_tutorial',
                       args=[self.pk, slugify(self.title)])
Exemplo n.º 7
0
    def save(self, *args, **kwargs):
        """Save a part.

        This will compute the slug field from title field and then save the
        model.

        """
        self.slug = slugify(self.title)
        super().save(*args, **kwargs)
Exemplo n.º 8
0
    def clean_title(self):
        data = self.cleaned_data['title']

        if slugify(data) == u'':
            raise forms.ValidationError(
                u'Votre titre doit au moins contenir une lettre de l’alphabet.'
            )

        return data
Exemplo n.º 9
0
    def get_absolute_url(self):
        """Get URL to view this tutorial.

        Returns:
            string

        """
        return reverse('pdp.tutorial.views.view_tutorial', args=[
            self.pk, slugify(self.title)
        ])
Exemplo n.º 10
0
    def get_absolute_url(self):
        """Get the URL to view this extract.

        Returns:
            string

        """
        return u'{0}#{1}-{2}'.format(self.chapter.get_absolute_url(),
                                     self.position_in_chapter,
                                     slugify(self.title))
Exemplo n.º 11
0
    def get_absolute_url(self):
        """Get the URL to view this extract.

        Returns:
            string

        """
        return u'{0}#{1}-{2}'.format(
            self.chapter.get_absolute_url(),
            self.position_in_chapter,
            slugify(self.title)
        )
Exemplo n.º 12
0
    def clean(self):
        cleaned_data = super().clean()

        title = slugify(cleaned_data.get('title'))

        existing = [x.slug for x in Part.objects.all().filter(
            tutorial=Tutorial.objects.get(pk=cleaned_data.get('tutorial')))]

        if title in existing:
            msg = u'Une partie portant ce nom existe déjà dans ce tutoriel.'
            self.add_error('title', msg)

        return cleaned_data
Exemplo n.º 13
0
    def clean(self):
        cleaned_data = super().clean()

        title = slugify(cleaned_data.get('title'))

        existing = [x.slug for x in Part.objects.all().filter(
            tutorial=Tutorial.objects.get(pk=cleaned_data.get('tutorial')))]

        if title in existing:
            msg = u'Une partie portant ce nom existe déjà dans ce tutoriel.'
            self._errors['title'] = self.error_class([msg])

        return cleaned_data
Exemplo n.º 14
0
    def clean(self):
        cleaned_data = super().clean()

        title = slugify(cleaned_data.get('title'))

        existing_chapters_titles = [x.slug for x in Chapter.objects.all()
                                    .filter(part=Part.objects.get(
                                        pk=cleaned_data.get('part')))]

        if title in existing_chapters_titles:
            msg = u'Un chapitre portant ce nom existe déjà dans cette partie.'
            self.add_error('title', msg)

        return cleaned_data
Exemplo n.º 15
0
    def clean(self):
        cleaned_data = super().clean()

        title = slugify(cleaned_data.get('title'))

        existing_chapters_titles = [x.slug for x in Chapter.objects.all()
                                    .filter(part=Part.objects.get(
                                        pk=cleaned_data.get('part')))]

        if title in existing_chapters_titles:
            msg = u'Un chapitre portant ce nom existe déjà dans cette partie.'
            self._errors['title'] = self.error_class([msg])

        return cleaned_data
Exemplo n.º 16
0
    def clean(self):
        cleaned_data = super().clean()

        title = slugify(cleaned_data.get('title'))
        chapter = cleaned_data.get('chapter')

        existing = [x.slug for x in Chapter.objects.all()
                    .filter(part=Part.objects.get(pk=cleaned_data.get('part')))
                    .exclude(pk=chapter)]

        if title in existing:
            msg = u'Un chapitre portant ce nom existe déjà dans cette partie.'
            self.add_error('title', msg)

        return cleaned_data
Exemplo n.º 17
0
    def clean(self):
        cleaned_data = super().clean()

        title = slugify(cleaned_data.get('title'))
        part = cleaned_data.get('part')

        existing = [x.slug for x in Part.objects.all()
                    .filter(tutorial=Tutorial.objects.get(
                        pk=cleaned_data.get('tutorial')))
                    .exclude(pk=part)]

        if title in existing:
            msg = u'Une partie portant ce nom existe déjà dans ce tutoriel.'
            self.add_error('title', msg)

        return cleaned_data
Exemplo n.º 18
0
    def save(self, *args, **kwargs):
        """Save tutorial instance.

        If tutorial's image was changed, it will update its thumbnail field
        resizing it. Then it will call normal saving of the model.

        """

        is_new = self.pk is None
        thumb_size = (IMAGE_MAX_HEIGHT, IMAGE_MAX_WIDTH)

        # Save the tutorial first if it was created in order to have a pk from
        # the database.
        if is_new:
            super().save(*args, **kwargs)

        # Compute tutorial's slug from its title
        self.slug = slugify(self.title)

        # Update the thumbnail if necessary
        if self.image and (is_new or has_changed(self, 'image')):
            # TODO : delete old image

            image = Image.open(self.image)

            if image.mode not in ('L', 'RGB'):
                image = image.convert('RGB')

            image.thumbnail(thumb_size, Image.ANTIALIAS)

            # Save the thumbnail to memory
            temp_handle = io.BytesIO()
            image.save(temp_handle, 'png')
            temp_handle.seek(0)  # rewind the file

            # Save to the thumbnail field
            suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
                                     temp_handle.read(),
                                     content_type='image/png')
            self.thumbnail.save(u'{}.png'.format(suf.name), suf, save=False)

        # Save the tutorial
        super().save(*args, **kwargs)
Exemplo n.º 19
0
    def save(self, *args, **kwargs):
        """Save tutorial instance.

        If tutorial's image was changed, it will update its thumbnail field
        resizing it. Then it will call normal saving of the model.

        """

        is_new = self.pk is None
        thumb_size = (IMAGE_MAX_HEIGHT, IMAGE_MAX_WIDTH)

        # Save the tutorial first if it was created in order to have a pk from
        # the database.
        if is_new:
            super().save(*args, **kwargs)

        # Compute tutorial's slug from its title
        self.slug = slugify(self.title)

        # Update the thumbnail if necessary
        if self.image and (is_new or has_changed(self, 'image')):
            # TODO : delete old image

            image = Image.open(self.image)

            if image.mode not in ('L', 'RGB'):
                image = image.convert('RGB')

            image.thumbnail(thumb_size, Image.ANTIALIAS)

            # Save the thumbnail to memory
            temp_handle = io.BytesIO()
            image.save(temp_handle, 'png')
            temp_handle.seek(0)  # rewind the file

            # Save to the thumbnail field
            suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
                                     temp_handle.read(),
                                     content_type='image/png')
            self.thumbnail.save(u'{}.png'.format(suf.name), suf, save=False)

        # Save the tutorial
        super().save(*args, **kwargs)
Exemplo n.º 20
0
def view_tutorial(request, tutorial_pk, tutorial_slug):
    """Display a tutorial.

    Returns:
        HttpResponse

    """
    tutorial = get_object_or_404(Tutorial, pk=tutorial_pk)

    if not tutorial.is_visible \
       and not request.user.has_perm('tutorial.change_tutorial') \
       and request.user not in tutorial.authors.all():
        if not (tutorial.is_beta and request.user.is_authenticated()):
            raise Http404

    # Make sure the URL is well-formed
    if not tutorial_slug == slugify(tutorial.title):
        return redirect(tutorial.get_absolute_url())

    # Two variables to handle two distinct cases (large/small tutorial)
    chapter = None
    parts = None
    part = None

    # If it's a small tutorial, fetch its chapter
    if tutorial.size == Tutorial.SMALL:
        chapter = Chapter.objects.get(tutorial=tutorial)
    elif tutorial.size == Tutorial.MEDIUM:
        part = Part.objects.get(tutorial=tutorial)
    else:
        parts = Part.objects.all(
        ).filter(tutorial=tutorial).order_by('position_in_tutorial')

    return render_template('tutorial/view_tutorial.html', {
        'tutorial': tutorial,
        'chapter': chapter,
        'part': part,
        'parts': parts,
    })
Exemplo n.º 21
0
    def save(self,
             force_update=False,
             force_insert=False,
             thumb_size=(IMAGE_MAX_HEIGHT, IMAGE_MAX_WIDTH)):
        """Save the chapter.

        This will update the chapter's thumbnail if its image was changed and
        then save the model.

        """
        self.slug = slugify(self.title)

        if has_changed(self, 'image') and self.image:
            # TODO : delete old image

            image = Image.open(self.image)

            if image.mode not in ('L', 'RGB'):
                image = image.convert('RGB')

            image.thumbnail(thumb_size, Image.ANTIALIAS)

            # save the thumbnail to memory
            temp_handle = io.StringIO()
            image.save(temp_handle, 'png')
            temp_handle.seek(0)  # rewind the file

            # save to the thumbnail field
            suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
                                     temp_handle.read(),
                                     content_type='image/png')
            self.thumbnail.save('{}.png'.format(suf.name), suf, save=False)

            # save the image object
            super().save(force_update, force_insert)
        else:
            super().save()
Exemplo n.º 22
0
def topic(request, topic_pk, topic_slug):
    """Display a thread and its posts using a pager.

    Returns:
        HttpResponse

    """

    # TODO: Clean that up
    g_topic = get_object_or_404(Topic, pk=topic_pk)

    # Check link
    if not topic_slug == slugify(g_topic.title):
        return redirect(g_topic.get_absolute_url())

    # We mark the topic as read
    if request.user.is_authenticated() and never_read(g_topic):
        mark_read(g_topic)

    posts = Post.objects.all() \
        .filter(topic__pk=g_topic.pk) \
        .order_by('position_in_topic')

    last_post_pk = g_topic.last_message.pk

    # Handle pagination
    paginator = Paginator(posts, settings.POSTS_PER_PAGE)

    # The category list is needed to move threads
    categories = Category.objects.all()

    # We try to get page number
    try:
        page_nbr = request.GET['page']
    except KeyError:
        page_nbr = 1

    # We try to page content
    try:
        posts = paginator.page(page_nbr)
        page_nbr = int(page_nbr)
    except PageNotAnInteger:
        posts = paginator.page(1)
        page_nbr = 1
    except EmptyPage:
        raise Http404

    res = []
    if page_nbr > 1:
        # Show the last post of the previous page
        last_page = paginator.page(page_nbr - 1).object_list
        last_post = (last_page)[len(last_page) - 1]
        res.append(last_post)

    for post in posts:
        res.append(post)

    return render_template('forum/topic.html', {
        'topic': g_topic,
        'posts': res,
        'categories': categories,
        'pages': paginator_range(page_nbr, paginator.num_pages),
        'nb': page_nbr,
        'last_post_pk': last_post_pk
    })
Exemplo n.º 23
0
def topic(request, topic_pk, topic_slug):
    """Display a topic and its posts using a pager.

    Returns:
        HttpResponse

    """
    # TODO: Clean that up
    g_topic = get_object_or_404(PrivateTopic, pk=topic_pk)

    # Check permissions
    if not is_participant(request.user, g_topic):
        raise PermissionDenied

    # Check link
    if not topic_slug == slugify(g_topic.title):
        return redirect(g_topic.get_absolute_url())

    # Mark the topic as read
    if request.user.is_authenticated():
        if never_privateread(g_topic):
            mark_read(g_topic)

    posts = PrivatePost.objects.all().filter(privatetopic__pk=g_topic.pk)\
        .order_by('position_in_topic')

    last_post_pk = g_topic.last_message.pk

    # Handle pagination
    paginator = Paginator(posts, settings.POSTS_PER_PAGE)

    try:
        page_nbr = int(request.GET['page'])
    except KeyError:
        page_nbr = 1

    try:
        posts = paginator.page(page_nbr)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        raise Http404

    res = []
    if page_nbr != 1:
        # Show the last post of the previous page
        last_page = paginator.page(page_nbr - 1).object_list
        last_post = (last_page)[len(last_page) - 1]
        res.append(last_post)

    for post in posts:
        res.append(post)

    members = [g_topic.author] + list(g_topic.participants.all())

    return render_template('messages/topic.html', {
        'topic': g_topic, 'posts': res,
        'pages': paginator_range(page_nbr, paginator.num_pages),
        'nb': page_nbr,
        'last_post_pk': last_post_pk,
        'members': members
    })
Exemplo n.º 24
0
def topic(request, topic_pk, topic_slug):
    """Display a topic and its posts using a pager.

    Returns:
        HttpResponse

    """
    # TODO: Clean that up
    g_topic = get_object_or_404(PrivateTopic, pk=topic_pk)

    # Check permissions
    if not is_participant(request.user, g_topic):
        raise PermissionDenied

    # Check link
    if not topic_slug == slugify(g_topic.title):
        return redirect(g_topic.get_absolute_url())

    # Mark the topic as read
    if request.user.is_authenticated():
        if never_privateread(g_topic):
            mark_read(g_topic)

    posts = PrivatePost.objects.all().filter(privatetopic__pk=g_topic.pk)\
        .order_by('position_in_topic')

    last_post_pk = g_topic.last_message.pk

    # Handle pagination
    paginator = Paginator(posts, settings.POSTS_PER_PAGE)

    try:
        page_nbr = int(request.GET['page'])
    except KeyError:
        page_nbr = 1

    try:
        posts = paginator.page(page_nbr)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        raise Http404

    res = []
    if page_nbr != 1:
        # Show the last post of the previous page
        last_page = paginator.page(page_nbr - 1).object_list
        last_post = (last_page)[len(last_page) - 1]
        res.append(last_post)

    for post in posts:
        res.append(post)

    members = [g_topic.author] + list(g_topic.participants.all())

    return render_template(
        'messages/topic.html', {
            'topic': g_topic,
            'posts': res,
            'pages': paginator_range(page_nbr, paginator.num_pages),
            'nb': page_nbr,
            'last_post_pk': last_post_pk,
            'members': members
        })
Exemplo n.º 25
0
def topic(request, topic_pk, topic_slug):
    """Display a thread and its posts using a pager.

    Returns:
        HttpResponse

    """

    # TODO: Clean that up
    g_topic = get_object_or_404(Topic, pk=topic_pk)

    # Check link
    if not topic_slug == slugify(g_topic.title):
        return redirect(g_topic.get_absolute_url())

    # We mark the topic as read
    if request.user.is_authenticated() and never_read(g_topic):
        mark_read(g_topic)

    posts = Post.objects.all() \
        .filter(topic__pk=g_topic.pk) \
        .order_by('position_in_topic')

    last_post_pk = g_topic.last_message.pk

    # Handle pagination
    paginator = Paginator(posts, settings.POSTS_PER_PAGE)

    # The category list is needed to move threads
    categories = Category.objects.all()

    # We try to get page number
    try:
        page_nbr = request.GET['page']
    except KeyError:
        page_nbr = 1

    # We try to page content
    try:
        posts = paginator.page(page_nbr)
        page_nbr = int(page_nbr)
    except PageNotAnInteger:
        posts = paginator.page(1)
        page_nbr = 1
    except EmptyPage:
        raise Http404

    res = []
    if page_nbr > 1:
        # Show the last post of the previous page
        last_page = paginator.page(page_nbr - 1).object_list
        last_post = (last_page)[len(last_page) - 1]
        res.append(last_post)

    for post in posts:
        res.append(post)

    return render_template(
        'forum/topic.html', {
            'topic': g_topic,
            'posts': res,
            'categories': categories,
            'pages': paginator_range(page_nbr, paginator.num_pages),
            'nb': page_nbr,
            'last_post_pk': last_post_pk
        })