コード例 #1
0
def doPost(request, current_posts):
    if request.method == 'POST':
        form = PostsForm(request.POST)
        if form.is_valid():
            formData = form.cleaned_data
            c = Post(
                subject=formData['subject'],
                author=request.user,
                content=formData['message'],
                time=datetime.datetime.now(),
            )
            if(len(formData['topic']) != 0):
                n = formData['topic']
                topics = Topic.objects.filter(name=n)
                if(len(topics) == 0):
                    t = Topic(name=n)
                    t.save()
                else:
                    t = topics[0]  
                c.topic = t
            c.save()
            return HttpResponseRedirect('/p')
    else:
        form = PostsForm(
            initial={'subject': 'Your subject', 'message': 'Put your comments here. Max 60000 words!'}
        )
    return render_to_response('posts/posts.html', {'form': form, 'current_posts' : current_posts }, context_instance=RequestContext(request)) 
コード例 #2
0
    def handle(self, *args, **options):
        PATH = os.path.join(BASE_DIR, '../assets/posts')
        SEPARATOR = '==='

        # For every blog post markdown file
        for post_file in os.listdir(PATH):
            post_f = open(os.path.join(PATH, post_file), 'r')
            post_string = post_f.read()

            # Get the heading and content data
            file_content = post_string.strip(SEPARATOR).split(SEPARATOR)
            heading = file_content[0].strip('\n').split(
                '\n')  # An array of the title, author and slug

            title = heading[0].replace('Title: ', '')
            author = heading[1].replace('Author: ', '')
            slug = heading[2].replace('Slug: ', '')

            content = file_content[1]  # The blog post content as a string
            tags = get_tags(content)

            # Create blog post object and save to the db
            post = Post(
                slug=slug.strip(),
                title=title.strip(),
                author=author.strip(),
                content=content.strip(),
                tags=tags,
            )

            post.save()
            self.stdout.write('Blog post "{}" saved.'.format(title))
コード例 #3
0
ファイル: views.py プロジェクト: 7Pros/circuit
def post_repost(request, pk=None):
    """
    Repost a post.

    This always reposts the original post.

    Redirects to the post's page if the repost was successful or if the user
    is not authenticated.
    Otherwise, redirects to the referer if present, or the landingpage if not.

    @param pk: the primary key which identifies the post
    @return redirect depending on the success
    """
    user = request.user
    repost_original = Post.objects.get(pk=pk).original_or_self()

    check = repost_original.check_repost(user)
    if check == 'not_auth':
        return redirect('posts:post', pk=repost_original.pk)
    if check != 'ok':
        return redirect(request.META['HTTP_REFERER'] or 'landingpage')

    repost = Post(content=repost_original.content,
                  author=user,
                  repost_original=repost_original)
    repost.save()
    context = {
        'content': "There is a new repost to a post of you made by %s" % user.username,
        'link_to_subject': reverse("posts:post", kwargs={'pk': repost.pk})
    }
    send_notifications(repost_original.author, "There is a new repost to your post",
                       'users/notification_for_post_email.html', context, repost)

    return redirect('posts:post', pk=repost.pk)
コード例 #4
0
ファイル: post_filters.py プロジェクト: pennyfea/404-project
def get_delete(value):
    post = Post()
    user = User()
    user.id = value['author']['id']
    post.id = value['id']
    post.user = user
    return post.get_delete_absolute_url()
コード例 #5
0
ファイル: tests.py プロジェクト: HubertNgu/319-Project
 def new_post_for_testing(self):
     """
     creates a new post with required fields filled out for use in testing
     """
     post = Post(url="test", creator="*****@*****.**", title="test", text_content="test", type="blog")
     post.save()
     return post
コード例 #6
0
    def add_post_data_from_webpage(self):

        for account in self.accounts:
            url = 'https://www.youtube.com/feeds/videos.xml?channel_id={}'.format(
                account.account_id)
            soup = BeautifulSoup(requests.get(url).content, "xml")
            for entry in soup.find_all('entry'):
                account.updated = datetime.utcnow()
                account.save()
                source_id = entry.find('id').text.replace('yt:video:', '')
                exists = Post.objects.filter(source_id=source_id).count()
                if exists:
                    continue
                if self.reject_condition_exists(
                        entry.find('title').text, account):
                    continue
                post = Post(account=account,
                            title=entry.find('title').text,
                            description=entry.find('media:group').find(
                                'media:description').text,
                            created=entry.find('published').text,
                            source_id=source_id,
                            url=entry.find('media:group').find(
                                'media:content').get('url'),
                            thumbnail=entry.find('media:group').find(
                                'media:thumbnail').get('url'))
                print('Adding {}\'s  -  {}'.format(account.name, post.title))
                post.save()
コード例 #7
0
ファイル: views.py プロジェクト: svrakitin/vas3k.club
def profile(request, user_slug):
    user = get_object_or_404(User, slug=user_slug)

    if user.id == request.me.id:
        goto = request.GET.get("goto")
        if goto:
            return redirect(goto)

    tags = Tag.objects.filter(is_visible=True).all()

    intro = Post.get_user_intro(user)
    projects = Post.objects.filter(author=user, type=Post.TYPE_PROJECT).all()
    active_tags = {t.tag_id for t in UserTag.objects.filter(user=user).all()}
    achievements = UserBadge.objects.filter(user=user)[:8]
    expertises = UserExpertise.objects.filter(user=user).all()
    posts = Post.objects_for_user(request.me)\
        .filter(author=user, is_visible=True)\
        .exclude(type__in=[Post.TYPE_INTRO, Post.TYPE_PROJECT])

    return render(
        request, "users/profile.html", {
            "user": user,
            "intro": intro,
            "projects": projects,
            "tags": tags,
            "active_tags": active_tags,
            "achievements": achievements,
            "expertise_form": ExpertiseForm(),
            "expertises": expertises,
            "posts": paginate(request, posts),
        })
