Beispiel #1
0
 def setUp(self):
     super(LikeTests, self).setUp()
     user = User.objects.create_user('test', '*****@*****.**', '12345678OK')
     self.current_user = user
     self.client.force_login(user=user)
     self.post = Post(title='test', text='test', author=self.current_user)
     self.post.save()
Beispiel #2
0
 def marry_multi_language_posts(self, new_post: Post, post_to_be_translated):
     if post_to_be_translated:
         language_group = self.get_language_group(post_to_be_translated)
         new_post.language_group = language_group
         new_post.save()
         post_to_be_translated.language_group = language_group
         post_to_be_translated.save()
Beispiel #3
0
    def post(self, request, slug):

        board = get_object_or_404(Board, slug=slug)

        new_thread = Thread(
            title=request.POST['thread_title'],
            board=board
        )

        new_thread.save()

        initial_post = Post(
            image=request.FILES['image'],
            body=request.POST['body'],
            parent_thread=Thread.objects.get(id=new_thread.id)
        )

        initial_post.save()

        return HttpResponseRedirect(
            reverse(
                'thread:single_thread',
                kwargs={
                    'id': Thread.objects.get(id=new_thread.id).id
                }
            )
        )
Beispiel #4
0
    def create(self, validated_data):

        request = self.context['request']
        p = Post(**validated_data)
        for file in request.FILES.getlist('file'):
            f = Files.objects.create(file_user=p, file=file)

        title = self.context['request'].data.get('title')
        description = self.context['request'].data.get('description')
        password = ''
        token = ''
        uname = request.data.get('username')
        uemail = request.data.get('email')
        if uname:
            password = randomstring(stringLength=5)
            token = randomstring(stringLength=10)
            u = User.objects.create(username=uname, email=uemail)
            u.set_password(password)
            pro = Profile.objects.create(user=u)
            pro.activation_token = token
            pro.save()
            u.save()
            p.poster = u
            p.save()
        body = 'Title:' + title + '\n' + 'Description:' + description + '\n' + 'username:'******'\npassword:'******'\nActivation url:http://127.0.0.1:8000/user/activate/' + str(
            token)
        msg = EmailMessage(title, body, settings.EMAIL_HOST_USER,
                           ['*****@*****.**'])
        msg.send()
        print(request.data)
        return p
def _get_github_events(author):
    """Retrieves all the public events for the given GitHub author.

    Events are retrieved from GitHub's API at
    https://api.github.com/users/<user>/events

    GitHub has a rate limit of 60. In order to not exhaust the limit as
    quickly, the events are cached. A GitHub E-tag is also stored, and used
    in the header of the request so that GitHub will not count the request
    towards the rate limit if events are unchanged.
    """
    headers = {'Connection': 'close'}

    if len(author.github_etag) > 0:
        headers['If-None-Match'] = author.github_etag

    url = 'https://api.github.com/users/%s/events' % author.github_user

    response = requests.get(url, headers=headers)

    # print response

    # We didn't get a response or we've reached our GitHub limit of 60.
    if not response or int(response.headers["X-RateLimit-Remaining"]) == 0:
        return []

    if response.status_code == 200:
        # Store the etag for future use
        author.github_etag = response.headers['ETag']
        author.save()

        events = []

        for event in response.json():
            content = _build_github_event_text(event, author)
            if content is not None:
                # Construct the GitHub event post
                post = Post(content=content,
                            content_type=Post.PLAIN_TEXT,
                            visibility=Post.PRIVATE,
                            author=author,
                            publication_date=dateutil.parser.parse(event['created_at']))
                events.append(post.getJsonObj())

        # Cache these results in the event that we've reached our rate
        # limit, or we get a 304 because the events haven't changed.
        cache.set(author.user.id, events, None)
        return events
    elif response.status_code == 304:
        # Results haven't changed, let's just return the cache, if one exists,
        # otherwise, we need to get it again.
        cached = cache.get(author.user.id)
        if cached is None:
            author.github_etag = ''
            return _get_github_events(author)
        else:
            return cached
    else:
        # print 'ERROR: API at %s returned %d' % url, response.status_code
        return []
Beispiel #6
0
 def test_was_published_recently_with_old_post(self):
     """
     was_published_recently() should return False for polls whose pub_date
     is older than 1 day
     """
     old_post = Post(pub_date=timezone.now() - datetime.timedelta(days=30))
     self.assertEqual(old_post.was_published_recently(), False)
Beispiel #7
0
def post(request,data):
	email = User.objects.get(mainuser=request.user).email
	newPost = Post(data=data, owner=User.objects.get(email=email), push_sent=False, network=User.objects.get(mainuser=request.user).network)
	newPost.save()
	tags = data.split(" ")
	thread.start_new_thread(collect_push, (email, tags, data, newPost))
	return HttpResponse(email+" " + " ".join(tags))
