Пример #1
0
 def test_wordwrap(self):
     self.assertEqual(wordwrap('this is a long paragraph of text that '
         "really needs to be wrapped I'm afraid", 14),
         'this is a long\nparagraph of\ntext that\nreally needs\nto be '
         "wrapped\nI'm afraid")
     self.assertEqual(wordwrap('this is a short paragraph of text.\n  '
         'But this line should be indented', 14),
         'this is a\nshort\nparagraph of\ntext.\n  But this\nline '
         'should be\nindented')
     self.assertEqual(wordwrap('this is a short paragraph of text.\n  '
         'But this line should be indented', 15), 'this is a short\n'
         'paragraph of\ntext.\n  But this line\nshould be\nindented')
Пример #2
0
 def test_wordwrap(self):
     self.assertEqual(wordwrap('this is a long paragraph of text that '
         "really needs to be wrapped I'm afraid", 14),
         'this is a long\nparagraph of\ntext that\nreally needs\nto be '
         "wrapped\nI'm afraid")
     self.assertEqual(wordwrap('this is a short paragraph of text.\n  '
         'But this line should be indented', 14),
         'this is a\nshort\nparagraph of\ntext.\n  But this\nline '
         'should be\nindented')
     self.assertEqual(wordwrap('this is a short paragraph of text.\n  '
         'But this line should be indented', 15), 'this is a short\n'
         'paragraph of\ntext.\n  But this line\nshould be\nindented')
Пример #3
0
def forum_email_notification(post):
    try:
        mail_subject = settings.FORUM_MAIL_PREFIX
    except AttributeError:
        me = Site.objects.get_current()
        mail_subject = "[%s Forums]" % me.name
    try:
        mail_from = settings.FORUM_MAIL_FROM
    except AttributeError:
        mail_from = settings.DEFAULT_FROM_EMAIL
    mail_tpl = loader.get_template('forum/notify.txt')
    c = Context({
        'body': wordwrap(striptags(post.body), 72),
        'site' : Site.objects.get_current(),
        'thread': post.thread,
        'author' : post.author,
        'subject' : post.thread.title,
        })
    email = EmailMessage(
            subject=mail_subject+' '+striptags(post.thread.title),
            body=mail_tpl.render(c),
            from_email=mail_from,
            to=[mail_from],
            bcc=[s.author.email for s in post.thread.subscription_set.all()])
    email.send(fail_silently=True)
Пример #4
0
 def test_non_string_input(self):
     # Filters shouldn't break if passed non-strings
     self.assertEqual(addslashes(123), '123')
     self.assertEqual(linenumbers(123), '1. 123')
     self.assertEqual(lower(123), '123')
     self.assertEqual(make_list(123), ['1', '2', '3'])
     self.assertEqual(slugify(123), '123')
     self.assertEqual(title(123), '123')
     self.assertEqual(truncatewords(123, 2), '123')
     self.assertEqual(upper(123), '123')
     self.assertEqual(urlencode(123), '123')
     self.assertEqual(urlize(123), '123')
     self.assertEqual(urlizetrunc(123, 1), '123')
     self.assertEqual(wordcount(123), 1)
     self.assertEqual(wordwrap(123, 2), '123')
     self.assertEqual(ljust('123', 4), '123 ')
     self.assertEqual(rjust('123', 4), ' 123')
     self.assertEqual(center('123', 5), ' 123 ')
     self.assertEqual(center('123', 6), ' 123  ')
     self.assertEqual(cut(123, '2'), '13')
     self.assertEqual(escape(123), '123')
     self.assertEqual(linebreaks_filter(123), '<p>123</p>')
     self.assertEqual(linebreaksbr(123), '123')
     self.assertEqual(removetags(123, 'a'), '123')
     self.assertEqual(striptags(123), '123')
Пример #5
0
 def test_wrap(self):
     self.assertEqual(
         wordwrap(
             'this is a long paragraph of text that really needs to be wrapped I\'m afraid',
             14),
         'this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI\'m afraid',
     )
Пример #6
0
 def test_indent2(self):
     self.assertEqual(
         wordwrap(
             'this is a short paragraph of text.\n  But this line should be indented',
             15),
         'this is a short\nparagraph of\ntext.\n  But this line\nshould be\nindented',
     )
Пример #7
0
 def test_wrap_lazy_string(self):
     self.assertEqual(
         wordwrap(lazystr(
             'this is a long paragraph of text that really needs to be wrapped I\'m afraid'
         ), 14),
         'this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI\'m afraid',
     )