コード例 #8
0
def upload(request, customer_id):
    customer = get_object_or_404(Customer, pk=customer_id)
    if request.method == 'POST' and request.POST['content']:

        myfile = request.FILES['myfile']
        post = Post()
        post.content = request.POST['content']
        post.createtime = timezone.now()
        post.updatetime = timezone.now()
        post.customer = Customer.objects.get(id=customer_id)
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)

        # image = Image()
        post.save()
        for file in request.FILES.getlist('myfile'):
            image = Image()
            post.save()
            image.imageurl = file
            image.post = Post.objects.get(id=post.id)
            image.save()
        # image.imageurl = filename
        # image.post = Post.objects.get(id=post.id)
        # post.save()
        # image.save()
        return redirect('/customers/' + 'detail/' + str(customer_id))
    return render(request, 'customers/detail.html', {'customer': customer})
コード例 #9
0
    def post(self, request, pk, idPost):
        """
        Actualiza un post en base a la información POST
        :param request: HttpRequest
        :return: HttpResponse
        """
        success_message = ''
        blog = UserUtils.getUserBlog(request.user.username)
        post_with_blog = Post()
        post_with_blog.blog = blog
        form = PostForm(request.POST, instance=post_with_blog) # Coge los datos del formulario sobreescribe los campos que tiene el objeto 'photo_with_owner'
        if form.is_valid():
            new_post = form.save() # Guarda el objeto en BB.DD. y me lo devuelve
            form = PostForm() # Forzamos a que el formulario se vacie si la creacion de la foto ha sido satisfactoria
            success_message = 'Guardado con éxito!'
            success_message += '<a href = "{0}">'.format(
                reverse('post_detail', args=[new_post.blog.author.username,new_post.pk])
            )
            success_message += 'Ver post'
            success_message += '</a>'

            blog = UserUtils.getUserBlog(pk)
            possible_posts = self.get_posts_queryset(request).filter(blog__name=blog.name, pk=idPost).order_by('-publication_date')
            post_to_delete = possible_posts[0] if len(possible_posts) >= 1 else None
            if post_to_delete is not None:
                post_to_delete.delete()
        context = {
            'form': form,
            'success_message': success_message
        }
        return self.render(request, context)
コード例 #10
0
    def test_list_posts(self):
        response = self.client.get(self.post_list_url)

        self.assertEqual(response.status_code, 200)

        post_data = [{
            'title': 'test1',
            'body': 'test1',
            'user': self.user
        }, {
            'title': 'test2',
            'body': 'test2',
            'user': self.user
        }]

        for data in post_data:
            post = Post(**data)
            post.save()

        # not logged in
        response = self.client.get(self.post_list_url)
        payload = response.json()

        self.assertEqual(len(payload), 2)

        # now logged in
        self.login()

        response = self.client.get(self.post_list_url)
        payload = response.json()

        self.assertEqual(len(payload), 2)
コード例 #11
0
 def post(self, request):
     """
     Crea un post en base a la información POST
     :param request: HttpRequest
     :return: HttpResponse
     """
     success_message = ''
     blog = UserUtils.getUserBlog(request.user.username)
     post_with_blog = Post()
     post_with_blog.blog = blog
     form = PostForm(request.POST, instance=post_with_blog) # Coge los datos del formulario sobreescribe los campos que tiene el objeto 'photo_with_owner'
     if form.is_valid():
         new_post = form.save() # Guarda el objeto en BB.DD. y me lo devuelve
         form = PostForm() # Forzamos a que el formulario se vacie si la creacion de la foto ha sido satisfactoria
         success_message = 'Guardado con éxito!'
         success_message += '<a href = "{0}">'.format(
             reverse('post_detail', args=[new_post.blog.author.username,new_post.pk])
         )
         success_message += 'Ver post'
         success_message += '</a>'
     context = {
         'form': form,
         'success_message': success_message
     }
     return self.render(request, context)
コード例 #12
0
    def post(self, request):
        form = RegistrarUsuarioForm(request.POST)

        if (form.is_valid()):
            dados = form.cleaned_data
            if request.POST['senha_1'] != request.POST['senha']:
                message = 'Atençao! As senhas não conferem.'
                form = RegistrarUsuarioForm(request.POST)
                return render(request, 'usuarios/registrar.html', {
                    'form': form,
                    'message': message
                })
            usuario = User.objects.create_user(dados['nome'], dados['email'],
                                               dados['senha'])
            perfil = Perfil(nome=usuario.username,
                            nome_empresa=dados['nome_empresa'],
                            telefone=dados['telefone'],
                            usuario=usuario)
            perfil.save()
            post = Post(user=perfil,
                        postagem='Opa, nenhuma postagem!',
                        init=True)
            post.save()
            message = Feedback(perfil=perfil,
                               message='Perfil criado com sucesso.')
            message.save()
            return redirect('login')

        return render(request, 'usuarios/registrar.html', {'form': form})
コード例 #13
0
ファイル: views.py プロジェクト: Albert-Chan/uglyDuckling
def doPost(request, current_posts):
    if request.method == 'POST':
        form = PostsForm(request.POST)
        if form.is_valid():
            formData = form.cleaned_data
            c = Post(
                subject=formData['subject'],
                author=request.user,
                content=formData['message'],
                time=datetime.datetime.now(),
            )
            if (len(formData['topic']) != 0):
                n = formData['topic']
                topics = Topic.objects.filter(name=n)
                if (len(topics) == 0):
                    t = Topic(name=n)
                    t.save()
                else:
                    t = topics[0]
                c.topic = t
            c.save()
            return HttpResponseRedirect('/p')
    else:
        form = PostsForm(
            initial={
                'subject': 'Your subject',
                'message': 'Put your comments here. Max 60000 words!'
            })
    return render_to_response('posts/posts.html', {
        'form': form,
        'current_posts': current_posts
    },
                              context_instance=RequestContext(request))
