Example #1
0
    def post(self, request):
        post = Post()
        form = PostForm(request.POST, instance=post)

        try:
            author_blog = Blog.objects.get(user=request.user)
            # Asignamos el post al blog del usuario autenticado
            post.blog = author_blog

            if form.is_valid():
                post = form.save()
                form = PostForm()
                url = reverse("post_detail_page", args=[request.user, post.pk])
                message = "¡Post creado con éxito!"
                message += mark_safe('<a href={0}> Ver post </a>'.format(url))
                messages.success(request, message)

        except ObjectDoesNotExist:
            messages.add_message(
                request, messages.ERROR,
                "Este usuario no dispone de un blog asociado. Consulte con el administrador"
            )
            form = PostForm()

        return render(request, "post_form.html", {'form': form})
    def post(self, request):

        success_message = ""

        blogs_list = Blog.objects.filter(owner__username__exact=request.user.username)
        if len(blogs_list) == 1:
            post_in_blog = Post()
            post_in_blog.blog = blogs_list[0]  # asigno como propietario de la foto el usuario autenticado
            form = PostForm(
                request.POST, instance=post_in_blog
            )  # basa la instancia de la petición en la que yo te paso. Mezcla campos!!
            if form.is_valid():
                new_post = form.save()  # Crea, guarda y devuelve el objeto
                form = PostForm()  # lo inicializamos tras guardar para que aparezca vacío de nuevo
                # Creamos nuestro mensaje de éxito con el link a la foto
                success_message = "Guardado con éxito!!"
                success_message += '<a href="{0}">'.format(
                    reverse("post_detail", args=[request.user.username, new_post.pk])
                )
                success_message += "See post"
                success_message += "</a>"
            context = {"form": form, "success_message": success_message}
            return render(request, "blogs/new_post.html", context)
        else:
            return HttpResponseNotFound("Houston, we have a problem")
    def validate_attachment(self):

        post = Post()
        post.attachment = self.initial_data.get("file")

        if post.get_attachment_type() == post.NONE:
            raise serializers.ValidationError(_("Fichero de tipo incorrecto"))
 def post(self, request):
     post = Post()
     post.user = request.user  #select user autenticated
     form = PostForm(request.POST, request.FILES, instance=post)
     if form.is_valid():
         form.save()
         return redirect("home_page")
     return render(request, "create_post_form.html", {"form": form})
 def create(self, request):
     post = Post()
     post.user = request.user
     serializer = PostCreateSerializer(data=request.data, instance=post)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Example #6
0
    def post(self, request):
        post = Post()
        post.owner = request.user
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            new_post = form.save()
            messages.success(request, 'Post creado correctamente con ID {0}'.format(new_post.pk))
            form = PostForm()

        context = {'form': form}
        return render(request, 'blogs/new_post.html', context)
Example #7
0
 def post(self, request):
     blog_post = Post()
     blog_post.user = request.user
     form = PostForm(request.POST, instance=blog_post)
     if form.is_valid():
         post = form.save()
         form = PostForm()
         url = reverse("post_detail_page", args=[request.user, post.pk])
         message = "Post created successfully! "
         message += '<a href="{0}">View</a>'.format(url)
         messages.success(request, message)
     return render(request, "post_form.html", {'form': form})
Example #8
0
def create_tutorial_post_for_new_blog(sender, instance, created, **kwargs):
    if created:
        t = Tag.objects.get_or_create(blog=instance, name='Site Info')[0]

        post_template = get_template('blogs/rendered/post_sample_body.md')
        context = Context({})
        p = Post(
            blog=instance,
            title='Hello, World',
            body=post_template.render(context)
        )
        p.save()
        p.tags.add(t)
Example #9
0
 def post(self, request):
     post = Post()
     post.user = request.user
     # post.id = pk
     form = PostForm(request.POST, instance=post)
     if form.is_valid():
         post = form.save()
         form = PostForm()
         url = reverse("post_detail_page", args=[post.user.username, post.pk])
         message = "¡¡ Se ha creado una nueva entrada !!"
         message += '<a href="{0}">Ver</a>'.format(url)
         messages.success(request, message)
     return render(request, "post_form.html", {'form': form})