Пример #8
0
def forum_email_notification(post):
    try:
        mail_subject = settings.FORUM_MAIL_PREFIX
    except AttributeError:
        me = Site.objects.get_current()
        mail_subject = "[%s Forums]" % me.name
    try:
        mail_from = settings.FORUM_MAIL_FROM
    except AttributeError:
        mail_from = settings.DEFAULT_FROM_EMAIL
    mail_tpl = loader.get_template('forum/notify.txt')
    c = Context({
        'body': wordwrap(striptags(post.body), 72),
        'site': Site.objects.get_current(),
        'thread': post.thread,
        'author': post.author,
        'subject': post.thread.title,
    })
    email = EmailMessage(
        subject=mail_subject + ' ' + striptags(post.thread.title),
        body=mail_tpl.render(c),
        from_email=mail_from,
        to=[mail_from],
        bcc=[s.author.email for s in post.thread.subscription_set.all()])
    email.send(fail_silently=True)
Пример #9
0
 def test_non_string_input(self):
     # Filters shouldn't break if passed non-strings
     self.assertEqual(addslashes(123), '123')
     self.assertEqual(linenumbers(123), '1. 123')
     self.assertEqual(lower(123), '123')
     self.assertEqual(make_list(123), ['1', '2', '3'])
     self.assertEqual(slugify(123), '123')
     self.assertEqual(title(123), '123')
     self.assertEqual(truncatewords(123, 2), '123')
     self.assertEqual(upper(123), '123')
     self.assertEqual(urlencode(123), '123')
     self.assertEqual(urlize(123), '123')
     self.assertEqual(urlizetrunc(123, 1), '123')
     self.assertEqual(wordcount(123), 1)
     self.assertEqual(wordwrap(123, 2), '123')
     self.assertEqual(ljust('123', 4), '123 ')
     self.assertEqual(rjust('123', 4), ' 123')
     self.assertEqual(center('123', 5), ' 123 ')
     self.assertEqual(center('123', 6), ' 123  ')
     self.assertEqual(cut(123, '2'), '13')
     self.assertEqual(escape(123), '123')
     self.assertEqual(linebreaks_filter(123), '<p>123</p>')
     self.assertEqual(linebreaksbr(123), '123')
     self.assertEqual(removetags(123, 'a'), '123')
     self.assertEqual(striptags(123), '123')
Пример #10
0
def license_txt(request, software_id):

    software = get_object_or_404(Software, pk=software_id)
    software_license = software.get_current_license()

    return HttpResponse(
        wordwrap(software_license.text, 80),
        mimetype="text/plain")
Пример #11
0
    def test_wordcount(self):
        self.assertEqual(wordcount(''), 0)
        self.assertEqual(wordcount('oneword'), 1)
        self.assertEqual(wordcount('lots of words'), 3)

        self.assertEqual(wordwrap('this is a long paragraph of text that '
            'really needs to be wrapped I\'m afraid', 14),
            "this is a long\nparagraph of\ntext that\nreally needs\nto be "
            "wrapped\nI'm afraid")

        self.assertEqual(wordwrap('this is a short paragraph of text.\n  '
            'But this line should be indented', 14),
            'this is a\nshort\nparagraph of\ntext.\n  But this\nline '
            'should be\nindented')

        self.assertEqual(wordwrap('this is a short paragraph of text.\n  '
            'But this line should be indented', 15), 'this is a short\n'
            'paragraph of\ntext.\n  But this line\nshould be\nindented')
Пример #12
0
    def test_wordcount(self):
        self.assertEqual(wordcount(''), 0)
        self.assertEqual(wordcount('oneword'), 1)
        self.assertEqual(wordcount('lots of words'), 3)

        self.assertEqual(wordwrap('this is a long paragraph of text that '
            'really needs to be wrapped I\'m afraid', 14),
            "this is a long\nparagraph of\ntext that\nreally needs\nto be "
            "wrapped\nI'm afraid")

        self.assertEqual(wordwrap('this is a short paragraph of text.\n  '
            'But this line should be indented', 14),
            'this is a\nshort\nparagraph of\ntext.\n  But this\nline '
            'should be\nindented')

        self.assertEqual(wordwrap('this is a short paragraph of text.\n  '
            'But this line should be indented', 15), 'this is a short\n'
            'paragraph of\ntext.\n  But this line\nshould be\nindented')
Пример #13
0
 def test_indent2(self):
     self.assertEqual(
         wordwrap(
             "this is a short paragraph of text.\n  But this line should be "
             "indented",
             15,
         ),
         "this is a short\nparagraph of\ntext.\n  But this line\nshould be\n"
         "indented",
     )