コード例 #14
0
def create_post(request):
    """
    Muestra un formulario para crear un nuevo post y lo crea si la petición es POST
    :param request: HttpRequest
    :return: HttpResponse
    """
    success_message = []
    if request.method == 'GET':
        form = PostForm()
    else:
        form = PostForm(request.POST)
        if form.is_valid():
            post_with_owner = Post()
            post_with_owner.owner = request.user # asigno como propietario del post, el usuario autenticado
            form = PostForm(request.POST, instance=post_with_owner)
            if form.is_valid():
                new_post = form.save() # Guarda el objeto Post y lo devuelve
                form = PostForm()
                success_message = '¡Post creado con éxito!'
                success_message += '<br><a href="{0}">'.format(
                    reverse('post_detail', args=[new_post.pk])
                )
                success_message += 'Ver foto'
                success_message += '</a>'
    context = {
        'form': form,
        'success_message': success_message
    }
    return render(request, 'posts/new_post.html', context)
コード例 #15
0
ファイル: auth.py プロジェクト: maxlipsky/vas3k.club
def debug_dev_login(request):
    if not settings.DEBUG:
        raise AccessDenied(title="Эта фича доступна только при DEBUG=true")

    user, is_created = User.objects.get_or_create(
        slug="dev",
        defaults=dict(
            patreon_id="123456",
            membership_platform_type=User.MEMBERSHIP_PLATFORM_PATREON,
            email="*****@*****.**",
            full_name="Senior 23 y.o. Developer",
            company="FAANG",
            position="Team Lead конечно",
            balance=10000,
            membership_started_at=datetime.utcnow(),
            membership_expires_at=datetime.utcnow() +
            timedelta(days=365 * 100),
            created_at=datetime.utcnow(),
            updated_at=datetime.utcnow(),
            is_email_verified=True,
            moderation_status=User.MODERATION_STATUS_APPROVED,
            roles=["god"],
        ),
    )

    if is_created:
        Post.upsert_user_intro(user, "Очень плохое интро", is_visible=True)

    session = Session.create_for_user(user)

    return set_session_cookie(redirect("profile", user.slug), user, session)
コード例 #16
0
def intro(request):
    if request.me.moderation_status == User.MODERATION_STATUS_APPROVED:
        return redirect("profile", request.me.slug)

    if request.method == "POST":
        form = UserIntroForm(request.POST, request.FILES, instance=request.me)
        if form.is_valid():
            user = form.save(commit=False)

            # send to moderation
            user.moderation_status = User.MODERATION_STATUS_ON_REVIEW
            user.save()

            # create intro post
            intro_post = Post.upsert_user_intro(user,
                                                form.cleaned_data["intro"],
                                                is_visible=False)

            Geo.update_for_user(user)

            # notify moderators to review profile
            async_task(notify_profile_needs_review, user, intro_post)

            return redirect("on_review")
    else:
        existing_intro = Post.get_user_intro(request.me)
        form = UserIntroForm(
            instance=request.me,
            initial={"intro": existing_intro.text if existing_intro else ""},
        )

    return render(request, "users/intro.html", {"form": form})
コード例 #17
0
    def create(self, validated_data):
        content = validated_data['content']
        thread_id = validated_data['thread_id']

        # Get thread object
        try:
            thread = Thread.objects.get(id=thread_id)
        except Thread.DoesNotExist:
            raise serializers.ValidationError('Thread does not exist, please enter correct thread id')

        # Get the requesting user
        user = None
        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user
        else:
            raise serializers.ValidationError('Must be authenticated to create post')

        # Create the post
        post = Post(
            content=content,
            thread=thread,
            creator=user
        )
        # Update the thread last_activity to post creation time
        post.save()
        thread.last_activity = post.created_at
        thread.save()
        return post
コード例 #18
0
ファイル: views.py プロジェクト: manezgz/Wordplease
def newPost(request):
   """

   :param request:
   :return:
   """
   success_message=''
   categorias =Categoria.objects.all()
   if request.method == 'GET':
       form=PostForm()
   else:
       post_with_owner = Post()
       post_with_owner.owner=request.user
       form=PostForm(request.POST,instance=post_with_owner)
       if form.is_valid():
           new_post=form.save()
           username=new_post.owner
           postid=new_post.pk
           success_message = 'Guardado con éxito'
           success_message += '<a href="{0}">'.format(reverse('post_detail',kwargs={'username':username,'postid':postid}))
           success_message += 'Ver Post'
           success_message += '</a>'
           form = PostForm()
   context = {
       'form' : form,
       'categorias' : categorias,
       'success_message' : success_message
   }
   return render(request, 'posts/new-post.html',context)
コード例 #19
0
ファイル: views.py プロジェクト: krainet/Wordplease
    def post(self, req):
        """
        Muestra un form para crear un post y lo crea si la peticion es POST
        :param req: HttpRequest
        :return: HttpResponse
        """
        error_messages = []
        success_message = ''

        # Creamos owner y se lo pasamos al form con un objeto pre-establecido
        post_with_owner = Post()
        post_with_owner.owner = req.user
        post_with_owner.blog = Blog.objects.filter(owner=req.user)[0]

        form = PostCreateForm(req.POST, instance=post_with_owner)
        if form.is_valid():

            new_post = form.save()
            form = PostCreateForm()
            success_message = u'Post guardado con éxito! '
            success_message += u'<a href="{0}">'.format(reverse('post_detail', args=[req.user.username, new_post.pk]))
            success_message += u'(ver post)</a>'
        else:
            error_messages.append(u'Formulario incompleto.')

        context = {
            'form': form,
            'success_message': success_message
        }
        return render(req, 'posts/new_post.html', context)