Example #10
0
def addBlog(request):
    if request.method == "POST":
        postTitle = request.POST['postTitle']
        postcontent = request.POST['postContent']
        postAuthorName = request.user  #request.POST['postAuthorName']
        postSlug = postTitle.replace(' ', '-')
        post = Post(title=postTitle,
                    author=postAuthorName,
                    content=postcontent,
                    slug=postSlug)
        post.save()
        return redirect('/blogs')
    else:
        return redirect('home')
Example #11
0
 def post(self, request):
     post = Post()
     post.user = request.user
     post.blog = request.user.blog
     form = PostForm(request.POST, instance=post)
     if form.is_valid():
         post = form.save()
         #vaciamos el formulario
         form = PostForm()
         url = reverse("post_detail", args=[post.user,post.pk]) #reverse genera url pasandole el tipo de URL
         message = " created successfully!"
         message += '<a href="{0}">Create your first post</a>'.format(url)
         #enviamos mensaje de exito con un enlace a la pelicula que acabamos de cr
         messages.success(request, message)
     return render(request, "post_form.html", {'form':form})
Example #12
0
def add_blog(request):
    if request.method == 'POST':
        form = BLOGENTRY(request.POST)
        if form.is_valid():
            form = form.cleaned_data
            a, b = Author(), Post()

            a.name, a.email = form['name'], form['email']

            if Author.objects.filter(email=form['name'],
                                     name=form['name']).count() == 0:
                a.save()

            b.title = form['title']
            b.date = timezone.now()
            b.author = a
            b.body = form['blog']
            b.save()

        return index(request)

    else:
        form = BLOGENTRY()

        return render(request, 'add_blog.html', {'form': form})
def populate_fake_data(N=5):
    for i in range(N):
        title = fake.sentence(nb_words=6,
                              variable_nb_words=True,
                              ext_word_list=None)
        body = " ".join(
            fake.texts(nb_texts=3, max_nb_chars=200, ext_word_list=None))
        created_on = fake.date_time_between(start_date='-2y',
                                            end_date='now',
                                            tzinfo=None)
        # updated_on = fake.date_time_between(start_date='-2y', end_date='now', tzinfo=None)
        post = Post(title=title, body=body, created_on=created_on)
        post.save()
        for cat in get_category():
            post.categories.add(cat)
        create_comments(post)
Example #14
0
    def test_create_comment(self):
        Comment.post = Post(title='Post being commented on')
        Comment.author = User(username='******')
        comment = Comment(author='James', text='This is my first test comment')

        self.assertEqual(comment.author, 'James')
        self.assertEqual(comment.text, 'This is my first test comment')
Example #15
0
    def post(self, request):
        """
        Procesa el formulario para la crear el anuncio
        :param request: objeto HttpRequest
        :return: HttpResponse con la respuesta
        """

        post = Post()
        post.owner = request.user
        form = PostForm(request.POST, request.FILES, instance=post)
        if form.is_valid():
            post = form.save()
            form = PostForm()
            messages.success(request, 'Anuncio creado correctamente')
        context = {'form': form}
        return render(request, 'blogs/form.html', context)
Example #16
0
def add_blog(request) :
	
	if request.method=='POST':
		form=BLOGENTRY(request.POST)
		if form.is_valid() :
			form=form.cleaned_data
			A=Post(title=form['title'],body=form['blog'],date=timezone.now(),author=Author.objects.get(handle=request.user.username))
			try :
				A.save()
			except IntegrityError as e:
				return render(request,'add_blog.html',{'form':BLOGENTRY(),'error':e.message})
			return index(request)
		else :
			return render(request,'add_blog.html',{'form':BLOGENTRY(),'error':'something went wrong..'})
	else :
		return render(request,'add_blog.html',{'form':BLOGENTRY()})