Пример #14
0
 def test_wrap(self):
     self.assertEqual(
         wordwrap(
             "this is a long paragraph of text that really needs to be wrapped I'm "
             "afraid",
             14,
         ),
         "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\n"
         "I'm afraid",
     )
Пример #15
0
def license_txt(request, software_id):

    software = get_object_or_404(Software, pk=software_id)
    software_license = software.get_current_license()

    if software_license is None:
        raise Http404('No license found for software')

    return HttpResponse(wordwrap(software_license.text, 80),
                        content_type="text/plain")
Пример #16
0
def license_txt(request, software_id):

    software = get_object_or_404(Software, pk=software_id)
    software_license = software.get_current_license()

    if software_license is None:
        raise Http404('No license found for software')

    return HttpResponse(
        wordwrap(software_license.text, 80),
        content_type="text/plain")
Пример #17
0
 def test_wrap_lazy_string(self):
     self.assertEqual(
         wordwrap(
             lazystr(
                 "this is a long paragraph of text that really needs to be wrapped "
                 "I'm afraid"),
             14,
         ),
         "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\n"
         "I'm afraid",
     )
Пример #18
0
def make_please_review_message(change, account):
  description = defaultfilters.wordwrap(change.description, 70)
  description = '  ' + description.replace('\n', '\n  ')
  sentence = defaultfilters.wordwrap(
      "%(account)s has asked that you review this change." % {
        'account': account.get_email_formatted(),
      }, 70)
  return """Hi,

%(sentence)s

    %(url)s

Thanks.

The commit message for this change is:
%(description)s
""" % { 'url': change_url(change),
        'sentence': sentence,
        'description': description,
      }
Пример #19
0
def make_please_review_message(change, account):
    description = defaultfilters.wordwrap(change.description, 70)
    description = '  ' + description.replace('\n', '\n  ')
    sentence = defaultfilters.wordwrap(
        "%(account)s has asked that you review this change." % {
            'account': account.get_email_formatted(),
        }, 70)
    return """Hi,

%(sentence)s

    %(url)s

Thanks.

The commit message for this change is:
%(description)s
""" % {
        'url': change_url(change),
        'sentence': sentence,
        'description': description,
    }
Пример #20
0
def streaming_ocorrencias(ocorrencias, dumps=dumps):
    yield '[\n'
    for ocorrencia, last in is_last(ocorrencias):
        yield dumps({
            'wkt': filters.safe(ocorrencia.ponto.wkt),
            'name': ocorrencia.titulo,
            'description': filters.wordwrap(ocorrencia.descricao, 10),
            'pk': ocorrencia.pk,
            'style': ocorrencia.get_estilo()
        })
        if not last:
            yield ',\n'
    yield '\n]'
Пример #21
0
def tds_trunc(value, arg):
    "truncate value"
    value = value.strip()
    length = len(value)
    arg = int(arg)
    if length <= arg:
        return value
    else:
        if re.search(r'(\s)', value):
            tmp = wordwrap(value, arg)
            return linebreaksbr(tmp)
        else:
            suffix = '...'
            return value[0:arg] + suffix
Пример #22
0
def tds_trunc(value, arg):
    "truncate value"
    value = value.strip()
    length = len(value)
    arg = int(arg)
    if length <= arg:
        return value
    else:
        if re.search(r'(\s)', value):
            tmp = wordwrap(value, arg)
            return linebreaksbr(tmp)
        else:
            suffix = '...'
            return value[0:arg] + suffix
Пример #23
0
def contact_reference(request, application, send=True, wordwrap=True,
                      subject="", body=""):
    """
    Request verification from a credentialing applicant's reference.

    Args:
        application : CredentialApplication object.
        send : If True, send the email.
        wordwrap : If True, wraps body at 70 characters.
        subject : Subject line.
        body : Body text.

    Returns:
        dict : email name, subject, body
    """
    applicant_name = ' '.join([application.first_names, application.last_name])

    if not subject:
        subject = 'Reference requested for {}'.format(
            applicant_name)
    if not body:
        body = loader.render_to_string(
            'notification/email/contact_reference.html', {
                'application': application,
                'applicant_name': applicant_name,
                'domain': get_current_site(request),
                'url_prefix': get_url_prefix(request),
                'signature': email_signature(),
                'footer': email_footer()
            })

    if wordwrap:
        body = defaultfilters.wordwrap(body, 70)

    if send:
        send_mail(subject, body, settings.CREDENTIAL_EMAIL,
                  [application.reference_email], fail_silently=False)

    return {"subject": subject, "body": body}