コード例 #20
0
    def image_form_upload(request):
        if request.method == 'POST':
            form = ImageForm(request.POST, request.FILES)
            if form.is_valid():

                url = "https://api.imgur.com/3/upload"
                access_token = "931ddfab9e19c9a7512147c83459ce1d457e09cf"
                headers = {'Authorization': 'Bearer ' + access_token}
                data = {
                    'image': request.FILES.get('imagefile').read(),
                    'title': request.POST['description'],
                    'type': 'file'
                }
                response = requests.request("POST",
                                            url,
                                            headers=headers,
                                            data=data)
                response_data = response.json()
                upload_success = response_data['success']
                external_link = response_data['data']['link']
                print(upload_success)

                # save reference to database as a post
                new_post = Post(content=external_link, author=request.user)
                new_post.save()

                return redirect('image')
        else:
            form = ImageForm()
        return render(request, 'iv/image.html', {'form': form})
コード例 #21
0
ファイル: schema.py プロジェクト: kamiram/gql
 def mutate(root, info, input=None):
     ok = True
     post_instance = Post(title=input.title,
                          descr=input.descr,
                          owner_id=input.owner)
     post_instance.save()
     return CreatePost(ok=ok, post=post_instance)
コード例 #22
0
ファイル: views.py プロジェクト: svrakitin/vas3k.club
def intro(request):
    if request.me.is_profile_complete \
            and request.me.is_profile_reviewed \
            and not request.me.is_profile_rejected:
        return redirect("profile", request.me.slug)

    if request.method == "POST":
        form = UserIntroForm(request.POST, request.FILES, instance=request.me)
        if form.is_valid():
            user = form.save(commit=False)

            # send to moderation
            user.is_profile_complete = True
            user.is_profile_reviewed = False
            user.is_profile_rejected = False
            user.save()

            # create intro post
            intro_post = Post.upsert_user_intro(user,
                                                form.cleaned_data["intro"],
                                                is_visible=False)

            # notify moderators to review profile
            async_task(notify_profile_needs_review, user, intro_post)

            return redirect("on_review")
    else:
        existing_intro = Post.get_user_intro(request.me)
        form = UserIntroForm(
            instance=request.me,
            initial={"intro": existing_intro.text if existing_intro else ""},
        )

    return render(request, "users/intro.html", {"form": form})
コード例 #23
0
ファイル: auth.py プロジェクト: DmitryKhitrin/vas3k.club
def debug_random_login(request):
    if not settings.DEBUG:
        raise AccessDenied(title="Эта фича доступна только при DEBUG=true")

    slug = "random_" + random_string()
    user, is_created = User.objects.get_or_create(
        slug=slug,
        defaults=dict(
            patreon_id=random_string(),
            membership_platform_type=User.MEMBERSHIP_PLATFORM_PATREON,
            email=slug + "@random.dev",
            full_name="%s %d y.o. Developer" % (random.choice(["Максим", "Олег"]), random.randint(18, 101)),
            company="Acme Corp.",
            position=random.choice(["Подниматель пингвинов", "Опускатель серверов", "Коллектор пивных бутылок"]),
            balance=10000,
            membership_started_at=datetime.utcnow(),
            membership_expires_at=datetime.utcnow() + timedelta(days=365 * 100),
            created_at=datetime.utcnow(),
            updated_at=datetime.utcnow(),
            is_email_verified=True,
            moderation_status=User.MODERATION_STATUS_APPROVED,
        ),
    )

    if is_created:
        Post.upsert_user_intro(user, "Интро как интро, аппрув прошло :Р", is_visible=True)

    session = Session.create_for_user(user)

    return set_session_cookie(redirect("profile", user.slug), user, session)
コード例 #24
0
ファイル: views.py プロジェクト: joviman69/Modulo8_Django
    def post(self, request):
        """
        Procesa el formulario de creación de un post
        :param request: objeto HttpRequest
        :return: HttpResponse con respuesta



        """
        post = Post()
        userid = User.objects.get(username=request.user).id
        try:
            post.blog = Blog.objects.get(owner=userid)
        except Blog.DoesNotExist:
            return HttpResponse(
                'Este usuario no tiene creado ningún blog. <a href="/new-blog" %}>Cree un blog</a> primero',
                status=404)

        form = PostForm(request.POST, request.FILES, instance=post)
        if form.is_valid():
            new_post = form.save()
            form = PostForm()
            messages.success(request, 'Post creado correctamente')

        context = {'form': form}
        return render(request, 'posts/form.html', context)
コード例 #25
0
def create(request):
    post = Post(post_text=request.POST['post_text'],
                title=request.POST['title'],
                content=request.POST['content'],
                pub_date=datetime.datetime.now())
    post.save()
    return HttpResponseRedirect(reverse('posts:detail', args=(post.id, )))
コード例 #26
0
ファイル: post_parser.py プロジェクト: deep11194g/ccv
def create_posts_from_xml(url):
    """
    Read XML file data and add each row as a post to database

    :param(str) url: Web URL of XML Data
    :return(int): No of Posts added to database
    """
    data = get_xml_data_from_file(url)
    count = 0
    from posts.models import Post
    for row in data:
        new_post = Post()
        for key, value in row.items():
            object_attr_type = KEY_ATTR_MAP.get(key)
            if not object_attr_type:
                continue        # XML key not of our interest
            attribute = object_attr_type[0]
            data_type = object_attr_type[1]
            try :
                # Type cast and assign value to mapped attribute of `post` object
                setattr(new_post, attribute, data_type(value))
            except (TypeError, ValueError) as e:
                continue
        new_post.save()
        count += 1
    print("{} Posts added".format(count))
    return count
