示例#1
0
    def save(self):

        try:

            title = self.validated_data['title']
            if len(title) < MIN_TITLE_LENGTH:
                raise serializers.ValidationError({
                    "response":
                    "Enter a title longer than " + str(MIN_TITLE_LENGTH) +
                    " characters."
                })

            body = self.validated_data['body']
            if len(body) < MIN_BODY_LENGTH:
                raise serializers.ValidationError({
                    "response":
                    "Enter a body longer than " + str(MIN_BODY_LENGTH) +
                    " characters."
                })

            blog_post = BlogPost(
                author=self.validated_data['author'],
                title=title,
                body=body,
            )
            blog_post.save()
            return blog_post
        except KeyError:
            raise serializers.ValidationError(
                {"response": "You must have a title, some content."})
示例#2
0
    def post(self, request):
        subject = request.POST['subject']
        content = request.POST['content']
        slug = titleToUrl(subject)
        published = request.POST['published'] == 'published'

        if not subject:
            messages.add_message(request, messages.INFO, 'Please add a subject.')
        if not content:
            messages.add_message(request, messages.INFO, 'Please add some content.')
        if not BlogPost.objects.filter(slug=slug).count() == 0:
            messages.add_message(request, messages.INFO, 'Please rename, you\'ve used that title before.')
        if messages.get_messages(request):
            params = {'subject': subject,
                      'content': content,
                      'published': published}
            return render(request, 'blog_create.html', params)
        else:
            post = BlogPost(title=subject,
                            body=content,
                            slug=slug,
                            published=published)
            post.save()
            messages.add_message(request, messages.SUCCESS, 'Blog post created.')
            return HttpResponseRedirect(reverse('blog_SinglePost', args=(slug,)))
示例#3
0
    def test_with_data_using_obj(self):

        category_key = self.categories.add("category")

        test_tags = ["a new tag", "a new new tag"]
        new_tag_keys = self.tags.add(test_tags)

        answer = Answer(p_answer="a test answer", is_correct=False)

        post = BlogPost(title="a title",
                        body="body text",
                        category=category_key,
                        tags=new_tag_keys,
                        summary="this is a summary",
                        answers=[answer])

        post.put()
        with open(os.path.join(TEST_IMAGE)) as f:
            self.assertTrue(post.add_blob(f.read(), TEST_IMAGE, 'image/jpeg'))

        form = PostForm(obj=post)
        # form.answers.append_entry(answer_field)
        #print (form.answers)

        self.assertEqual(form.title.data, "a title")
        self.assertEqual(form.body.data, "body text")
        self.assertEqual(form.answers[0].p_answer.data, "a test answer")
        self.assertEqual(form.images[0].filename.data, TEST_IMAGE)
示例#4
0
    def setUp(self):

        # Create author
        author = User.objects.create_superuser('author',
                                               '*****@*****.**',
                                               'authorpassword')

        # Create user for comment
        user_comment = User.objects.create_user('comment_user',
                                                '*****@*****.**',
                                                'commentpassword')

        self.test_post = BlogPost(title='test_title',
                                  slug='test_title',
                                  author=author,
                                  category='test_category',
                                  content='blog_content',
                                  status=1)
        self.test_post.save()

        self.blog_image = BlogImage(article_id=self.test_post)
        self.blog_image.image = SimpleUploadedFile(name='test_image.jpg',
                                                   content=b'',
                                                   content_type='image/jpeg')
        self.blog_image.save()
        self.test_blogcomment = BlogComment(article_id=self.test_post,
                                            user_id=user_comment,
                                            comment_title='test_comment_title')
        self.test_blogcomment.save()
示例#5
0
 def test_cannot_create_post_without_body(self):
     blog_post = BlogPost(title="",
                          date=datetime.datetime.now(),
                          body="",
                          visible=True)
     with self.assertRaises(ValidationError):
         blog_post.full_clean()
示例#6
0
def publish(request):
    if request.user.is_authenticated:
        if request.user.profile.is_verified == "VF" and request.user.profile.is_email_verified == "VF":
            if request.method == "POST":
                title = request.POST.get("title")
                first_heading = request.POST.get("first_heading")
                first_content = request.POST.get("first_content")
                second_heading = request.POST.get("second_heading")
                second_content = request.POST.get("second_content")
                sub_heading = request.POST.get("sub_heading")
                sub_content = request.POST.get("sub_content")

                publish = BlogPost(title=title,
                                   heading1=first_heading,
                                   content_heading1=first_content,
                                   heading2=second_heading,
                                   content_heading2=second_content,
                                   sub_heading=sub_heading,
                                   sub_heading_content=sub_content,
                                   author=request.user.first_name)
                publish.save()
                messages.success(
                    request,
                    "Your content has been submitted successfully for review. Your content will be published after successful review."
                )
                return HttpResponseRedirect("/blog/publish")
        else:
            return HttpResponseRedirect("/home/notVerified")
    else:
        return HttpResponseRedirect("/home/cannot_access")
    return render(request, "blog/publish.html")