Beispiel #8
0
 def test_was_published_recently_with_future_post(self):
     """
     was_published_recently() should return False for post whose
     pub_date is in the future
     """
     future_post = Post(pub_date=timezone.now() + datetime.timedelta(days=30))
     self.assertEqual(future_post.was_published_recently(), False)
Beispiel #9
0
 def test_was_published_recently_with_recent_post(self):
     """
     was_published_recently() should return True for polls whose pub_date
     is within the last day
     """
     recent_post = Post(pub_date=timezone.now() - datetime.timedelta(hours=1))
     self.assertEqual(recent_post.was_published_recently(), True)
Beispiel #10
0
class PostDetailViewTest(TestCase):
    _multiprocess_can_split_ = True

    def setUp(self):
        faker = Faker()
        author = create_user()
        self.post = Post(
            author=author, body=faker.paragraphs(),
            title=faker.words().capitalize())
        self.post.save()

    def test_post_detail_render(self):
        response = self.client.get(
            reverse(POST_DETAIL_URL, args=(self.post.slug, )))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, self.post.title)
        for paragraph in self.post.body.split('\n\n'):
            self.assertContains(response, paragraph)

    def test_draft_post_returns_404(self):
        self.post.is_draft = True
        self.post.save()
        response = self.client.get(
            reverse(POST_DETAIL_URL, args=(self.post.slug, )))
        self.assertEqual(response.status_code, 404)
 def post(self, request, *args, **kwargs):
     data = request.data
     usertags = []
     hashtags = []
     for usertag_pk in data.get('usertags'):
         try:
             usertag = get_user_model().objects.get(pk=usertag_pk)
         except get_user_model().DoesNotExist:
             usertag = None
         if usertag is not None:
             usertags.append(usertag)
     for hashtag_pk in data.get('hashtags'):
         try:
             hashtag = get_user_model().objects.get(pk=hashtag_pk)
         except get_user_model().DoesNotExist:
             hashtag = None
         if hashtag is not None:
             hashtags.append(hashtag)
     try:
         author = get_user_model().objects.get(pk=data.get('author'))
     except get_user_model().DoesNotExist:
         author = None
     if author is not None:
         post = Post(
             author=author,
             image=request.FILES["image"],
             caption=data.get('caption'),
             location=data.get('location'),
             usertags=usertags,
             hashtags=hashtags,
         )
         post.save()
         return Response(status=status.HTTP_201_CREATED)
     return Response(status=status.HTTP_404_NOT_FOUND,
                     data={"error": "Invalid pk values"})
Beispiel #12
0
	def insert_post(cls):
		author = MotssUser.objects.all()[1]
		thread = Thread.objects.all()[0]
		post = Post(thread=thread, author=author, authorip='127.0.0.1', \
			message='test insert post', position=thread.maxposition)
		post.save()
		return post
def index(request):
    """发帖的界面"""
    if request.method == "POST":  # 如果请求方式为POST, 则为提交内容
        topic = request.POST.get("topic")  # 主题
        course = request.POST.get("course")
        content = request.POST.get("content")  # 内容

        if topic and course and content:
            post = Post(topic=topic, course=course, counter=0, author_user_id=request.user.id, content=content)  # 数据库插入
            post.save()
            request.session["status"] = "提交成功"
            request.session["id"] = post.id
            return JsonResponse({"status": "提交成功", "code": 200})
        else:
            if not topic:
                return JsonResponse({"status": "标题不能为空", "code": 400})
            elif not course:
                return JsonResponse({'status': '请选择对应的课程', "code": 400})
            else:
                return JsonResponse({"status": "请输入内容", "code": 400})

    course = Course.objects.all()
    data = []
    for c in course:
        data.append(c.name)
    status = None
    id = None
    if request.session.get("status") and request.session.get("id"):
        status = request.session.pop("status")
        id = request.session.pop("id")

    return render(request, "post/index.html", context={"data": data, "msg": status, "id": id})
Beispiel #14
0
 def _create_post_name_text(self, user):
     text = 'text'
     name = 'name'
     post = Post(text=text,
                 name=name,
                 author=user)
     post.save()
     return post, name, text
Beispiel #15
0
def post(request):
    if request.method == 'POST':
        caption = request.POST.get('caption')
        url = request.POST.get('url')
        desc = request.POST.get('desc')
        ins = Post(caption=caption, url=url, desc=desc)
        ins.save()
    return render(request, 'post.html')