コード例 #27
0
def post_reply(request, pk=None):
    """
    Reply to a post.

    Redirects to the post page.

    @param request:
    @param pk:

    @return:
    """
    user = request.user
    reply_original = Post.objects.get(pk=pk)
    author = reply_original.author

    check = reply_original.check_reply(user)
    if check != 'ok':
        return redirect('posts:post', pk=reply_original.pk)

    reply = Post(content=request.POST['content_reply'],
                 author=user,
                 reply_original=reply_original)

    reply.save()
    context = {
        'content':
        "There is a new reply to a post of you made by %s" % user.username,
        'link_to_subject': reverse("posts:post", kwargs={'pk': reply.pk})
    }
    send_notifications(author, "There is a new reply to your post",
                       'users/notification_for_post_email.html', context,
                       reply)
    reply_original.reply.add(reply)

    return redirect('posts:post', pk=reply_original.pk)
コード例 #28
0
ファイル: views.py プロジェクト: 7Pros/circuit
def post_reply(request, pk=None):
    """
    Reply to a post.

    Redirects to the post page.

    @param request:
    @param pk:

    @return:
    """
    user = request.user
    reply_original = Post.objects.get(pk=pk)
    author = reply_original.author

    check = reply_original.check_reply(user)
    if check != 'ok':
        return redirect('posts:post', pk=reply_original.pk)

    reply = Post(content=request.POST['content_reply'],
                 author=user,
                 reply_original=reply_original)

    reply.save()
    context = {
        'content': "There is a new reply to a post of you made by %s" % user.username,
        'link_to_subject': reverse("posts:post", kwargs={'pk': reply.pk})
    }
    send_notifications(author, "There is a new reply to your post",
                       'users/notification_for_post_email.html', context, reply)
    reply_original.reply.add(reply)

    return redirect('posts:post', pk=reply_original.pk)
コード例 #29
0
 def setUp(self):
     self.factory = RequestFactory()
     self.client = Client()
     self.user = DjangoUser.objects.create_superuser(
         'adminz', '*****@*****.**', 'adminpass')
     self.post = Post(user=self.user, **POST_DATA)
     self.post.save()
コード例 #30
0
    def post(self, request):
        """
        Muestra un formulario para crear un nuevo post.
        :param request: HttpRequest
        :return: HttpResponse
        """
        success_message = ''

        form_with_blog = Post()
        posible_blog = Blog.objects.filter(owner=request.user)
        blog = posible_blog[0] if len(posible_blog) == 1 else None
        if blog is not None:
            form_with_blog.blog = blog
            form = PostForm(request.POST, instance=form_with_blog)
            if form.is_valid():
                new_post = form.save()
                form = PostForm()
                success_message = 'Guardado con éxito!'
        else:
            form = PostForm()
        context = {
            'form': form,
            'success_message': success_message
        }

        return render(request, 'posts/new_post.html', context)
コード例 #31
0
ファイル: views.py プロジェクト: ednapiranha/refrig
def posts(request):
    """
    add a new post
    """
    if check_key(request):
        if request.method == 'POST':
            Post.save_by_pattern(request)
    return HttpResponseRedirect('/yours')
コード例 #32
0
ファイル: tests.py プロジェクト: sonnym/craigle
    def test_create_or_update(self):
        url = 'foo'

        Post.create_or_update(url)
        self.assertEqual(1, Post.objects.count())

        Post.create_or_update(url)
        self.assertEqual(1, Post.objects.count())
コード例 #33
0
 def test_user_feed_contains_post_by_user(self):
     """A user's post show up on their own feed."""
     test_user = self.users[0]
     self.client.force_login(test_user)
     post = Post(author=test_user, title="TestPost", content="testcontent")
     post.save()
     response = self.client.get('/')
     self.assertContains(response, 'TestPost')
コード例 #34
0
 def test_publish_study_post(self):
     new_post = Post(category='OOP',
                     body='unit test post',
                     author=self.user)
     new_post.save()
     pk = new_post.id
     response = self.client.post(reverse('posts:post-detail', args=(pk, )))
     self.assertEqual(response.status_code, 200)
コード例 #35
0
ファイル: views.py プロジェクト: 7Pros/circuit
    def form_valid(self, form):
        """
        Check if the user is allowed to edit the post this way.

        The user must be logged in and the post content must be
        at most 256 python characters long.

        @param form: the form containing the new post
        @return `form_valid` if accepted, `form_invalid` if not
        """
        if not self.request.user.is_authenticated:
            return self.form_invalid(form)
        has_img = 'image' in self.request.FILES
        if has_img and not Post.image_is_valid(self.request.FILES['image']):
            messages.error(self.request, 'Invalid image format')

        if not Post.content_is_valid(self.request.POST['content']):
            return self.form_invalid(form)
        old_post = self.object
        parsed_content_old = Post.parse_content(old_post.content)
        post = form.save()
        parsed_content_new = Post.parse_content(post.content)
        mentioned_users = User.objects.filter(username__in=parsed_content_new['mentions'])
        for mentionedUser in mentioned_users:
            if post.circles_id == -1:
                members = mentioned_users
            else:
                members = post.circles.members.all()

            for member in members:
                if mentionedUser.username in parsed_content_old['mentions']:
                    context = {
                        'content': "%s changed his post you were metioned in" % self.request.user.username,
                        'link_to_subject': reverse("posts:post", kwargs={'pk': post.pk})
                    }
                else:
                    context = {
                        'content': "%s mentioned you in his post" % self.request.user.username,
                        'link_to_subject': reverse("posts:post", kwargs={'pk': post.pk})
                    }
                send_notifications(mentionedUser, "You were mentioned!",
                                   'users/notification_for_post_email.html', context, post)

        circle_pk = int(self.request.POST['circle'])
        if circle_pk not in (ME_CIRCLE, PUBLIC_CIRCLE):
            circle_owner_id = Circle.objects.get(pk=circle_pk).owner_id
            # Is the selected circle not one of the user's circles?
            if circle_owner_id != self.request.user.pk:
                return self.form_invalid(form)

        post = form.save()
        if has_img:
            post.image = self.request.FILES['image']

        circle_pk = int(self.request.POST['circle'])
        post.circles = Circle(circle_pk)

        return super(PostEditView, self).form_valid(form)