示例#7
0
def create_blog(request):
    form = ArticleForm(request.POST)
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = ArticleForm(request.POST, request.FILES)
        # check whether it's valid:
        if form.is_valid():
            title = form.cleaned_data['title']
            lead_paragraph = form.cleaned_data['lead_paragraph']
            content = form.cleaned_data['content']
            title = request.POST['title']
            lead_paragraph = request.POST['lead_paragraph']
            image = request.FILES['image']
            content = request.POST['content']
            #create slug from title-input
            slug = create_slug_text(title)
            new_article = BlogPost(title=title,
                                   lead_paragraph=lead_paragraph,
                                   image=image,
                                   slug=slug,
                                   meta_title=title,
                                   meta_description=lead_paragraph,
                                   content=content)
            new_article.save()
            # redirect to a blog_post_url:
            return redirect('blog_thanks')
            # if a GET (or any other method) we'll create a blank form
        else:
            form = ArticleForm()
    context = {
        'form': form
        }
    return render(request, "blog/edit/form.html", context)
示例#8
0
    def test_stripped_answers(self):
        test_tags = ["a new tag", "a new new tag"]
        tag_keys = self.tags.add(test_tags)

        ans1 = Answer(p_answer="ans1", is_correct=True)

        ans2 = Answer(p_answer="ans2", is_correct=False)

        category_key = self.categories.add("category")
        summary = "a summmary"
        title = "a title"
        body = "here is a body"

        post_key = BlogPost(title=title,
                            body=body,
                            category=category_key,
                            tags=tag_keys,
                            summary=summary,
                            answers=[ans1, ans2]).put()

        post = post_key.get()
        jsoned_answers = [{
            "p_answer": "ans1",
            "is_correct": False
        }, {
            "p_answer": "ans2",
            "is_correct": False
        }]

        self.assertItemsEqual(post.strip_answers_jsoned(), jsoned_answers)
示例#9
0
 def setUp(self):
     
     # Create an initial object to test with
     post = BlogPost(title=u'Hello Wørld', text=u'Hello World, this is dynamicresponse. ÆØÅæøå.')
     post.save()
     
     self.post = post
示例#10
0
    def save(self):

        try:
            image = self.validated_data['image']
            title = self.validated_data['title']
            if len(title) < MIN_TITLE_LENGTH:
                raise serializers.ValidationError({
                    "response":
                    "Enter a title longer than " + str(MIN_TITLE_LENGTH) +
                    " characters."
                })

            body = self.validated_data['body']
            if len(body) < MIN_BODY_LENGTH:
                raise serializers.ValidationError({
                    "response":
                    "Enter a body longer than " + str(MIN_BODY_LENGTH) +
                    " characters."
                })

            blog_post = BlogPost(
                author=self.validated_data['author'],
                title=title,
                body=body,
                image=image,
            )

            url = os.path.join(settings.TEMP, str(image))
            storage = FileSystemStorage(location=url)

            with storage.open('', 'wb+') as destination:
                for chunk in image.chunks():
                    destination.write(chunk)
                destination.close()

            # Check image size
            if not is_image_size_valid(url, IMAGE_SIZE_MAX_BYTES):
                os.remove(url)
                raise serializers.ValidationError({
                    "response":
                    "That image is too large. Images must be less than 2 MB. Try a different image."
                })

            # Check image aspect ratio
            if not is_image_aspect_ratio_valid(url):
                os.remove(url)
                raise serializers.ValidationError({
                    "response":
                    "Image height must not exceed image width. Try a different image."
                })

            os.remove(url)
            blog_post.save()
            return blog_post
        except KeyError:
            raise serializers.ValidationError({
                "response":
                "You must have a title, some content, and an image."
            })
示例#11
0
    def setUp(self):

        # Create an initial object to test with
        post = BlogPost(title=u'Hello Wørld',
                        text=u'Hello World, this is dynamicresponse. ÆØÅæøå.')
        post.save()

        self.post = post