Beispiel #16
0
def fake_post(num=500):
    for i in range(num):
        user = User.objects.order_by('?').first()
        ask = Post(title=faker.sentence()[:40],
                   content=faker.paragraph(),
                   user=user)
        ask.save()
        print('create post: {}:{}'.format(user.username, ask))
Beispiel #17
0
 def test_drafts_are_not_displayed(self):
     faker = Faker()
     post = Post(
         author=create_user(), body=faker.paragraphs(),
         title=faker.words().capitalize(), is_draft=True)
     post.save()
     PostListView.paginate_by = self.post_count + 1
     response = self.client.get(reverse(POST_LIST_URL))
     self.assertEqual(len(response.context['object_list']), self.post_count)
Beispiel #18
0
 def post(self, request, pk1, pk2):
     profile = self.get_profile(pk1)
     post = self.get_post(pk2)
     new_post = Post(image=post.image,
                     owner=profile,
                     repost=post.owner,
                     text=post.text)
     new_post.save()
     return Response({}, status=status.HTTP_201_CREATED)
Beispiel #19
0
def get_post_info(driver):
    #SCROLL_PAUSE_TIME = 1
    #
    # # Get scroll height
    # last_height = driver.execute_script("return document.body.scrollHeight")
    # while True:
    #     # Scroll down to bottom
    #     driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    #     # Wait to load page
    #     time.sleep(SCROLL_PAUSE_TIME)
    #     # Calculate new scroll height and compare with last scroll height
    #     new_height = driver.execute_script("return document.body.scrollHeight")
    #     if new_height == last_height:
    #         break
    #     last_height = new_height
    html = driver.page_source
    soup = BeautifulSoup(html, 'html.parser')
    writeSubject = soup.find('h1',{'class' : 'tNGpbb uTUgB YVvGBb'}).getText()    
    div = soup.findAll('div', {'class' : 'n4xnA'})

    for post in div:
        temp = post.findAll('span',{'class' : 'PazDv'})
        title= temp[0].getText()        
        write_date = temp[1].getText()

        if(("오전" in write_date) or ("오후" in write_date)):
            try:
                writer = post.find('span',{'class' : 'YVvGBb asQXV'}).getText()
                content = post.find('div',{'class' : 'pco8Kc obylVb'}).getText("\n")
                
                if(Post.objects.filter(postDate = write_date, postContent = content)):
                    return
                else:
                    Post(
                        postWriter = writer,
                        postTitle = title,
                        postDate = write_date,
                        postContent = content,
                        postUrl = driver.current_url,
                        postSubject = writeSubject
                    ).save()
            except:
                content = post.find('div', {'class' : 'JZicYb QRiHXd'}).getText("\n")
                if(Post.objects.filter(postDate = write_date, postContent = content)):
                    return
                else:
                    Post(
                        postWriter = writer,
                        postTitle = title,
                        postDate = write_date,
                        postContent = content,
                        postUrl = driver.current_url,
                        postSubject = writeSubject
                    ).save()
        else:
            pass
    return
Beispiel #20
0
 def setUp(self):
     self.post_count = 2
     PostListView.paginate_by = 1
     faker = Faker()
     author = create_user()
     for i in xrange(self.post_count):
         post = Post(
             author=author, body=faker.paragraphs(),
             title=faker.words().capitalize())
         post.save()
Beispiel #21
0
def pub(request):
    try:
        payload = simplejson.loads(request.body)

        post = Post()
        content = Content()
        content.content = payload['content']
        post.title = payload['title']
        post.author = request.user
        post.content = content

        try:
            content.save()
            post.save()


        except Exception as e:
            print(e)
            return HttpResponse("pub content save error")

        try:
            post.save()
            return JsonResponse({
                'post_id': post.id,
                'title': post.title,
                'author': post.author.name,
                'content': post.content.content
            })
        except Exception as e:
            print(e)
            return HttpResponse("pub content save error")
    except Exception as e:
        print(e)
        return HttpResponse("pub content save error")
Beispiel #22
0
def upload():

    if 'username' in session:
        form = UploadForm()
        if request.method == 'POST':
            if form.validate_on_submit():
                # create new record
                new_post = Post()
                new_post.poster = User.objects.get(
                    username=session['username']).id
                new_post.title = form.title.data
                new_post.tags = [x for x in form.tags.data]

                if form.link.data:
                    new_post.link = form.link.data

                if request.files.get('meme'):
                    filename = secure_filename(form.meme.data.filename)
                    hashed_fname = sha256(filename.encode('utf-8')).hexdigest()
                    file_path = os.path.join('upload_folder', hashed_fname)
                    form.meme.data.save(file_path)
                    new_post.image = hashed_fname

                new_post.save()

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

        return render_template('post/upload.html', form=form)
    else:
        return abort(403)