コード例 #36
0
ファイル: views.py プロジェクト: chrisrodz/microposts
def add(request):
	if request.method == 'POST':
		user = Follower.objects.get(follower=request.user)
		post = request.POST['message']
		p = Post(post=post,user=user)
		p.save()
		return profile(request)
	else:
		return render_to_response('addpost.html', {'user': request.user}, context_instance=RequestContext(request))
コード例 #37
0
def create(request):
    if request.method == "POST":
        title = request.POST.get('title')
        content = request.POST.get('content')
        post = Post(title=title, content=content)
        post.save()
        return redirect('list')

    return render(request, 'posts/create.html')
コード例 #38
0
class PostForUser(TestCase):
    databases = ['default', 'messenger_users_db']

    def setUp(self):
        self.POST_DATA = POST_DATA
        self.user = DjangoUser.objects.create_user(username='******',
                                                   email='*****@*****.**',
                                                   password='******')
        self.post = Post(user=self.user, **self.POST_DATA)
        self.post.save()
        self.muser = MUser(last_channel_id=1,
                           channel_id=1,
                           backup_key="backz1",
                           username="******")
        self.muser.save()

    def test_get_post_for_user(self):
        user_data = {'username': "******", 'value': 15, 'premium': False}
        response = self.client.get('/posts/getPostForUser', user_data)

    def test_get_post_for_user_chan(self):
        user_data = {'channel_id': 1, 'value': 15, 'premium': False}
        response = self.client.get('/posts/getPostForUser', user_data)

    def test_fail_to_get_post_for_user__recoo(self):
        user_data = {'channel_id': 1, 'value': 15, 'premium': False}
        response = self.client.get('/posts/getRecommendedPostForUser',
                                   user_data)
        # self.assertEqual(response.)

    def test_fail_post_for_user(self):
        user_data = {"asdf": "fasd"}
        response = self.client.get('/posts/getPostForUser', user_data)
        #TODO: json error

    def test_fetch_post(self):
        p_id = self.post.id
        self.client.post(
            f"/messenger_users/actions/user/{self.muser.id}/set/set active_session"
        )
        response = self.client.get(f'/posts/{p_id}/', {
            "username": self.muser.username,
            'bot_id': 1
        })
        eq_(response.status_code, 200)

    def test_set_interaction(self):
        data = {
            "username": self.muser.username,
            "bot_id": "1",
            "post_id": self.post.id,
            "interaction_type": "opened"
        }
        response = self.client.post('/posts/set_interaction/', data)

    def test_comment_post(self):
        pass
コード例 #39
0
    def mutate(self, info, title, content):
        post = Post(title=title, content=content)
        post.save()

        return CreatePost(
            id=post.id,
            title=post.title,
            content=post.content,
        )
コード例 #40
0
 def test_post_edit_wrong_user(self):
     """Test post edit wrong user returns 404."""
     this_user = self.users[0]
     self.client.force_login(this_user)
     this_post = Post()
     this_post.author = self.users[1]
     this_post.save()
     response = self.client.post('/posts/' + str(this_post.id) + '/edit')
     self.assertTrue(response.status_code == 404)
コード例 #41
0
 def test_save_delete(self):
     self.testpost2 = Post(user=self.testuser,
                           url="www.example.com/testimage2.jpeg",
                           likes=0)
     self.assertNotIn(self.testpost2, Post.objects.all())
     self.testpost2.save_pic()
     self.assertIn(self.testpost2, Post.objects.all())
     self.testpost2.delete()
     self.assertNotIn(self.testpost2, Post.objects.all())
コード例 #42
0
    def test_add_answer_to_question(self):
        post = Post(content='Testing',
                    type='answer',
                    parent=Question.objects.get(pk=1).post,
                    created_by=A2AUser.objects.get(pk=1))
        post.save()

        self.check_num_answers()
        self.check_num_questions()
コード例 #43
0
def create(user_id: int, post):
    newPost = Post(user_id=user_id,
                   post=post,
                   created_at=datetime.now(),
                   updated_at=datetime.now())

    newPost.save()

    return True
コード例 #44
0
ファイル: tests.py プロジェクト: tlmn95/tech2016
    def test_add_answer_to_question(self):
        post = Post(
            content='Testing',
            type='answer',
            parent=Question.objects.get(pk=1).post,
            created_by=A2AUser.objects.get(pk=1)
        )
        post.save()

        self.check_num_answers()
        self.check_num_questions()
コード例 #45
0
    def post(self, request):
        form = AddPostForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            post = Post()
            post.text = data['text']
            post.author = request.user
            post.save()
            return redirect("posts:list")

        return render_to_response(self.template_name, {'form': form}, context_instance=RequestContext(request))
コード例 #46
0
ファイル: models.py プロジェクト: RohitRepo/ShowCase
    def create_post(self, created, raw):
        if not created or raw:
            return

        if self.bucket.public:
            post = Post(
                composition=self.composition,
                creator=self.bucket.owner,
                post_type = Post.BUCKET,
                content_object=self.bucket)
            post.save()