Example #17
0
    def test_doesnt_regenerate_slug_if_same_title(self):
        test_title = 'Test title'
        post = Post(title=test_title, author=self.new_user)
        post.generate_unique_slug()
        post.save()
        self.assertEqual(post.slug, 'test-title')

        post.save()
        self.assertEqual(post.slug, 'test-title')
Example #18
0
 def test_create_post(self):
     Post.author = User(username='******')
     post = Post(author='Max',
                 title='My first test post',
                 text='This is my first test post')
     self.assertEqual(post.author, 'Max')
     self.assertEqual(post.title, 'My first test post')
     self.assertEqual(post.text, 'This is my first test post')
Example #19
0
    def post(self, request, pk=None):
        post = Post(blog=request.user.blog)

        form = PostForm(request.POST, instance=post)

        if form.is_valid():
            if pk is not None:
                post.response = Post.objects.filter(pk=pk).first()
            form.save()
            send_email = self.need_send_email(post)
            if send_email:
                self.send_email_notification(post)
            return redirect(home)
        else:
            message = _("blogs.views.error_create_post")
            context = {"post": post, "form": form, "message": message}
            return render(request, 'blogs/post_new.html', context)
    def post(self, request):
        """
        Crea un post en base a la información POST. Con el decorador @login_required() nos va a ejecutar esta función
        solamente en el caso de que el usuario esté autenticado. En caso contrario, redirigirá a una url del paquete
        django.contrib.auth que redefinimos en el settings.py LOGIN_URL. Esta es la magia que hace Django para
        redireccionar al usuario a una url en el caso de que intente acceder a una url protegida sólo accesible si
        está autenticado.
        :param request: Objeto HttpRequest con la petición
        :return: HttpResponse
        """
        success_message = ''

        # Creo un post vacío y le asigno el blog actual.
        post_with_blog = Post()
        post_with_blog.blog = request.user.blog

        # Le pedimos al formulario que en vez de usar la instancia que él crea, utilice la que le
        # indicamos con el post_with_blog. Con esto, guarda la instancia con todos los campos del
        # formulario, excepto del blog, que coge el que le indicamos nosotros que ha sido creado.
        form = PostForm(request.POST, instance=post_with_blog)

        if form.is_valid():
            # Si se valida correctamente creamos objeto post, lo guardamos en DB y lo devolvemos
            # Obtenemos el blog del usuario autenticado para guardarlo automáticamente.
            new_post = form.save()

            # Reiniciamos formulario y componemos mensaje con enlace al nuevo post creado. Para acceder a una url
            # nombrada en un controlador utilizamos la función reverse, con los argumentos de la url nombrada, en este
            # caso, el nombre del blog, y la pk del post.
            # Como por defecto Django escapa el HTML, necesitamos indicar que el enlace al nuevo post no escape HTML.
            # Lo indicamos en la plantilla con el |safe en el mensaje. Lo normal es que este trabajo se haga en el
            # template
            form = PostForm()
            success_message = '¡Post creado con éxito!  '
            success_message += '<a href="{0}">'.format(reverse('post_detail', args=[new_post.blog, new_post.pk]))
            success_message += 'Ver post'
            success_message += '</a>'

        context = {
            'form': form,
            'success_message': success_message
        }

        return self.renderize(request, context)
Example #21
0
def fake_posts(count=50):
    for i in range(count):
        post = Post(
            title = fake.sentence(),
            body = fake.text(2000),
            category_id = random.randint(1, Category.query.count()),
            timestamp=fake.date_time_this_year()
        )
        db.session.add(post)
    db.session.commit()
Example #22
0
def api_create_blog_view(request):
    account = Account.objects.get(pk=1)
    post = Post(author=account)

    if request.method == "POST":
        serializer = PostSerializer(post, data=request.data)
        if serializer.is_valid():
            serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #23
0
 def setUp(self):
     self.posts = [
         Post(uuid=uuid.uuid4(),
              author='*****@*****.**',
              heading='post 1',
              content='post 1 content'),
         Post(uuid=uuid.uuid4(),
              author='*****@*****.**',
              heading='post 2',
              content='post 2 content')
     ]
     Post.objects.bulk_create(self.posts)
     self.author_user = User.objects.create_user(username='******',
                                                 password='******')
     self.author_user.author.is_author = True
     self.author_user.author.save()
     self.normal_user = User.objects.create_user(username='******',
                                                 password='******')
     self.url = reverse('blogs:new')