Beispiel #23
0
    def put(self, request, user, *args, **kwargs):
        try:
            body = self.process_body(request, ['text', 'name', ])
        except Exception as error:
            return self.respond_error_json(error)

        post = Post(text=body['text'],
                    name=body['name'],
                    author=user,
                    status=Post.ACTIVE)
        post.save()
        return self.respond_success_json({'post': post.serialize()})
Beispiel #24
0
 def post(self, request, *args, **kwargs):
     print(request.data)
     post = Post(user=User.objects.get(id=1), model=request.data['model'])
     post.save()
     tweets = twitterpy.getTweets(subject=request.data['model'])
     for co, i in enumerate(tweets):
         # nlp.analyze(i)
         Tweet(post=post, tweet=i).setToUniqo(co).save()
         print('*' * 30)
         print('*' * 30)
     print(post.tweets)
     return self.create(request, *args, **kwargs)
Beispiel #25
0
 def post(self, request):
     post_with_owner = Post()
     self.check_permissions(request)  # compruebo si el usuario autenticado puede hacer POST
     blog = Blog.objects.filter(owner=request.user).all()
     post_with_owner.blog = blog[0]
     post_with_owner.owner = request.user  # asigno como propietario de la foto, el usuario autenticado
     post_with_owner.visibility = POSTED
     serializer = PostCreateSerializer(instance=post_with_owner, data=request.data)
     if serializer.is_valid():
         serializer.save()  # Guarda el objeto Photo y me lo devuelve
         return Response(serializer.data, status=status.HTTP_200_OK)
     else:
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #26
0
def submit_post(request):  # 글쓰기 인서트.
    post = Post(
        img1=request.POST["img1"],
        img2=request.POST["img2"],
        img3=request.POST["img3"],
        content=request.POST["content"],
        user_id=User.objects.filter(user_id=request.session["id"]).get())  # 세션에 담겨있는 유저아이디로 저장.
    post.save()  # 포스트테이블 부분 서버로 저장완료.
    tags = split_tags(request.POST["tag"])  # 태그부분에 담긴 글을 split_tag 함수를 통해 쪼갠 후 tags 변수 안에 담기.
    for tag in tags:
        dto = PostTag(word=tag, post_id=post)
        dto.save()  # 포스트태그_테이블로 단어와, 포스트id를 반복적으로 디비저장처리.
    return redirect("home")  # 메인 페이지 보내기.
Beispiel #27
0
 def post(self, request):
     form = FazerPostForm(request.POST)
     if form.is_valid():
         logado = get_perfil_logado(request)
         dados_form = form.cleaned_data
         texto = '' + dados_form['post']
         post = Post(conteudo=texto,
                     autor=logado,
                     amei=0,
                     odiei=0,
                     triste=0,
                     legal=0)
         post.save()
     return redirect('pagina-inicial')
Beispiel #28
0
 def test_save_existing_model_by_different_user(self):
     author = create_user()
     faker = Faker()
     post = Post(
         author=author,
         title=faker.words().capitalize(),
         body=faker.paragraphs())
     post.save()
     form = self.postadmin.get_form(post)
     user = create_user()
     request = HttpRequest()
     request.user = user
     self.postadmin.save_model(request, post, form, False)
     self.assertNotEqual(post.author, user)
     self.assertGreater(post.modified_at, post.created_at)
Beispiel #29
0
def new_post(request):
    if request.method == 'POST':
        form = NewPostForm(request.POST)
        if form.is_valid():
            body = form.cleaned_data['body']
            is_anonymous = form.cleaned_data['is_anonymous']
            post = Post(body=body,
                        user=request.user,
                        is_anonymous=is_anonymous)
            post.save()
            return redirect('/account/' + request.user.username)

    else:
        form = NewPostForm()
    return render(request, 'account/_new_post.html', {'form': form})
Beispiel #30
0
def post_create(request):
    form = PostForm()
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            new_post = Post(
                title=data['title'],
                content=data['content'],
            )
            new_post.save()
            return redirect('/')
    context = {'form': form}

    return render(request, 'post/post_create.html', context)
Beispiel #31
0
 def GET(self, post_url=None):
     try:
         import hashlib
         post_id = post_url
         post = Post.get_by_id(int(post_id))
         if not post:
             raise web.notfound()
     
         fullpath = web.ctx.home + web.ctx.fullpath
         check = "%s%s" % (fullpath, post.key())
         checksum = hashlib.sha1(check).hexdigest()
     
         comments_query = Comment.all().filter('post =', post)
         if blog.comment_sort == 'asc':
             comments_query.order('created')
         else:
             comments_query.order('-created')
     
         comments = comments_query.fetch(blog.comment_pagesize)
     
         return render('theme/show.html',
                       post=post,
                       checksum=checksum,
                       comments=comments)
     except:
         raise web.notfound()