Пример #24
0
    def post(self, pool):
        form = forms.InviteForm(self.request.POST)
        if not form.is_valid():
            return self.get(pool, form, 400)

        from lib.jinja import render_to_string
        from django.template.defaultfilters import wordwrap

        email_context = dict(
            pool=pool,
            entries=pool.entries.count())

        subject = u'Invitation to join NFL pool %s' % pool
        body = self.render_to_string('pools/invite.txt', email_context)
        body = wordwrap(body, 72)

        emails = form.cleaned_data['emails']

        for email in form.cleaned_data['emails']:
            mail.send_mail(
                sender=settings.EMAIL_FROM,
                to=email,
                subject=subject,
                body=body)
Пример #25
0
def reply(request, thread):
    """Post a reply.

    If a thread isn't closed, and the user is logged in, post a reply
    to a thread. Note we don't have "nested" replies at this stage.

    @param thread: thread id to reply to
    @type thread: integer
    @return: a view to post a reply
    @rtype: Django response
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect("%s?next=%s" % (reverse("user_signin"), request.path))
    t = get_object_or_404(Thread, pk=thread)
    if t.closed:
        return HttpResponseServerError()
    if not Forum.objects.has_access(t.forum, request.user.groups.all()):
        return HttpResponseForbidden()

    if request.method == "POST":
        form = ReplyForm(request.POST)
        if form.is_valid():
            if request.POST.has_key("preview"):
                preview = {"body": form.cleaned_data["body"]}
            else:
                body = form.cleaned_data["body"]
                p = Post(thread=t, author=request.user, body=body, time=datetime.now())
                p.save()

                sub = Subscription.objects.filter(thread=t, author=request.user)
                if form.cleaned_data.get("subscribe", False):
                    if not sub:
                        s = Subscription(author=request.user, thread=t)
                        s.save()
                else:
                    if sub:
                        sub.delete()

                if t.subscription_set.count() > 0:
                    # Subscriptions are updated now send mail to all the authors subscribed in
                    # this thread.
                    mail_subject = ""
                    try:
                        mail_subject = settings.FORUM_MAIL_PREFIX
                    except AttributeError:
                        mail_subject = "[Forum]"

                    mail_from = ""
                    try:
                        mail_from = settings.FORUM_MAIL_FROM
                    except AttributeError:
                        mail_from = settings.DEFAULT_FROM_EMAIL

                    mail_tpl = loader.get_template("forum/notify.txt")
                    c = RequestContext(
                        {"body": wordwrap(striptags(body), 72), "site": Site.objects.get_current(), "thread": t}
                    )

                    email = EmailMessage(
                        subject=mail_subject + " " + striptags(t.title),
                        body=mail_tpl.render(c),
                        from_email=mail_from,
                        bcc=[s.author.email for s in t.subscription_set.all()],
                    )
                    email.send(fail_silently=True)

                return HttpResponseRedirect(p.get_absolute_url())
    else:
        preview = False
        form = ReplyForm()

    return render_to_response(
        "forum/reply.html",
        RequestContext(request, {"form": form, "forum": t.forum, "thread": t, "preview": preview, "section": "forum"}),
    )
Пример #26
0
def reply(request, thread, flag_partner=False):
	"""
	If a thread isn't closed, and the user is logged in, post a reply
	to a thread. Note we don't have "nested" replies at this stage.
	"""
	if flag_partner:
		if request.user.is_authenticated() and request.user.get_profile().is_partner():pass
		else:
			messages.add_message(request, messages.ERROR, 'Пожалуйста, авторизируйтесь как партнер.')
			return redirect('/accounts/login/?next=%s' % request.path)
			
	if not request.user.is_authenticated():
		return HttpResponseRedirect('%s?next=%s' % (LOGIN_URL, request.path))
	t = get_object_or_404(Thread, pk=thread)
	if t.closed:
		return HttpResponseServerError()
	if not Forum.objects.has_access(t.forum, request.user.groups.all()):
		return HttpResponseForbidden()

	if request.method == "POST":
		form = ReplyForm(request.POST)
		formset = AttachFileFormset(request.POST, request.FILES)
		if form.is_valid() and formset.is_valid():
			p = Post(
				thread=t,
				author=request.user,
				body=form.cleaned_data['body'],
				time=datetime.now(),
			)
			p.save()
			
			formset.instance = p
			formset.save()

			sub = Subscription.objects.filter(thread=t, author=request.user)
			if form.cleaned_data.get('subscribe',False):
				if not sub:
					s = Subscription(author=request.user, thread=t)
					s.save()
			else:
				if sub: sub.delete()

			if t.subscription_set.count() > 0:
				mail_subject = ''
				try: mail_subject = settings.FORUM_MAIL_PREFIX 
				except AttributeError: mail_subject = '[Forum]'

				mail_from = ''
				try: mail_from = settings.FORUM_MAIL_FROM
				except AttributeError: mail_from = settings.DEFAULT_FROM_EMAIL

				mail_tpl = loader.get_template('forum/notify.txt')
				body = form.cleaned_data['body']
				c = Context({
					'body': wordwrap(striptags(body), 72),
					'site' : Site.objects.get_current(),
					'thread': t,
				})

				email = EmailMessage(
					subject=mail_subject+' '+striptags(t.title),
					body= mail_tpl.render(c),
					from_email=mail_from,
					bcc=[s.author.email for s in t.subscription_set.all()],)
				email.send(fail_silently=True)

			return HttpResponseRedirect(p.get_absolute_url())
	else:
		form = ReplyForm()
		formset = AttachFileFormset()
    
	return render_to_response('forum/reply.html',
		RequestContext(request, {
			'form': form,
			'formset': formset,
			'forum': t.forum,
			'thread': t,
			'flag_partner':flag_partner
		}))
Пример #27
0
    def post(self, request, *args, **kwargs):
        """
        If a thread isn't closed, and the user is logged in, post a reply
        to a thread. Note we don't have "nested" replies at this stage.
        """
        if not request.user.is_authenticated():
            return HttpResponseRedirect('%s?next=%s' % (LOGIN_URL, request.path))

        if self.thread.closed:
            return HttpResponseServerError()

        self.object = None
        form_class = self.get_form_class()
        form       = self.get_form(form_class)

        if form.is_valid():
            self.object = form.save(commit=False)
            self.object.thread = self.thread
            self.object.author = request.user
            self.object.time   = timezone.now()
            self.object.save()

            sub = Subscription.objects.filter(thread=self.thread, author=request.user)
            if form.cleaned_data.get('subscribe',False):
                if not sub:
                    s = Subscription(
                        author=request.user,
                        thread=self.thread
                        )
                    s.save()
            else:
                if sub:
                    sub.delete()

            if self.thread.subscription_set.count() > 0:
                # Subscriptions are updated now send mail to all the authors subscribed in
                # this thread.
                mail_subject = ''
                try:
                    mail_subject = settings.FORUM_MAIL_PREFIX
                except AttributeError:
                    mail_subject = '[Forum]'

                mail_from = ''
                try:
                    mail_from = settings.FORUM_MAIL_FROM
                except AttributeError:
                    mail_from = settings.DEFAULT_FROM_EMAIL

                mail_tpl = loader.get_template('forum/notify.txt')
                c = Context({
                    'body': wordwrap(striptags(body), 72),
                    'site' : Site.objects.get_current(),
                    'thread': self.thread,
                    })

                email = EmailMessage(
                        subject=mail_subject+' '+striptags(self.thread.title),
                        body= mail_tpl.render(c),
                        from_email=mail_from,
                        bcc=[s.author.email for s in self.thread.subscription_set.all()],)
                email.send(fail_silently=True)
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

        self.object = None
        return super(PostCreateView, self).post(request, *args, **kwargs)
Пример #28
0
def reply(request, thread):
    """
    If a thread isn't closed, and the user is logged in, post a reply
    to a thread. Note we don't have "nested" replies at this stage.
    """
    if not request.user.is_authenticated():
        return HttpResponseServerError()
    t = get_object_or_404(Thread, pk=thread)
    if t.closed:
        return HttpResponseServerError()
    body = request.POST.get('body', False)
    p = Post(
        thread=t, 
        author=request.user,
        body=body,
        time=datetime.now(),
        )
    p.save()

    sub = Subscription.objects.filter(thread=t, author=request.user)
    if request.POST.get('subscribe',False):
        if not sub:
            s = Subscription(
                author=request.user,
                thread=t
                )
            s.save()
    else:
        if sub:
            sub.delete()

    # Subscriptions are updated now send mail to all the authors subscribed in
    # this thread.
    mail_subject = ''
    try:
        mail_subject = settings.FORUM_MAIL_PREFIX 
    except AttributeError:
        mail_subject = '[Forum]'

    mail_from = ''
    try:
        mail_from = settings.FORUM_MAIL_FROM
    except AttributeError:
        mail_from = settings.DEFAULT_FROM_EMAIL

    mail_tpl = loader.get_template('forum/notify.txt')
    c = Context({
        'body': wordwrap(striptags(body), 72),
        'site' : Site.objects.get_current(),
        'thread': t,
        })

    #email = EmailMessage('Hello', 'Body goes here', '*****@*****.**',
    #            ['*****@*****.**', '*****@*****.**'], ['*****@*****.**'],
    #                        headers = {'Reply-To': '*****@*****.**'})
    email = EmailMessage(
            subject=mail_subject+' '+striptags(t.title),
            body= mail_tpl.render(c),
            from_email=mail_from,
            to=[mail_from],
            bcc=[s.author.email for s in t.subscription_set.all()],)
    email.send(fail_silently=True)

    return HttpResponseRedirect(p.get_absolute_url())
def reply(request, thread):
    """
    If a thread isn't closed, and the user is logged in, post a reply
    to a thread. Note we don't have "nested" replies at this stage.
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('%s?next=%s' % (LOGIN_URL, request.path))
    t = get_object_or_404(Thread, pk=thread)
    if t.closed:
        return HttpResponseServerError()
    if not Forum.objects.has_access(t.forum, request.user.groups.all()):
        return HttpResponseForbidden()

    if request.method == "POST":
        form = ReplyForm(request.POST)
        if form.is_valid():
            body = form.cleaned_data['body']
            p = Post(
                thread=t,
                author=request.user,
                body=body,
                time=datetime.now(),
            )
            p.save()

            sub = Subscription.objects.filter(thread=t, author=request.user)
            if form.cleaned_data.get('subscribe', False):
                if not sub:
                    s = Subscription(author=request.user, thread=t)
                    s.save()
            else:
                if sub:
                    sub.delete()

            if t.subscription_set.count() > 0:
                # Subscriptions are updated now send mail to all the authors subscribed in
                # this thread.
                mail_subject = ''
                try:
                    mail_subject = settings.FORUM_MAIL_PREFIX
                except AttributeError:
                    mail_subject = '[Forum]'

                mail_from = ''
                try:
                    mail_from = settings.FORUM_MAIL_FROM
                except AttributeError:
                    mail_from = settings.DEFAULT_FROM_EMAIL

                mail_tpl = loader.get_template('forum/notify.txt')
                c = Context({
                    'body': wordwrap(striptags(body), 72),
                    'site': Site.objects.get_current(),
                    'thread': t,
                })

                email = EmailMessage(
                    subject=mail_subject + ' ' + striptags(t.title),
                    body=mail_tpl.render(c),
                    from_email=mail_from,
                    bcc=[s.author.email for s in t.subscription_set.all()],
                )
                email.send(fail_silently=True)

            return HttpResponseRedirect(p.get_absolute_url())
    else:
        form = ReplyForm()

    return render_to_response(
        'forum/reply.html',
        RequestContext(request, {
            'form': form,
            'forum': t.forum,
            'thread': t,
        }))