コード例 #47
0
ファイル: api.py プロジェクト: rooshilp/CMPUT410W15-project
def postid_post(request, post_id):
    # get post with id in url
    if request.method == "GET":
        try:
            post = [Post.objects.get(uuid=post_id)]
            data = get_posts(post)
        except:
            return HttpResponse(status=404)
        return JsonResponse(data, safe=False)
    # update post with id in url
    if request.method == "PUT":
        received_data = json.loads(request.body)
        try:
            current_user = User.objects.get(username=request.user.username)
            current_profile = Profile.objeects.get(user=current_user)
            post = Post.objects.get(uuid=post_id)

            title = received_data['title']
            description = received_data['description']
            content_type = received_data['content-type']
            content = received_data['content']

            post.title = received_data['title']
            post.description = received_data['description']
            post.content_type = received_data['content-type']
            post.post_text = received_data['content']
            post.save()
        except:
            return HttpResponse(status=404)

        return HttpResponse(status=200)

    # create post with id in url
    if request.method == "POST":
        received_data = json.loads(request.body)
        try:
            current_user = User.objects.get(username=request.user.username)
            current_profile = Profile.objects.get(user=current_user)

            title = received_data['title']
            description = received_data['description']
            content_type = received_data['content-type']
            content = received_data['content']
            date = timezone.now()
            new_post = Post(uuid=post_id, author=current_profile, title=title, description=description,
            content_type=content_type, post_text=content, date=date)
            new_post.save()
        except:
            return HttpResponse(status=404)

        return HttpResponse(status=200)

    return HttpResponse(status=405)
コード例 #48
0
ファイル: views.py プロジェクト: ljsking/tiny
def post(request):
    msg = request.GET['message']
    email = request.user.email
    p = Post(message=msg, email=email, pub_date=datetime.datetime.now())
    p.save()
    '''
    sa = request.user.social_auth.get()
    token = sa.extra_data['access_token']
    graph = facebook.GraphAPI(token)
    graph.put_object('me','feed',message=msg)
    '''
    
    return HttpResponseRedirect(reverse('posts.views.index'))
コード例 #49
0
ファイル: test_models.py プロジェクト: kaapstorm/onepageblog
def markdown_post():
    post = Post(
        title='My Post',
        content_markdown=inspect.cleandoc("""
        Heading
        =======

        Body text
        """)
    )
    post.save()
    yield post
    post.delete()
コード例 #50
0
ファイル: views.py プロジェクト: joshyg/statshark
def add_post(request, post_id):
  print "in add_post"+str(post_id)
  session_id = request.session.get('_auth_user_id', -1)
  if(session_id == -1):
    return HttpResponse("Must login to view this page")
  username = User.objects.get(pk=session_id)
  #csrf: Cross Site Request Forgery protection
  csrf_request = {}
  csrf_request.update(csrf(request))
  p = Post(title=request.POST['new_post_title'], 
           text=request.POST['new_post_text'], 
           pub_date = timezone.now(),
           author = username,
           love = 0, hate = 0)
             
  p.save()
  #upload choices if poll
  localchoice_text = []
  localchoice = []
####old approach, works for a fixed amount of choices
  print request.POST
  print "id = "+post_id
  i = 1
  choice_i_exists = True
  while(choice_i_exists == True):
    localchoice_text.append(request.POST.get('choice_%d' % (i), -1))
    if(localchoice_text[i-1] == -1):
      choice_i_exists = False
    elif(localchoice_text[i-1] != ''):
      #the following failed when we deleted posts
      #localchoice.append(Choice(parent_post = get_object_or_404(Post, pk=post_id),
      localchoice.append(Choice(parent_post = p,
                         text = localchoice_text[i-1], 
                         votes = 0))
      localchoice[i-1].save()
    i+=1
    
  #upload photo
  post_photo = request.POST.get('post_photo', -1)
  if(post_photo != ''):
    photo_file = File(request.FILES['post_photo'])
    #the following failed when we deleted posts
    #post_photo = PostPhoto(parent_post =get_object_or_404(Post, pk=post_id),
    #                       image = photo_file)
    post_photo = PostPhoto(parent_post = p,
                           image = photo_file)
    post_photo.save()
    photo_file.close()
    
    #photo_object = PostPhoto
  return HttpResponseRedirect(reverse('posts.views.main'))
コード例 #51
0
ファイル: views.py プロジェクト: jonathanyip/GhostCat
def userPost(request):
	if not request.user.is_authenticated():
		return redirect('Login')
	
	if 'form-post' in request.POST:
		text = request.POST['form-post']
		if(len(text) > 140):
			context = { 'post_error': 'The post needs to be 140 characters or less!' }
			return render(request, 'post_form.html', context)
		post = Post(post_text=text, post_author=request.user)
		post.save()
		return redirect('Homepage')
	
	return render(request, 'postForm.html')
コード例 #52
0
ファイル: views.py プロジェクト: GleasSpty/eduh2
def school(request, internalName):
	user = request.user
	posts = Post.objects.filter(school = School.objects.get(internalName = internalName))

	if request.method == 'POST':
		postForm = PostForm(request.POST)
		if postForm.is_valid():
			post = Post(title = postForm.cleaned_data['title'], user = user, school = user.get_profile().school, seekingFemale = postForm.cleaned_data['seekingFemale'], seekingMale = postForm.cleaned_data['seekingMale'], seekingTransgendered = postForm.cleaned_data['seekingTransgendered'], type = postForm.cleaned_data['hookupType'], allowOtherSchools = postForm.cleaned_data['allowOtherSchools'], text = postForm.cleaned_data['text'])
			post.save()
			return HttpResponseRedirect('')
		else:
			return render_to_response('schools/school.html', {'posts':  posts, 'postForm':  postForm, 'user':  user, 'loginform':  AuthenticationForm, 'logoSize':  50}, context_instance = RequestContext(request))
	else:
		return render_to_response('schools/school.html', {'posts':  posts, 'postForm':  PostForm(), 'user':  user, 'loginform':  AuthenticationForm, 'logoSize':  50}, context_instance = RequestContext(request))