Beispiel #32
0
 def handle(self, *args, **options):
     post_cnt = options['post_cnt']
     if post_cnt > 0:
         Post.objects.bulk_create(
             [Post(text="Sample Text #{}".format(i)) for i in range(post_cnt)]
         )
         self.stdout.write(self.style.SUCCESS('Successfully add {} posts'.format(post_cnt)))
Beispiel #33
0
 def GET(self):
     from util.feedgenerator import Atom1Feed
     
     blog = Blog.get()
     blog_home = web.ctx.home
     feed = Atom1Feed(
         title=blog.name,
         link=blog_home,
         description=blog.description,
     )
     posts = Post.all().filter('hidden =', False).order('-date').fetch(10)
     for post in posts:
         if post.category:
             category = (post.category.name,)
         else:
             category = ()
         if post.tags:
             category = category + tuple(post.tags)
         feed.add_item(title=post.title,
                       link=blog_home + post.getUrl(),
                       description=post.content,
                       pubdate=post.date,
                       categories=category
                       )
     web.header('Content-Type', 'application/atom+xml')
     return feed.writeString('utf-8')
Beispiel #34
0
def post_view(request, post_slug, post_id):
    post = Post.get(post_id)
    if not post:
        raise Http404('The post could not be found')

    if post.status != 'PUBLISHED' and post.user_id != request.user.id \
            or post.slug != post_slug:
        raise Http404('The post could not be found.')

    comments = Comment.get_comments(post)
    if post.status != 'DRAFT':
        comment_form = request.user.is_authenticated() and\
            AuthorizedCommentForm or AnonymousCommentForm
        comment_form = comment_form(
            initial={
                'root_ctype_id': ContentType.objects.get_for_model(Post).id,
                'root_object_id': post.id,
                'next_page': reverse('post', args=[post.slug, post.id])
            })
    else:
        comment_form = None
    return render(request, 'post/view.html', {
        'post': post,
        'comments': comments,
        'comment_form': comment_form
    })
Beispiel #35
0
    def setUp(self):
        CustomUser(id=1,
                   first_name='Bohdan',
                   last_name='Dubas',
                   phone='123456789',
                   email='*****@*****.**',
                   is_active=False).save()

        self.user = CustomUser.objects.get(id=1)

        Blog(id=22,
             name='TestName',
             description='TestDescription',
             author=self.user).save()

        self.blog = Blog.objects.get(id=22)

        Post(id=333,
             title='TestPost',
             content='Just testing post',
             author=self.user,
             blog=self.blog).save()

        self.post = Post.objects.get(id=333)

        Comment(id=4444,
                author=self.user,
                post=self.post,
                content='Great post!',
                created_at=TEST_DATE).save()

        self.comment = Comment.objects.get(id=4444)
    def test_edit_post(self):
        post = Post(
            title='test_title',
            text='test_text',
            author=self.test_user
        )
        post.save()
        self.assertEquals(Post.objects.count(), 1)

        url = "/api/v1/posts/" + str(int(post.id)) + "/"
        data = {
            'title': 'new_test_title',
            'text': 'new_test_text'
        }
        response = self.client.put(url, data, format='json')
        self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED)
Beispiel #37
0
def category(request, category_id):
    '''
    GET: Displays all posts visible to the user which fall under the supplied
         category ID.
    '''
    if not request.user.is_authenticated():
        return redirect('/login/')

    author = Author.objects.get(user=request.user)
    allAllowedPosts = Post.getAllowedPosts(author)

    try:
        category = Category.objects.get(id=int(category_id))
        postIds = PostCategory.objects.filter(post__in=allAllowedPosts,
                        category=category).values_list('post', flat=True)
        postsWithCategory = Post.objects.filter(id__in=postIds)
    except DoesNotExist:
        redirect('author.views.stream')

    if 'application/json' in request.META['HTTP_ACCEPT']:
        return HttpResponse(json.dumps([post.as_dict()
                                        for post in postsWithCategory]),
                            content_type='application/json')
    else:
        return HttpResponse(["%s\n" % obj.content
                                for obj in postsWithCategory],
                            content_type='text/plain')
Beispiel #38
0
def new_post(request):
    if request.method == 'POST':
        form = PostForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            obj = Post(author=request.user,
                       timestamp=timezone.now(),
                       description=form.cleaned_data.get('description'),
                       image=form.cleaned_data.get('image'))
            obj.save()

            return redirect('/post/%d/' % obj.id)

    context = dict()
    context['form'] = PostForm()

    return render(request, 'post_new.html', context)