Пример #30
0
 def test_non_string_input(self):
     self.assertEqual(wordwrap(123, 2), '123')
Пример #31
0
def wordwrap(context, value, arg=None):
    return filters.wordwrap(value, arg)
Пример #32
0
def edit(request, thread):
    """
    If a thread isn't closed, and the user is logged in, post a reply
    to a thread. Note we don't have "nested" replies at this stage.
    """
    if not request.user.is_authenticated():
        return HttpResponseServerError()
    t = get_object_or_404(Thread, pk=thread)
    if t.closed:
        return HttpResponseServerError()
    if not Forum.objects.has_access(t.forum, request.user.groups.all()):
        return HttpResponseForbidden()

    if request.method == "POST":
        form = ReplyForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            body = form.cleaned_data['body']
            p = Post(
                thread=t,
                author=request.user,
                body=body,
                time=datetime.now(),
                )
            p.save()

            sub = Subscription.objects.filter(thread=t, author=request.user)
            if form.cleaned_data.get('subscribe',False):
                if not sub:
                    s = Subscription(
                        author=request.user,
                        thread=t
                        )
                    s.save()
            else:
                if sub:
                    sub.delete()

            # Subscriptions are updated now send mail to all the authors subscribed in
            # this thread.
            mail_subject = ''
            try:
                mail_subject = settings.FORUM_MAIL_PREFIX
            except AttributeError:
                mail_subject = '[Forum]'

            mail_from = ''
            try:
                mail_from = settings.FORUM_MAIL_FROM
            except AttributeError:
                mail_from = settings.DEFAULT_FROM_EMAIL

            mail_tpl = loader.get_template('forum/notify.txt')
            c = Context({
                'body': wordwrap(striptags(body), 72),
                'site' : Site.objects.get_current(),
                'thread': t,
                })

            email = EmailMessage(
                    subject=mail_subject+' '+striptags(t.title),
                    body= mail_tpl.render(c),
                    from_email=mail_from,
                    to=[mail_from],
                    bcc=[s.author.email for s in t.subscription_set.all()],)
            email.send(fail_silently=True)

            for attachedfilefield in form.files:
                #file_path = '%s%s' % (settings.MEDIA_ROOT, form.files[attachedfilefield])
                attachment_file = form.files[attachedfilefield]
                attach=Attachment()
                attach.handle_uploaded_attachment(p,
                    attachment_file,
                    request.user,
                    attachment_file.name,
                    t.title
                    )

            return HttpResponseRedirect(p.get_absolute_url())
    else:
        post_id = request.GET.get('pid', 0)
        if post_id ==0:
            return HttpResponseServerError(_("The Post Do Not Exist"))
        try:
            p = Post.objects.all().get(id=post_id)
        except Post.DoesNotExist:
            raise Http404(_("Not Found"))
        
        body=p.body
        initial = {'subscribe': True,
            'body':body}
        form = ReplyForm(initial=initial)

    return render_to_response('forum/edit.html',
        RequestContext(request, {
            'form': form,
            'post': p
        }))