Example #24
0
 def post(self, request):
     """
     Crea un post en base a la información POST
     :param request:
     :return:
     """
     success_message = ""
     post_with_owner = Post()
     post_with_owner.owner = request.user
     form = PostForm(request.POST, instance=post_with_owner)
     if form.is_valid():
         # Guardamos el objeto post y lo devolvemos
         new_post = form.save()
         form = PostForm()
         success_message = "Post generado con éxito!"
         success_message += '<a href="{0}">'.format(reverse("post_detail", args=[new_post.owner, new_post.pk]))
         success_message += " Ver post"
         success_message += "</a>"
     context = {"form": form, "success_message": success_message}
     return render(request, "blogs/new_post.html", context)
Example #25
0
    def test_save(self):
        self.assertEqual(User.objects.count(), 0)

        new_user = User.objects.create_user(username='******', password='******')

        new_post = Post(author=new_user)
        form = PostModelForm({'title': 'Cats'}, instance=new_post)
        result = form.is_valid()
        form.save()

        self.assertTrue(result)
        self.assertEqual(User.objects.count(), 1)
Example #26
0
def newpost(request):
	if request.user.is_authenticated():
		if request.method == 'POST':
			titles= request.POST.get('title')
			data = request.POST.get('postdata')
			time=datetime.now()
			p = Post(title=titles,post=data,created=time)
			p.save()
			return HttpResponseRedirect("/")

		else:
			status = request.GET.get('status')
        		t = get_template('addpost.html')
			if status:
				html = t.render(Context({'message' : "Username already exists"}))
			else:
				html = t.render(Context({'message' : ""}))
			return HttpResponse(html)

	else:
		return HttpResponseRedirect("/")
Example #27
0
 def get(self, request):
     '''
     Post Form render. 
     If data are correct the form save the content if not sends a feedback.
     User must logged
     '''
     success_message = ''
     post = Post()
     post_form = PostForm()
     # Template context
     context = {'form': post_form, 'message': success_message}
     return render(request, 'blogs/post-create.html', context)
Example #28
0
 def delete_cascade(self, user):
     # delete comments
     user_comments = Comment.query(Comment.user == user.key)
     CommentDeleteMixin.delete_cascade_multi(self, user_comments)
     # delete posts
     user_posts = Post.query(Post.author == user.key)
     for post in user_posts:
         post.delete_cascade()
     # delete reactions
     user_reactions = Reaction.query(Reaction.user == user.key)
     ndb.delete_multi(user_reactions.fetch(keys_only=True))
     # finally, the user itself
     user.key.delete()
Example #29
0
    def post(self, request):
        """
        Publicar el post
        :param request: HttpRequest
        :return: HttpResponse
        """
        # Crear el post con los datos del POST
        post = Post(owner=request.user)
        form = PostForm(request.POST, instance=post)

        if form.is_valid():
            post.save()

            for genre in form.cleaned_data["genres"]:
                post.genres.add(genre)

            form = PostForm()
            message = 'Publicado'
        else:
            message = 'No se ha publicado'

        context = {"form": form, "message": message}
        return render(request, 'blogs/new_post.html', context)
Example #30
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Post Created Successfully', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html',
                           title='New Post',
                           legend='New Post',
                           form=form)