Beispiel #39
0
 def setUp(self):
     faker = Faker()
     author = create_user()
     self.post = Post(
         author=author, body=faker.paragraphs(),
         title=faker.words().capitalize())
     self.post.save()
Beispiel #40
0
def new_discussion(request):
    if request.method == "POST":
        current_user = get_current_user(request=request)
        #Create post
        new_post = Post()
        new_post.autor = current_user
        new_post.text = request.POST["post_text"]
        new_post.save()
        #Create discussion
        new_discussion = Discussion()
        new_discussion.theme = request.POST["discussion_theme"]
        new_discussion.bodyText = new_post
        new_discussion.master = current_user
        new_discussion.save()
        return redirect("/all_discussion")
    return render(request, "new_discussion.html", {"current_user": get_current_user(request=request)})
Beispiel #41
0
def send_top_five_medical_cases_weekly(request):
    weekly_five_medical_cases = MedicalCase.weekly_top_five_medical_case()
    subject_medical_case = MedicalCase.objects.last()
    weekly_top_five_discussions = Post.weekly_top_five_discussions()
    registered_doctors = Doctor.objects.all()
    for registered_doctor in registered_doctors:
        context = Context({
            'weekly_five_medical_cases': weekly_five_medical_cases,
            'weekly_top_five_discussions': weekly_top_five_discussions,
            'doctor': registered_doctor,
            'domain': home,
        })
        MedicalCase.send_medical_cases(subject_medical_case,context, registered_doctor)
        # registered_doctors_mailing_list.append(registered_doctor.user.email) ## might need to accesss name of the docs

        # current_site = get_current_site(request)
        # subject = subject_medical_case.title
        # message = render_to_string('medicalcase/medical_case_email_update.html', {
        #     'weekly_five_medical_cases': weekly_five_medical_cases,
        #     'weekly_top_five_discussions': weekly_top_five_discussions,
        #     'doctor': registered_doctor,
        #     'domain': current_site.domain,
        #
        # })
        # to_email1 = registered_doctor.user.email
        # email = EmailMessage(subject, message, to=[to_email1])
        # email.content_subtype = "html"
        # email.send()

    return HttpResponse("Successfully sent")
    def test_delete_post(self):
        post = Post(
            title='test_title',
            text='test_text',
            author=self.current_user
        )
        post.save()
        self.assertEquals(Post.objects.count(), 1)

        url = "/api/v1/posts/" + str(int(post.id)) + "/"
        data = {
            'id': post.id
        }
        response = self.client.delete(url, data, format='json')
        self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEquals(Post.objects.count(), 0)
def post_save(request):
    if request.POST.has_key('post_dog'):
        post_dog = request.POST['post_dog']
        date = request.POST['post_date']
        post_body = request.POST['post_body']
        p = Post(dog = post_dog, post_date = date, body = post_body)
        p.save()

        post_list = Post.objects.order_by('-post_date')[:10]
        context = RequestContext(request, {
            'post_list': post_list
        })
        return render(request, 'post/index.html', context)

    else:
        return
Beispiel #44
0
def post_update(request): #나의 글 업데이트.
    id = request.POST.get("pid")
    dto = Post(id=id,
               img1=request.POST["img1"],
               img2=request.POST["img2"],
               img3=request.POST["img3"],
               content=request.POST["content"],
               user_id=User.objects.filter(user_id=request.session["id"]).get(),
               time=timezone.now()) # 글을 수정받고, 시간을 새로운 시간으로 갱신.
    dto.save()
    PostTag.objects.filter(post_id=id).delete() #기존의 태그데이터를 삭제하고.
    tags = split_tags(request.POST["tag"])  #새로운 태그를 받아 split_tags 함수로 정리 후,
    for tag in tags:                                #반복문을 통해 태그테이블로 세이브처리.
        id = request.POST.get("pid")
        tag = PostTag(word=tag, post_id=dto)
        tag.save()
    return redirect("mypage")  # 메인 페이지 보내기.
Beispiel #45
0
 def GET(self, post_id):
     if post_id:
         post = Post.get_by_id(int(post_id))
         post.delete()
         
         clear_cache()
     
     raise web.seeother('/admin/posts')
Beispiel #46
0
def pub(request: HttpRequest):
    try:
        payload = simplejson.loads(request.body)

        title = payload['title']
        c = payload['content']

        post = Post()
        post.title = title
        post.postdate = datetime.datetime.now(
            datetime.timezone(datetime.timedelta(hours=8)))
        post.auther = User(
            pk=request.user.id
        )  # request.user    # User(request.user.id) # User(pk=request.user.id)

        post.save()

        content = Content()
        content.post = post
        content.content = c

        content.save()
        return JsonResponse({'post_id': post.id})
    except Exception as e:
        print(e)
        return HttpResponseBadRequest()