Пример #33
0
    def post(self, request, *args, **kwargs):
        """
        If a thread isn't closed, and the user is logged in, post a reply
        to a thread. Note we don't have "nested" replies at this stage.
        """
        if not request.user.is_authenticated():
            return HttpResponseRedirect('%s?next=%s' %
                                        (LOGIN_URL, request.path))

        if self.thread.closed:
            return HttpResponseServerError()

        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        if form.is_valid():
            self.object = form.save(commit=False)
            self.object.thread = self.thread
            self.object.author = request.user
            self.object.time = timezone.now()
            self.object.save()

            sub = Subscription.objects.filter(thread=self.thread,
                                              author=request.user)
            if form.cleaned_data.get('subscribe', False):
                if not sub:
                    s = Subscription(author=request.user, thread=self.thread)
                    s.save()
            else:
                if sub:
                    sub.delete()

            if self.thread.subscription_set.count() > 0:
                # Subscriptions are updated now send mail to all the authors subscribed in
                # this thread.
                mail_subject = ''
                try:
                    mail_subject = settings.FORUM_MAIL_PREFIX
                except AttributeError:
                    mail_subject = '[Forum]'

                mail_from = ''
                try:
                    mail_from = settings.FORUM_MAIL_FROM
                except AttributeError:
                    mail_from = settings.DEFAULT_FROM_EMAIL

                mail_tpl = loader.get_template('forum/notify.txt')
                c = Context({
                    'body': wordwrap(striptags(body), 72),
                    'site': Site.objects.get_current(),
                    'thread': self.thread,
                })

                email = EmailMessage(
                    subject=mail_subject + ' ' + striptags(self.thread.title),
                    body=mail_tpl.render(c),
                    from_email=mail_from,
                    bcc=[
                        s.author.email
                        for s in self.thread.subscription_set.all()
                    ],
                )
                email.send(fail_silently=True)
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

        self.object = None
        return super(PostCreateView, self).post(request, *args, **kwargs)