Example #31
0
    def content_html(self):
        '''直接渲染模板'''
        from blogs.models import Post
        from comment.models import Comment

        result = ''
        if self.display_type == self.DISPLAY_HTML:
            result = self.content
        elif self.display_type == self.DISPLAY_LATEST:
            context = {
                'posts': Post.latest_posts()
            }
            result = render_to_string('config/blocks/sidebar_posts.html', context)
        elif self.display_type == self.DISPLAY_HOT:
            context = {
                'posts': Post.hot_posts()
            }
            result = render_to_string('config/blocks/sidebar_posts.html', context)
        elif self.display_type == self.DISPLAY_COMMENT:
            context = {
                'comments': Comment.objects.filter(status=Comment.STATUS_NORMAL)
            }
            result = render_to_string('config/blocks/sidebar_comments.html', context)
        return result
    def post(self):
        data = request.get_json()
        subject = data.get('subject')
        content = data.get('content')
        tags = data.get('tags', [])

        user = g.user
        if subject and content:
            new_post = Post(author=user.key,
                            subject=subject,
                            content=content)
            # store it in DB
            new_post.put()
            new_post.add_tags(tags)
            new_post_key = new_post.key
            return (
                {'key': new_post_key.integer_id()},
                201,
                {'Location': api.url_for(UserBlogPostAPI,
                                         username=user.username,
                                         post_id=new_post_key.integer_id())},
            )
        else:
            return None, 400  # Bad Request
Example #33
0
    def post(self, request):
        success_message = ''

        # Creo un post vacío con el usuario para pasarselo al formulario
        # De este modo oculto el campo owner y lo cargo automaticamente.
        post_with_owner = Post()
        post_with_owner.owner = request.user
        form = PostForm(request.POST, instance=post_with_owner)

        if form.is_valid():
            # Creo el post con los datos del formulario y lo almaceno en nueva new_post
            new_post = form.save()
            form = PostForm()
            success_message = 'Guardado con exito!'
            success_message += '<a href="{0}">'.format(reverse('post_detail', args=[new_post.owner, new_post.pk]))
            success_message += 'Ver post'
            success_message += '</a>'

        context = {
            'form': form,
            'success_message': success_message
        }

        return render(request, 'blogs/post_create.html', context)
Example #34
0
 def create(self, validated_data):
     user_id = self.context.get("user_id")
     category_ids = self.context.get("category")
     categories = []
     if category_ids != ['']:
         categories = Category.objects.filter(id__in=category_ids)
     user = User.objects.get(id=user_id)
     post = Post(**validated_data)
     post.blog = self.get_user_blog(user)
     post.save()
     for cat in categories:
         post.category.add(cat)
     post.save()
     return post
Example #35
0
 def get_user_base_context(self, user):
     username = user.username
     return OrderedDict([
         ("username", username),
         ("id", user.key.integer_id()),
         ("uri", urls.get_user_uri(username)),
         ("email", user.email),
         ("full_name", user.full_name),
         ("bio", user.bio),
         ("blogsposts_count", Post.query(Post.author == user.key).count()),
         ("blogposts_uri", urls.get_user_blogposts_uri(username=username)),
         ("reactions_uri", urls.get_user_reactions_uri(username=username)),
         ("comments_uri", urls.get_user_comments_uri(username=username)),
         ("is_active", user.is_active),
         ("is_admin", user.is_admin),
         ("joined", datetime.strftime(user.joined, TIME_FMT)),
         ("last_updated", datetime.strftime(user.last_updated, TIME_FMT)),
     ])
Example #36
0
    def post(self, request):
        """
        Presenta el formulario para crear una foto y, en caso de que la petición sea POST la valida
        y la crea en caso de que sea válida
        :param request: objeto HttpRequest con los datos de la petición
        :return: objeto HttpResponse con los datos de la respuesta
        """
        message = None
        post_with_user = Post(owner=request.user)
        post_form = PostForm(request.POST, instance=post_with_user)
        if post_form.is_valid():
            new_post = post_form.save()
            post_form = PostForm()
            message = 'Foto creada satisfactoriamente. <a href="{0}">Ver foto</a>'.format(
                reverse('photos_detail', args=[new_post.pk])
            )

        context = {'form': post_form, 'message': message}
        return render(request, 'photos/photo_creation.html', context)
 def get(self):
     posts = Post.query().order(-Post.created)
     return [self.get_post_context(p) for p in posts]
 def get(self, username):
     user = get_user_by_username_or_404(username)
     posts = Post.query(Post.author == user.key).order(-Post.created)
     return [self.get_post_context(p) for p in posts]