Beispiel #47
0
def post(req):
    if req.method == 'POST':
        form = PostForm(req.POST)
        if form.is_valid():
            formData = form.cleaned_data
            articles = Post(
                author =  User.objects.get(username=req.user.username),
                title = formData['title'],
                category = Category.objects.get(name=formData['category']),
                content = formData['content']
            )
            articles.save()

        return HttpResponseRedirect('/')

    else:
        form = PostForm()

    return render(req, 'write.html', {'form': form})
Beispiel #48
0
	def create_thread(self, author, subject, message, readperm=1, attaches=[], tags=None):
		subject = escape(subject)
		xss = XssParser()
		xss.feed(message)
		message = xss.result
		at_users = xss.at_users
		print at_users
		hasAttach = (len(attaches)>0)
		post = Post(author=author, authorip=author.loginip, \
			subject=subject, message=message, position=0, hasattach=hasAttach, \
			readperm=readperm)
		thread = Thread(author=author, subject=subject, abstract="abstract", \
			hasattach=hasAttach, tags=tags)
		try :
			thread.save()
			post.thread = thread
			post.save()
		except Exception, e:
			raise PostException(cause=e)
Beispiel #49
0
def create_group_discussion(request, group_id):
    current_user = get_current_user(request=request)
    current_group = Group.objects.get(id=group_id)
    if request.method == "POST":
        #Create post
        new_post = Post()
        new_post.autor = current_user
        new_post.text = request.POST["post_text"]
        new_post.save()
        #Create discussion
        new_discussion = Discussion()
        new_discussion.theme = request.POST["discussion_theme"]
        new_discussion.bodyText = new_post
        new_discussion.master = current_user
        new_discussion.save()
        #Add discussion to group
        current_group.discussionList.add(new_discussion)
        current_group.save()
        urlForRedirect = "/show_group_id=%s" % group_id
        return redirect(urlForRedirect)
Beispiel #50
0
	def reply_thread(self, author, tid, subject, message, readperm=1, attaches=[]):
		subject = escape(subject)
		xss = XssParser()
		xss.feed(message)
		message = xss.result
		at_users = xss.at_users
		print at_users
		hasAttach = (len(attaches)>0)
		qt = Thread.objects.filter(tid=tid)
		if not qt.exists():
			raise NoSuchThreadException(tid=tid)
		thread = qt.get()
		position = thread.maxposition
		try:
			thread.replied_by(author)
			post = Post(thread=thread, author=author, authorip=author.loginip, subject=subject, \
				message=message, position=position, hasattach=hasAttach, readperm=readperm)
			post.save()
		except Exception, e:
			raise PostException(cause=e)
Beispiel #51
0
def getAuthorPosts(request, author_id):
    """
    Retrieves all posts made by the author specified and that are visible
    to currently authenticated user

    """
    if 'application/json' in request.META['HTTP_ACCEPT']:
        return getAuthorPostsAsJSON(request, author_id)
    elif 'text/html' in request.META['HTTP_ACCEPT']:
        context = RequestContext(request)

        if not request.user.is_authenticated():
           return render_to_response('login/index.html', context)

        viewer = Author.objects.get(user=request.user)
        author = Author.objects.get(guid=author_id)

        postIds = AuthorPost.objects.filter(author=author).values_list(
                    'post', flat=True)

        posts = Post.getViewablePosts(viewer, author)
        comments = []
        categories = []
        visibilityExceptions = []
        images = []

        for post in posts:
            categoryIds = PostCategory.objects.filter(post = post).values_list(
                            'category', flat=True)
            visExceptions = PostVisibilityException.objects.filter(
                            post=post)
            authorIds = [e.author.guid for e in visExceptions]
            imageIds = ImagePost.objects.filter(post=post).values_list(
                            'image', flat=True)

            comments.append(Comment.objects.filter(post_ref=post))
            categories.append(Category.objects.filter(id__in=categoryIds))
            visibilityExceptions.append(Author.objects.filter(
                                            guid__in=authorIds))
            images.append(Image.objects.filter(id__in=imageIds))

            # Convert Markdown into HTML for web browser
            # django.contrib.markup is deprecated in 1.6, so, workaround
            if post.contentType == post.MARKDOWN:
                post.content = markdown.markdown(post.content)

        context["posts"] = zip(posts, comments, categories, visibilityExceptions,
                               images)
        context["author_id"] = author.guid

        return render_to_response('post/posts.html', context)
    else:
        return getAuthorPostsAsJSON(request, author_id)