コード例 #53
0
ファイル: views.py プロジェクト: tpolasek/cmput410-project
def create_post(request, author_name = None ):
    context = RequestContext(request)
    u = request.user
    a = Author.objects.get(user = u)

    form = CreatePostForm()
    context_dict = {'author': a, 'success': False, 'form':form }

    if request.method == "POST":
        access = request.POST['access']
        c = request.POST['content']
        post_title = request.POST['title']
        t = request.POST['content_type']
        if t == "text/x-markdown":
            import markdown2
            c = markdown2.markdown(c)
        elif t == "text/plain":
            c = c
        else:
            pass

        p = Post(author=a, visibility=access, content=c, title=post_title)
        p.content_type = t
        p.save()
        p.source = "http://%s/posts/%s" % ( request.META['HTTP_HOST'], p.id )
        p.origin = p.source
        p.save()

        return HttpResponseRedirect("/posts/")

    return render_to_response('social/createPost.html', context_dict, context)
コード例 #54
0
ファイル: views.py プロジェクト: robertsami/COS333
def create_thread(request):
	tuple = get_tags(request.POST['title'])
	# Create and save new thread
	t = Thread(author=request.POST['author'], title=tuple[0], professor_viewable=(request.POST.has_key('professor_viewable')))
	t.save()
	for ttag in tuple[1]:
		tag = Tag(tag = ttag)
		tag.save()
		t.tags.add(tag)
	t.save()
	# Create and save new post
	p = Post(author=request.POST['author'], content=request.POST['content'], thread=t)
	p.save()
	return HttpResponseRedirect(reverse('posts.views.index'))
コード例 #55
0
ファイル: tests.py プロジェクト: vladymir/myblog
 def test_creating_new_post_and_saving_to_database(self):
     #start creating a new post
     post = Post()
     post.title = "My first post"
     post.pub_date = timezone.now()
     
     post.save()
     
     all_posts_in_database = Post.objects.all()
     self.assertEquals(len(all_posts_in_database),1)
     only_post_in_database = all_posts_in_database[0]
     self.assertEquals(only_post_in_database, post)
     
     self.assertEquals(only_post_in_database.title, "My first post")
     self.assertEquals(only_post_in_database.pub_date, post.pub_date)
コード例 #56
0
ファイル: addpost.py プロジェクト: Lukasa/minimalog
    def handle(self, *args, **options):
        for url in args:
            try:
                post = requests.get(url)

                if post.status_code == requests.codes.ok:
                    # Assume that the name of the post is the filename. Works for GitHub.
                    filename = '.'.join(url.split('/')[-1].split('.')[:-1])
                    p = Post(body = post.text, title = filename)
                    p.save()
                    self.stdout.write("Successfully added new post with url: '%s'" % filename)
                else:
                    raise CommandError('URL not valid.')
            except (requests.RequestException, requests.Timeout, requests.ConnectionError) as e:
                raise CommandError("A connection error was encountered.")
コード例 #57
0
ファイル: tests.py プロジェクト: dm03514/django-posts-lite
 def test_votepost_create_success(self):
     """
     Tests that a new vote can successfully be created
     """
     self.client.login(username=self.username, 
                       password=self.password)
     # create a new post
     post = Post(created_by=self.test_user, text='asdfasdf', title='tests')
     post.save()
     response = self.client.post(reverse('posts:vote', 
                                         args=[post.pk, 'up']), 
                                 follow=True)
     self.assertTrue('Thank you for voting' in response.content)
     vote = PostVote.objects.get(post=post)
     self.assertEqual(vote.score, 1)
コード例 #58
0
ファイル: views.py プロジェクト: rajesh67/Ucodice.com
def postplan_update_view(request,*args,**kwargs):
    year=kwargs.get('year')
    month=kwargs.get('month')
    day=kwargs.get('day')
    slug=kwargs.get('slug')
    post=Post.objects(slug=slug).first()
    if request.method=="POST":
        form=PlanForm(request.POST)
        if form.is_valid():
            ending=form.cleaned_data['ending']
            starting=form.cleaned_data['starting']
            title=form.cleaned_data['title']
            transport=form.cleaned_data['transport']
            cost=form.cleaned_data['cost']
            content=form.cleaned_data['content']
            plan=PostPlan(title=title,transport=transport,cost=cost,content=content)
            plan.save()
            plan.starting=datetime.combine(date(year=year,month=month,day=day),starting)
            plan.ending=datetime.combine(date(year=year,month=month,day=day),ending)
            plan.save()
            post.postplans.append(plan.number)
            post.save()
            return HttpResponseRedirect(reverse('plan-create',kwargs={'slug':slug,'year':year,'month':month,'day':day}))
    else:
        plan=PostPlan.objects(number=kwargs.get('pk')).first()
        form=PlanForm()
        return render(request,'plans/plan_update.html',{'plan':plan,'form':form})
コード例 #59
0
ファイル: views.py プロジェクト: 7Pros/circuit
def user_profile_by_username(request, username):
    """
    Renders the view of a profile that was searched by username

    @param request: HttpRequestObj - current request.
    @param username: string - searched username

    @return rendered template with the given context
    """
    try:
        user = User.objects.get(username=username)
    except:
        raise Http404("Username does not exist", username)

    if request.user.is_authenticated():
        posts = Post.visible_posts_for(request.user) \
            .filter(author=user.pk) \
            .select_related('author', 'repost_original', 'reply_original')
    else:
        posts = Post.objects.filter(circles=PUBLIC_CIRCLE) \
            .filter(author=user.pk) \
            .select_related('author', 'repost_original', 'reply_original')

    for post in posts:
        post.set_post_extra(request)
        for reply in post.extra['replies']:
            reply.set_post_extra(request)
    
    context = {'posts': posts, 'user': user}

    return render(request, 'users/user_profile.html', context)