Exemplo n.º 1
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
Exemplo n.º 2
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()
Exemplo n.º 3
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)
Exemplo n.º 4
0
def create(request):
    if request.method == 'POST':
        BlogPost(
            title=request.POST.get('title'),
            body=request.POST.get('body'),
        ).save()
    return HttpResponseRedirect('/blog')
Exemplo n.º 5
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)
Exemplo n.º 6
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()
Exemplo n.º 7
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)
    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}))
Exemplo n.º 9
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")
Exemplo n.º 10
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)
Exemplo n.º 11
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)
Exemplo n.º 12
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()
Exemplo n.º 13
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."})
Exemplo n.º 14
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."
            })
Exemplo n.º 15
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/')
Exemplo n.º 16
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
Exemplo n.º 17
0
def api_create_blog_view(request):
    account = request.user
    blog_post = BlogPost(author=account)
    if request.method == 'POST':
        serializer = BlogPostSerializer(blog_post, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 18
0
def create(reqeust):

    if request.method == 'POST':
        BlogPost(
            title=reqeust.POST['title'],
            body1=reqeust.POST['body'],
            timestamp=datetime.now(),
        ).save()
    return render(reqeust, 'archive.html')
Exemplo n.º 19
0
def create_blogpost(request):
    if request.method == 'POST':
        BlogPost(
            title=request.POST.get('title'),
            author=request.POST.get('author'),
            body=request.POST.get('body'),
            timestamp=datetime.now(),
            ).save()
    return HttpResponseRedirect('/blog/view')
Exemplo n.º 20
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
        })
Exemplo n.º 21
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 HttpResponseRedirect('/blog/')
    return render_to_response('blog/archive.html', {'post': BlogPost},
                              RequestContext(request))
Exemplo n.º 22
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()
Exemplo n.º 23
0
def api_post_blog_view(request, slug):
    account = request.user
    blog_post = BlogPost(author=account)
    if request.method == "POST":
        serializer = BlogPostSerializer(blog_post, data=request.data)
        data = {}
        if (serializer.is_valid()):
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.erros, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 24
0
def api_create_blog_view(request):
    account = Account.objects.get(pk=1)
    blogpost=BlogPost(author=account)
    if request.method == "POST":
        serializer = BlogPostSerializer(blogpost, data=request.data)
        data={}
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 25
0
 def test_unique_slug(self):
     """
     two post with identical titles should different slugs
     """
     repeated_title = self.post.title
     post2 = BlogPost()
     post2.title = repeated_title
     post2.writer = self.user2
     post2.text = "another random text"
     post2.save()
     self.assertNotEqual(self.post.slug, post2.slug)
Exemplo n.º 26
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')
Exemplo n.º 27
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
Exemplo n.º 28
0
def api_blog_create_view(request):
    account = Account.objects.get(pk=1)#query about a random user
    print(account)
    blog_post = BlogPost(author=account)#pass the author to BlogPost since it is a required field

    if request.method =='POST':
        serializer = BlogPostSerializer(blog_post,data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 29
0
 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()
Exemplo n.º 30
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)