示例#12
0
class ViewTestCase(BlogTests):
    def setUp(self):
        super().setUp()
        self.foo = BlogPost(author=self.staff, title='foo', content='bar')
        self.foo.save()

    def test_index(self):
        response = self.client.get(reverse('blog_index'), follow=True)
        context = response.context[-1]
        self.assertEqual(set(context['posts']), set(BlogPost.objects.all()))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'blog/index.html')

    def test_create_get_no_user(self):
        response = self.client.get(reverse('blog_create'), follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertRedirects(response, '/admin/login/?next=/blog/create')

    def test_create_get_staff_user(self):
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.get(reverse('blog_create'), follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'blog/create.html')
        context = response.context[-1]
        self.assertTrue(isinstance(context['form'], BlogPostForm))

    def test_create_post_by_normal_user(self):
        count = BlogPost.objects.count()
        response = self.client.post(reverse('blog_create'), {
            'author': self.normal.id,
            'title': 'foo',
            'content': 'bar'
        },
                                    follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(count, BlogPost.objects.count())

    def test_create_post_by_staff_user(self):
        count = BlogPost.objects.count()
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.post(reverse('blog_create'), {
            'author': self.staff.id,
            'title': 'bar',
            'content': 'baz'
        },
                                    follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(count + 1, BlogPost.objects.count())

    def test_edit_get_staff_user(self):
        blog_post_id = BlogPost.objects.values('id')[0]['id']
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.post(reverse('blog_edit',
                                            kwargs={'pk': blog_post_id}), {},
                                    follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'blog/create.html')
示例#13
0
class StatusTests(TestCase):
    fixtures = ['devel']

    def setUp(self):
        self.client.login(username='******', password='******')
        self.user = ActiveUser.objects.filter(username='******')[0]
        self.post = BlogPost(title='Hello World!',
                        author=self.user,
                        tags='hello world',
                        abstract='Hello World!',
                        text='Hello World!',
                        priority=BlogPost.PRIORITY_NORMAL)
        self.post.save()

        self.url = reverse('blog_pending_edit', kwargs={'pk': self.post.pk})
        self.form = {
            'title': self.post.title,
            'abstract': self.post.abstract,
            'tags': self.post.tags,
            'text': self.post.text,
            'priority': self.post.priority
        }

    def test_draft(self):
        self.form['action'] = UserCreatePostForm.ACTION_DRAFT
        response = self.client.post(self.url, self.form, follow=True)
        self.post.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertLessEqual((datetime.datetime.now() - self.post.date_modified).total_seconds(), 10)

    def test_submitted(self):
        self.post.status = BlogPost.STATUS_DRAFT
        self.post.save()

        self.form['action'] = UserCreatePostForm.ACTION_SUBMIT
        response = self.client.post(self.url, self.form, follow=True)
        self.assertEqual(response.status_code, 200)

    def test_approved(self):
        self.form['action'] = UserCreatePostForm.ACTION_APPROVE
        response = self.client.post(self.url, self.form, follow=True)
        self.post.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertLessEqual((datetime.datetime.now() - self.post.date_approved).total_seconds(), 10)

    def test_published(self):
        self.form['action'] = UserCreatePostForm.ACTION_PUBLISH
        response = self.client.post(self.url, self.form, follow=True)
        self.post.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertLessEqual((datetime.datetime.now() - self.post.date_published).total_seconds(), 10)

    def test_reject(self):
        self.form['action'] = UserCreatePostForm.ACTION_DELETE
        response = self.client.post(self.url, self.form, follow=True)
        self.assertEqual(response.status_code, 200)
示例#14
0
def add_post(request):
    if request.method == 'POST':
        post = BlogPost(title=request.POST.get('title'),
                        body=request.POST.get('body'),
                        timestamp=datetime.now())

        post.save()
        return django.http.HttpResponseRedirect('/blog/')
    else:
        return django.http.HttpResponseForbidden()
示例#15
0
def add_post(request):
    get_title = request.POST['post_title']
    get_post_image = request.FILES.get('post_image', None)
    get_content = request.POST['post_content']
    get_content_preview = content_preview_text_gen(get_content)
    get_datetime = timezone.now()
    get_user = request.user
    p = BlogPost(title=get_title, post_image=get_post_image, content=get_content, content_preview=get_content_preview, datetime=get_datetime, author=get_user)
    p.save()
    return HttpResponseRedirect(reverse('blog:index'))
示例#16
0
def save(request, url):
    posts = BlogPost.objects.all()
    for post in posts:
        if post.id == int(url):
            b = BlogPost(body=request.GET.get('body'), title=request.GET.get('title'), id=post.id,
                         timestamp=timezone.now())
            b.save()
            t = loader.get_template("article.html")
            c = Context({'post': b})
            return HttpResponse(t.render(c))
示例#17
0
 def test_blog_image(self):
     user_1 = User(username='******')
     user_1.save()
     blog = BlogPost(title='blog_title', category='category', author=user_1)
     blog.save()
     blog_image = BlogImage(article_id=blog)
     blog_image.image = SimpleUploadedFile(name='test_image.jpg',
                                           content=b'',
                                           content_type='image/jpeg')
     self.assertEqual(str(blog_image),
                      'test_image.jpg, blog_title, category')
示例#18
0
    def setUp(self):

        # Headers for GET requests
        self.extra_headers = {'HTTP_ACCEPT': 'application/json'}

        # Create an initial object to test with
        post = BlogPost(title=u'Hello Wørld',
                        text=u'Hello World, this is dynamicresponse. ÆØÅæøå.')
        post.save()

        self.post = post
示例#19
0
 def setUp(self):
     
     # Headers for GET requests
     self.extra_headers = {
         'HTTP_ACCEPT': 'application/json'
     }
     
     # Create an initial object to test with
     post = BlogPost(title=u'Hello Wørld', text=u'Hello World, this is dynamicresponse. ÆØÅæøå.')
     post.save()
     
     self.post = post
示例#20
0
    def test_drafedit(self):
        post = BlogPost(title='Hello World!',
                        author=self.user,
                        tags='hello world',
                        abstract='Hello World!',
                        text='Hello World!',
                        priority=BlogPost.STATUS_DRAFT)
        post.save()

        url = reverse('blog_draft_edit', kwargs={'pk': post.pk})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
示例#21
0
文件: seed.py 项目: Hamband/django
 def seed_blog_posts(self):
     self.stdout.write('Seed Blog posts...\n')
     BlogPost.objects.all().delete()
     date = self.fake.date_between(start_date='-30y', end_date='today')
     for i in range(4):
         post = BlogPost(author=self.get_random_user(),
                         poster=None,
                         subject=self.fake_fa.sentence(),
                         content=self.fake_fa.text(),
                         published_at=date,
                         updated_at=date)
         post.save()
示例#22
0
    def test_publish__commit_false(self):
        user = User()
        post = BlogPost(
            status=BlogPost.Status.DRAFT,
            published=None,
            author=None
        )

        post.publish(user, commit=False)

        self.assertEqual(post.author, user)
        self.assertIsNotNone(post.published)
        self.assertEqual(post.status, BlogPost.Status.PUBLISHED)
示例#23
0
    def test_get_a_post(self):
        category_key = self.categories.add("category")
        test_tags = ["a new tag", "a new new tag"]
        new_tag_keys = self.tags.add(test_tags)
        post_key = self.posts.add("a title", "body text", category_key,
                                  new_tag_keys)

        #test with no memcache
        post = BlogPost.get(post_key.id())
        self.assertEqual(post.key, post_key)

        #test memcached
        post = BlogPost.get(post_key.id())
        self.assertEqual(post.key, post_key)
示例#24
0
    def setUpTestData(cls):
        cls.blog1 = BlogPost(
            title='I am a title 1!',
            description='Description 1.',
            author='*****@*****.**'
        )
        cls.blog1.save()

        cls.blog2 = BlogPost(
            title='I am a title 2!',
            description='Description 2.',
            author='*****@*****.**'
        )
        cls.blog2.save()
示例#25
0
 def post(self, request):
     data = request.body.decode('utf8')
     data = json.loads(data)
     try:
         # print(request.META)
         user = get_user(request)
         if not user:
             return JsonResponse({"error": "not valid auth"}, safe=False)
         new_blogpost = BlogPost(name=data["name"],
                                 text=data["text"],
                                 created_by_id=user.id)
         new_blogpost.save()
         return JsonResponse({"created": data}, safe=False)
     except:
         return JsonResponse({"error": "not a valid data"}, safe=False)
示例#26
0
    def test_blog(self):
        blog = Blog(title="test blog")
        blog.save()
        self.assertIsInstance(blog, Blog)

        blog_post = BlogPost(blog=blog, title="test post",
                content="this is content")
        blog_post.save()
        self.assertIsInstance(blog_post, BlogPost)

        get_by_slug = BlogPost.objects.get_by_slug(blog_post.slug)
        self.assertIsInstance(get_by_slug, BlogPost)

        homepage = BlogPost.objects.homepage_posts()
        self.assertEquals(len(homepage), 1)
示例#27
0
    def test_create_post(self):
        user = User.objects.get(username='******')
        post = BlogPost(user=user)

        post.title = "My test post"
        post.content = "This is a test post"

        post.save()

        all_posts = BlogPost.objects.all()
        self.assertEquals(len(all_posts), 1)
        only_post = all_posts[0]
        self.assertEquals(only_post, post)

        self.assertEquals(only_post.title, "My test post")
示例#28
0
文件: serializers.py 项目: onats1/src
    def save(self):

        try:
            image = self.validated_data['image']
            title = self.validated_data['title']
            if len(title) < MIN_TITLE_LENGTH:
                raise serializers.ValidationError(
                    {"response": "Enter a title longer than " + str(MIN_TITLE_LENGTH) + " characters."})

            body = self.validated_data['body']
            if len(body) < MIN_BODY_LENGTH:
                raise serializers.ValidationError(
                    {"response": "Enter a body longer than " + str(MIN_BODY_LENGTH) + " characters."})

            blog_post = BlogPost(
                author=self.validated_data['author'],
                title=title,
                body=body,
                image=image,
            )

            url = os.path.join(settings.TEMP, str(image))
            storage = FileSystemStorage(location=url)

            with storage.open('', 'wb+') as destination:
                for chunk in image.chunks():
                    destination.write(chunk)
                destination.close()

            if sys.getsizeof(image.file) > IMAGE_SIZE_MAX_BYTES:
                os.remove(url)
                raise serializers.ValidationError(
                    {"response": "That image is too large. Images must be less than 3 MB. Try a different image."})

            img = cv2.imread(url)
            dimensions = img.shape  # gives: (height, width, ?)

            aspect_ratio = dimensions[1] / dimensions[0]  # divide w / h
            if aspect_ratio < 1:
                os.remove(url)
                raise serializers.ValidationError(
                    {"response": "Image height must not exceed image width. Try a different image."})

            os.remove(url)
            blog_post.save()
            return blog_post
        except KeyError:
            raise serializers.ValidationError({"response": "You must have a title, some content, and an image."})
示例#29
0
def create(request):
    if request.method == 'POST':
        BlogPost(
            title=request.POST.get('title'),
            body=request.POST.get('body'),
        ).save()
    return HttpResponseRedirect('/blog')
示例#30
0
def post_detail(request, blog_name=None, post_key_name=None):
    post = BlogPost.get_by_key_name(post_key_name,
                                    parent=db.Key.from_path('Blog', blog_name))
    if not post:
        return HttpResponse404()
    return render_to_response('post_detail.html', {'post': post},
                              RequestContext(request))
示例#31
0
    def get_context_data(self, *args, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['pages_menu'] = Page.objects.exclude(is_menu=False)
        try:
            ctx['company_info'] = Appearance.objects.all().first()
        except ObjectDoesNotExist:
            ctx['company_info'] = None
        ctx['socialsite_info'] = Socialsite.objects.all()
        try:
            ctx['blog'] = BlogTitle.objects.first()
        except ObjectDoesNotExist:
            ctx['blog'] = None
        try:
            ctx['popular_posts_qs'] = BlogPost.all_post(
                check_deadline=True).order_by('-count')[:4]
        except ObjectDoesNotExist:
            ctx['popular_posts_qs'] = None

        try:
            ctx['notices'] = Notice.objects.all()[:3]
        except ObjectDoesNotExist:
            ctx['notices'] = None
        ctx['footer_links'] = Page.objects.filter(is_footer_link=True)

        return ctx
示例#32
0
def create_post():
    form = BlogPostForm()

    if (form.validate_on_submit() or request.method == "POST"):
        post = BlogPost(title=form.title.data,
                        category=form.category.data,
                        text=form.text.data,
                        user_id=current_user.id)
        db.session.add(post)
        db.session.commit()

        followers = Followers.query.filter_by(
            followed_id=current_user.id).all()

        for follower in followers:
            notif = Notifications(
                follower.follower_id,
                f'{current_user.username} has posted a blog "{form.title.data}"!',
                post.id, True)
            db.session.add(notif)

        db.session.add(post)
        db.session.commit()

        flash('Post Created!')

        return redirect(url_for('core.index'))

    if (current_user.is_authenticated):
        notifs = Notifications.query.filter_by(
            user_id=current_user.id).order_by(Notifications.date.desc()).all()
    else:
        notifs = []

    return render_template('create_post.html', form=form, notifs=notifs)
    def test_get_view_on_site_url__return_link(self):
        blog_post = BlogPost(slug='test-blog')

        url = self.admin.get_view_on_site_url(blog_post)

        self.assertEqual(url,
                         reverse('blog:post', kwargs={'slug': blog_post.slug}))
 def decorate(self, post_id=None):
     post = None
     if post_id:
         post = BlogPost.get_by_id(int(post_id))
         if not post:
             raise NotFound
     return fun(self, post)
    def generate_resource(cls, post, resource, pagenum=1, start_ts=None):
        from blog.models import BlogPost
        q = BlogPost.all().order('-published')
        q.filter('published <', start_ts or datetime.datetime.max)
        cls._filter_query(resource, q)

        posts = q.fetch(config.posts_per_page + 1)
        more_posts = len(posts) > config.posts_per_page

        path_args = {
            'resource': resource,
        }
        path_args['pagenum'] = pagenum - 1
        prev_page = cls.path % path_args
        path_args['pagenum'] = pagenum + 1
        next_page = cls.path % path_args
        template_vals = {
            'posts': posts[:config.posts_per_page],
            'prev_page': prev_page if pagenum > 1 else None,
            'next_page': next_page if more_posts else None,
            'config': config,
        }
        template_name = "blog/themes/%s/listing.html" % config.theme
        rendered = utils.render_template(template_name, template_vals)
        
        path_args['pagenum'] = pagenum
        StaticContent.set(cls.path % path_args, rendered, config.html_mime_type)

        if pagenum == 1:
            StaticContent.set(cls.first_page_path % path_args, rendered, config.html_mime_type)
        if more_posts:
            deferred.defer(cls.generate_resource, None, resource, pagenum + 1,
                           posts[-2].published)
示例#36
0
def api_create_blog_view(request):

    blog_post = BlogPost(author=request.user)

    if request.method == 'POST':
        try:
            if request.user.customer.membership:
                data = request.data
                data['author'] = request.user.pk
                serializer = BlogPostCreateSerializer(data=data)

                data = {}
                if serializer.is_valid():
                    blog_post = serializer.save()
                    data['response'] = CREATE_SUCCESS
                    data['pk'] = blog_post.pk
                    data['title'] = blog_post.title
                    data['body'] = blog_post.body
                    data['slug'] = blog_post.slug
                    data['date_updated'] = blog_post.date_updated
                    image_url = str(
                        request.build_absolute_uri(blog_post.image.url))
                    if "?" in image_url:
                        image_url = image_url[:image_url.rfind("?")]
                    data['image'] = image_url
                    data['username'] = blog_post.author.username
                    return Response(data=data)
        except Customer.DoesNotExist:
            return Response({'response': "RESPONSE_MUST_BECOME_T2R_MEMBER"})
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#37
0
def test_blog_post_model():
    user = CustomUser(email="*****@*****.**", username="******")
    user.save()
    tag1 = Tag(name="tag1")
    tag1.save()
    tag2 = Tag(name="tag2")
    tag2.save()
    post = BlogPost(author=user, title="Test title!", body="post body")
    post.tags.set([tag1, tag2])
    post.save()
    assert post.author.username == "test"
    assert post.title == "Test title!"
    assert post.slug == "test-title"
    assert post.tags.all()[1] == tag2
    assert post.body == "post body"
    assert str(post) == post.title
示例#38
0
def test_blog_post_model_unique_slugs():
    user = CustomUser(email="*****@*****.**", username="******")
    user.save()
    post1 = BlogPost(author=user, title="Test title!", body="post body")
    post1.save()
    post2 = BlogPost(author=user, title="Test title", body="post body")
    post2.save()
    assert post1.slug == "test-title"
    assert post1.slug != post2.slug
示例#39
0
def heartbeats(request):
    if not request.user.is_authenticated:
        return HttpResponseRedirect('/login')
    if request.method == 'POST':
        is_search = False
        if request.POST.has_key('search'):
            is_search = True
            words = request.POST['search']
            search_title = BlogPost.objects.filter(title__contains=words)
            search_body = BlogPost.objects.filter(body__contains=words)
            posts = search_body | search_title
            posts = list(posts)
            relation_people = []
            for post in posts:
                b = User.objects.get(username=post.author)
                a = Profile.objects.get(user=b)
                relation_people.extend([a])
            posts = zip(posts, relation_people)
            return render(request, 'heartbeats.html', {
                'posts': posts,
                'is_search': is_search,
                'word': words
            })
        if request.POST.has_key('body'):
            bp = BlogPost()
            bp.title = request.POST['title']
            bp.body = request.POST['body']
            bp.author = request.user.username
            bp.timestamp = datetime.now()
            bp.save()
            posts = BlogPost.objects.all()
            posts = list(posts)
            relation_people = []
            for post in posts:
                b = User.objects.get(username=post.author)
                a = Profile.objects.get(user=b)
                relation_people.extend([a])
            posts = zip(posts, relation_people)
            return render(
                request, 'heartbeats.html', {
                    'posts': posts,
                    'is_search': is_search,
                    'relation_people': relation_people
                })
    else:
        posts = BlogPost.objects.all()
        posts = list(posts)
        relation_people = []
        for post in posts:
            b = User.objects.get(username=post.author)
            a = Profile.objects.get(user=b)
            relation_people.extend([a])
        posts = zip(posts, relation_people)
        return render(request, 'heartbeats.html', {
            'posts': posts,
            'relation_people': relation_people
        })
示例#40
0
def post_delete(request, post_id):
    post = BlogPost.get_by_id(int(post_id))
    user = users.get_current_user()
    if request.method == "POST" and post.author == user.email():
        post.key.delete()
        return redirect("home")
    else:
        return redirect("forbidden")
示例#41
0
def post_delete(request, post_id):
	post = BlogPost.get_by_id(int(post_id))
	user = users.get_current_user()
	if request.method == "POST" and post.author == user.email():
		post.key.delete()
		return redirect("home")
	else:
		return redirect("forbidden")
示例#42
0
def user_posts(username):
    page = request.args.get('page', 1, type=int)
    user = User.query.filter_by(username=username).first_or_404()
    blog_posts = BlogPost.query.filter_by(author=user).order_by(
        BlogPost.desc()).paginate(page=page, per_page=5)
    return render_template('user_blog_posts.html',
                           blog_posts=blog_posts,
                           user=user)
示例#43
0
def create_blogpost(request):
    if request.method == 'POST':
        BlogPost(
            title=request.POST.get('title'),
            body=request.POST.get('body'),
            timestamp=datetime.now(),
        ).save()
    return redirect('/blog/')
示例#44
0
def generate_blog_post():
    post = BlogPost()
    post.name = random.choice(long_actions)
    post.content = user_description
    post.date = generate_datetime()
    post.published = True
    post.save()
示例#45
0
def post_add(request):
	if request.method == "GET":
		form = BlogPostForm()
		params = {"form": form}
		return blog_render(request, "post_add.html", params)

	elif request.method == "POST":
		form = BlogPostForm(request.POST)

		if form.is_valid():
			BlogPost.create(title=form.cleaned_data["title"],
			                content=form.cleaned_data["content"],
			                author=users.get_current_user().email())
		else:
			params = {"form": form}
			return blog_render(request, "post_add.html", params)

		return redirect("home")
示例#46
0
 def setUp(self):
     self.client.login(username='******', password='******')
     self.user = ActiveUser.objects.filter(username='******')[0]
     self.post = BlogPost(title='Hello World!',
                     author=self.user,
                     tags='hello world',
                     abstract='Hello World!',
                     text='Hello World!',
                     priority=BlogPost.STATUS_SUBMITTED)
     self.post.save()
示例#47
0
def edit_post(request, blog_name=None, post_key_name=None):
    user = users.get_current_user()
    if not user:
        return HttpResponseForbidden()
    if user.nickname() != blog_name:
        return HttpResponseForbidden()
    post = BlogPost.get_by_key_name(post_key_name,
                                    parent=db.Key.from_path('Blog', blog_name))
    if not post:
        return HttpResponse404()
    return render_to_response('post_form.html', {'post': post},
                              RequestContext(request))
示例#48
0
def post_edit(request, post_id):
	post = BlogPost.get_by_id(int(post_id))
	user = users.get_current_user()
	if request.method == "GET" and post.author == user.email():
		form = BlogPostForm({"title": post.title, "content": post.content})
		params = {"form": form, "post": post}
		return blog_render(request, "post_edit.html", params)
	elif request.method == "POST" and post.author == user.email():
		form = BlogPostForm(request.POST)

		if form.is_valid():
			BlogPost.edit(post_id=int(post_id),
			              title=form.cleaned_data["title"],
			              content=form.cleaned_data["content"])
		else:
			params = {"form": form}
			return blog_render(request, "post_add.html", params)

		return redirect("home")
	else:
		return redirect("forbidden")
示例#49
0
def index(request):
    """Displays the index page."""
    # Fetch all of the BlogPosts
    posts = BlogPost.all().order('-date')

    # Setup the data to pass on to the template
    template_values = {
        'posts': posts,
    }

    # Load and render the template
    return shortcuts.render_to_response('index.html', template_values)
 def generate_resource(cls, post, resource):
     from blog.models import BlogPost
     if not post:
         post = BlogPost.get_by_id(resource)
     else:
         assert resource == post.key().id()
     template_vals = {
         'post': post,
         'config': config,
     }
     template_name = "blog/themes/%s/post.html" % config.theme
     rendered = utils.render_template(template_name, template_vals)
     StaticContent.set(post.path, rendered, config.html_mime_type)
示例#51
0
def view(request, post_uri):
    # Find the requested post
    post = BlogPost.all().filter('uri = ', post_uri).fetch(1)

    # Make sure the requested post exists
    if post == None or len(post) == 0:
        return http.HttpResponseNotFound('No post exists with that uri (%r)' % post_uri)

    # Get the requested post data
    post = post[0]

    # Load and display the view template
    return shortcuts.render_to_response('view.html', {'post': post})
示例#52
0
class PendingTests(TestCase):
    fixtures = ['devel']

    def setUp(self):
        self.client.login(username='******', password='******')
        self.user = ActiveUser.objects.filter(username='******')[0]
        self.post = BlogPost(title='Hello World!',
                        author=self.user,
                        tags='hello world',
                        abstract='Hello World!',
                        text='Hello World!',
                        priority=BlogPost.STATUS_SUBMITTED)
        self.post.save()

    def test_list(self):
        response = self.client.get(reverse('blog_pending_list'))
        self.assertEqual(response.status_code, 200)

    def test_edit(self):
        url = reverse('blog_pending_edit', kwargs={'pk': self.post.pk})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
示例#53
0
    def test_save_and_retrieve_blog_posts(self):
        self.assertEqual(BlogPost.objects.all().count(), 0)
        blog_post = BlogPost()
        blog_post.title = "A post"
        blog_post.date = datetime.datetime(1939, 9, 1, 5, 0, 0)
        blog_post.body = "Blah blah blah"
        blog_post.visible = False
        blog_post.save()
        self.assertEqual(BlogPost.objects.all().count(), 1)

        retrieved_post = BlogPost.objects.first()
        self.assertEqual(retrieved_post, blog_post)
示例#54
0
def insert_post_with_unique_key(post_dict):
    """
    First we try to add the blog post with key name equal to the slug of the
    post's title.
    If this key is already taken we append a random two characters and repeat
    until a free key is generated. The blog post is then saved with this new
    key.

    In all queries we specify the parent as the blog with name the author's
    nickname. This means that all queries run on a single entity group so we
    don't have to use a cross-group transaction. Also this means two users can
    be posting at the same time as the transaction only locks the entity group
    corresponding to the current logged in user.
    """
    key_name_base = unicode(slugify(post_dict['title']))
    key_name = key_name_base
    parent_key = blog_key(post_dict['author'])
    while BlogPost.get_by_key_name(key_name, parent=parent_key):
        key_name = '%s-%s' % (key_name_base, ''.join([random.choice(
            string.ascii_letters + string.digits) for i in range(2)]))
    post = BlogPost(parent=parent_key, key_name=key_name, **post_dict)
    post.put()
    return post
示例#55
0
def delete_post(request, blog_name=None, post_key_name=None):
    user = users.get_current_user()
    if not user:
        return HttpResponseForbidden()
    if user.nickname() != blog_name:
        return HttpResponseForbidden()
    post = BlogPost.get_by_key_name(post_key_name,
                                    parent=db.Key.from_path('Blog', blog_name))
    if not post:
        return HttpResponse404()
    try:
        post.delete()
    except Exception, e:
        return HttpResponseServerError()
示例#56
0
def update_blog_post(title, content, is_published, blog_post_id=None):
    if not blog_post_id:
        p = BlogPost()
    else:
        p = get_blog_post(blog_post_id)
    p.title = title
    p.content = content
    p.is_published = bool(is_published)
    p.put()
    return p
def regenerate(batch_size=50, seen=None, start_ts=None):
    """Regenerate all static content"""
    if not seen:
        seen = set()
    q = BlogPost.all().order('-published')
    q.filter('published <', start_ts or datetime.datetime.max)
    posts = q.fetch(batch_size)
    for post in posts:
        for generator_class, deps in post.get_deps(True):
            for dep in deps:
                if (generator_class.__name__, dep) not in seen:
                    logging.warn((generator_class.__name__, dep))
                    seen.add((generator_class.__name__, dep))
                    deferred.defer(generator_class.generate_resource, None, dep)
    if len(posts) == batch_size:
        deferred.defer(regenerate, batch_size, seen, posts[-1].published)
 def generate_resource(cls, post, resource):
     from blog.models import BlogPost
     q = BlogPost.all().order('-updated')
     posts = list(itertools.islice((x for x in q if x.path), 10))
     for post in posts:
         updated = post.updated
         break
     template_vals = {
         'posts': posts,
         'config': config,
         'updated': updated,
     }
     rendered = utils.render_template("blog/atom.xml", template_vals)
     StaticContent.set('/feeds/atom.xml', rendered,
                       'application/atom+xml; charset=utf-8')
     if config.hubbub_hub_url:
         cls.send_hubbub_ping(config.hubbub_hub_url)
示例#59
0
    def test_wgs84_coords(self):
        """
        latitude is +/- 90  longitude is +- 180
        """
        mapX = BlogSurface.objects.create(title="theWorld")

        m1 = BlogPost(blog_surface=mapX, title="legal marker", lat=89.9, lng=179.9)
        m1.save()

        m2 = BlogPost(blog_surface=mapX, title="illegal marker", lat=99.9, lng=199.9)
        with self.assertRaises(ValidationError):
            m2.save()
def index(request, start=0, count=10):
    offset = start
    more_posts = False 
    posts = BlogPost.all().order('-published').fetch(count+1, offset)
    if len(posts) > count:
        posts = posts[0:count]
        more_posts = True
    template_vals = {
            'offset': offset,
            'count': count,
            'last_post': offset + len(posts) - 1,
            'prev_offset': max(0, offset - count),
            'next_offset': offset + count,
            'posts': posts,
            'more_posts': more_posts,
            'config': config,
            'menu_view': True,
            }
    return render_to_response("blog/admin/index.html", template_vals)