Beispiel #52
0
class PostAdminViewTest(TestCase):
    _multiprocess_can_split_ = True

    def setUp(self):
        faker = Faker()
        author = create_user()
        self.post = Post(
            author=author, body=faker.paragraphs(),
            title=faker.words().capitalize())
        self.post.save()

    @create_admin_user_and_login
    def test_post_edit_render(self):
        response = self.client.get(
            reverse(POST_EDIT_URL, args=(self.post.pk, )))
        self.assertEqual(response.status_code, 200)

    @create_admin_user_and_login
    def test_post_add_render(self):
        response = self.client.get(reverse(POST_ADD_URL))
        self.assertEqual(response.status_code, 200)
Beispiel #53
0
 def post(self, request):
     """
     Crea un post en base a la información POST
     :param request: HttpRequest
     :return: HttpResponse
     """
     success_message = ""
     post_with_owner = Post()
     blog = self.get_blogs_queryset(request.user.username).all()
     post_with_owner.blog = blog[0]
     post_with_owner.owner = request.user  # asigno como propietario de la foto, el usuario autenticado
     form = PostForm(request.POST, instance=post_with_owner)
     if form.is_valid():
         new_post = form.save()  # Guarda el objeto Photo y me lo devuelve
         form = PostForm()
         success_message = "Guardado con éxito!"
         success_message += '<a href="{0}">'.format(
             reverse("post_detail", args=[new_post.blog.owner.username, new_post.pk])
         )
         success_message += "Ver post"
         success_message += "</a>"
     context = {"form": form, "success_message": success_message}
     return render(request, "post/new_post.html", context)
Beispiel #54
0
 def GET(self, post_id=None):
     post = {}
     if post_id:
         # post = Post.get(db.Key.from_path(Post.kind(), int(post_id)))
         post = Post.get_by_id(int(post_id))
         title = u'修改日志'
     else:
         title = u'写新日志'
         post['date'] = datetime.now()
     
     categories = Category.all().order('sort')
     
     return render('admin/post.html',
                   post=post,
                   title=title,
                   categories=categories)
Beispiel #55
0
def add_answer(request, post_parent):
    current_user = get_current_user(request=request)
    sub_main_post = Post.objects.get(pk=post_parent)
    main_post = sub_main_post.mainPost
    if request.method == "POST":
        #Create post
        new_post = Post()
        new_post.autor = current_user
        new_post.text = request.POST["comment_text"]
        new_post.mainPost = main_post
        new_post.subMainPost = sub_main_post
        new_post.save()
        #Post has been created
        urlForRedirect = "/show_discussion_id=%s" % main_post.id
        return redirect("/all_discussion")
Beispiel #56
0
 def body(self):
     content = memcache.get('widget_post_list')
     if not content:
         post_list = Post.all().filter('hidden =',False)\
                         .order('-date').fetch(10)
     
         content = []
         write = content.append
         write('<ul>')
         for post in post_list:
             write('<li><a href="%s">%s</a></li>' %
                         (post.getUrl(), post.title))
         write('</ul>')
         content = '\n'.join(content)
         memcache.set('widget_post_list', content)
     
     return content
Beispiel #57
0
def profile(request, author_id):
    """
    GET: Returns the profile page / information of an author.
    """
    if 'text/html' not in request.META['HTTP_ACCEPT']:
        try:
            author = Author.objects.get(guid=author_id)
        except ObjectDoesNotExist:
            return HttpResponse(json.dumps({"message": "User not found", "status": 404}),
                                status=404, content_type="application/json")

        return HttpResponse(json.dumps(author.as_dict()),
                            content_type="application/json")
    else:
        if request.user.is_authenticated():
            viewer = Author.objects.get(user=request.user)
            try:
                author = Author.objects.get(guid=author_id)
            except Author.DoesNotExist:
                context = RequestContext(request)
                context['author_id'] = viewer.guid
                context['doge'] = doges[random.randint(0,6)]
                if not getRemoteAuthorProfile(context, author_id):
                     # Error conncecting with remote server
                    return render_to_response('error/doge_error.html', context)
                return render_to_response('author/remote_profile.html', context)

            user = author.user
            payload = { } # This is what we send in the RequestContext
            payload['author_id'] = viewer.guid
            payload['firstName'] = user.first_name or ""
            payload['lastName'] = user.last_name or ""
            payload['username'] = user.username
            payload['githubUsername'] = author.githubUsername or ""
            payload['host'] = author.host or ""
            payload['url'] = author.url or request.build_absolute_uri(author.get_absolute_url())
            payload['userIsAuthor'] = (user.username == request.user.username)
            context = RequestContext(request, payload)
            viewer = Author.objects.get(user=User.objects.get(
                    username=request.user))
            context['authPosts'] = Post.getViewablePosts(viewer, author)
            context['doge'] = doges[random.randint(0,6)]

            return render_to_response('author/profile.html', context)
        else:
            return redirect('/login/')