Пример #34
0
 def test_indent2(self):
     self.assertEqual(
         wordwrap('this is a short paragraph of text.\n  But this line should be indented', 15),
         'this is a short\nparagraph of\ntext.\n  But this line\nshould be\nindented',
     )
Пример #35
0
 def test_non_string_input(self):
     self.assertEqual(wordwrap(123, 2), '123')
Пример #36
0
def reply(request, thread):
    """
    If a thread isn't closed, and the user is logged in, post a reply
    to a thread. Note we don't have "nested" replies at this stage.
    """
    if not request.user.is_authenticated():
        return HttpResponseServerError()
    t = get_object_or_404(Thread, pk=thread)
    if t.closed:
        return HttpResponseServerError()
    if not Forum.objects.has_access(t.forum, request.user.groups.all()):
        return HttpResponseForbidden()

    if request.method == "POST":
        form = ReplyForm(request.POST)
        if form.is_valid():
            body = form.cleaned_data['body']
            p = Post(
                thread=t, 
                author=request.user,
                body=body,
                time=datetime.now(),
                )
            p.save()

            sub = Subscription.objects.filter(thread=t, author=request.user)
            if form.cleaned_data.get('subscribe',False):
                if not sub:
                    s = Subscription(
                        author=request.user,
                        thread=t
                        )
                    s.save()
            else:
                if sub:
                    sub.delete()

            # Subscriptions are updated now send mail to all the authors subscribed in
            # this thread.
            mail_subject = ''
            try:
                mail_subject = settings.FORUM_MAIL_PREFIX 
            except AttributeError:
                mail_subject = '[Forum]'

            mail_from = ''
            try:
                mail_from = settings.FORUM_MAIL_FROM
            except AttributeError:
                mail_from = settings.DEFAULT_FROM_EMAIL

            mail_tpl = loader.get_template('forum/notify.txt')
            c = Context({
                'body': wordwrap(striptags(body), 72),
                'site' : Site.objects.get_current(),
                'thread': t,
                })

            email = EmailMessage(
                    subject=mail_subject+' '+striptags(t.title),
                    body= mail_tpl.render(c),
                    from_email=mail_from,
                    to=[mail_from],
                    bcc=[s.author.email for s in t.subscription_set.all()],)
            email.send(fail_silently=True)

            return HttpResponseRedirect(p.get_absolute_url())
    else:
        form = ReplyForm()
    
    return render_to_response('forum/reply.html',
        RequestContext(request, {
            'form': form,
            'forum': t.forum,
            'thread': t,
        }))
Пример #37
0
def reply(request, thread):
    """
    If a thread isn't closed, and the user is logged in, post a reply
    to a thread. Note we don't have "nested" replies at this stage.
    """
    if not request.user.is_authenticated():
        return HttpResponseServerError()
    t = get_object_or_404(Thread, pk=thread)
    if t.closed:
        return HttpResponseServerError()
    if not Forum.objects.has_access(t.forum, request.user.groups.all()):
        return HttpResponseForbidden()

    if request.method == "POST":
        form = ReplyForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            body = form.cleaned_data['body']
            p = Post(
                thread=t,
                author=request.user,
                body=body,
                time=datetime.now(),
                )
            p.save()

            sub = Subscription.objects.filter(thread=t, author=request.user)
            if form.cleaned_data.get('subscribe',False):
                if not sub:
                    s = Subscription(
                        author=request.user,
                        thread=t
                        )
                    s.save()
            else:
                if sub:
                    sub.delete()

            # Subscriptions are updated now send mail to all the authors subscribed in
            # this thread.
            mail_subject = ''
            try:
                mail_subject = settings.FORUM_MAIL_PREFIX
            except AttributeError:
                mail_subject = '[Forum]'

            mail_from = ''
            try:
                mail_from = settings.FORUM_MAIL_FROM
            except AttributeError:
                mail_from = settings.DEFAULT_FROM_EMAIL

            mail_tpl = loader.get_template('forum/notify.txt')
            c = Context({
                'body': wordwrap(striptags(body), 72),
                'site' : Site.objects.get_current(),
                'thread': t,
                })

            email = EmailMessage(
                    subject=mail_subject+' '+striptags(t.title),
                    body= mail_tpl.render(c),
                    from_email=mail_from,
                    to=[mail_from],
                    bcc=[s.author.email for s in t.subscription_set.all()],)
            email.send(fail_silently=True)

##            data={'title': t.title,
##                'summary': t.title,
##                'attached_timestamp':datetime.now()
##                }
##            attachment_form=AttachmentForm(data=data,files=form.files)
##            a=attachment_form.errors
##            content_type =ContentType.objects.get_for_model(Post)
##            object_id = p.id
##            ffs=form.files
##            debug()
##            if attachment_form.is_valid():
##                attachment = attachment_form.save(commit=False)
##                attachment.content_type = content_type
##                attachment.object_id = object_id
##                attachment.attached_by = request.user
##                attachment.save()

#            for attachedfilefield in form.files:
#                #file_path = '%s%s' % (settings.MEDIA_ROOT, form.files[attachedfilefield])
#                attachment_file = form.files[attachedfilefield]
#                file_path =os.path.join(ATTACHMENT_DIR, randomfilename(attachment_file.name))
#                (mimetype, encoding) = mimetypes.guess_type(file_path)
#
#                try:
#                    mime_type = mimetype
#                except:
#                    mime_type = 'text/plain'
#
#                attach=Attachment(
#                    content_type =ContentType.objects.get_for_model(Post),
#                    object_id = p.id,
#                    title = attachment_file.name,
#                    summary = t.title,
#                    attached_by = request.user,
#                    )
#                attach.save_uploaded_file(attachment_file)
#                attach.save()


            for attachedfilefield in form.files:
                #file_path = '%s%s' % (settings.MEDIA_ROOT, form.files[attachedfilefield])
                attachment_file = form.files[attachedfilefield]
                attach=Attachment()
                attach.handle_uploaded_attachment(p,
                    attachment_file,
                    request.user,
                    attachment_file.name,
                    t.title
                    )

            return HttpResponseRedirect(p.get_absolute_url())
    else:
        form = ReplyForm()

    return render_to_response('forum/reply.html',
        RequestContext(request, {
            'form': form,
            'forum': t.forum,
            'thread': t,
        }))