Beispiel #1
0
def update(request, id):
	form = PostForm(request.POST, instance=Post.objects.get(pk=id))
	if form.is_valid():
		post = form.save()
		post.add_tags(request.POST['tags'])
		return redirect(post.uri())
	return render(request, 'blog/edit.html', {'post':post})
def new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user

            post.ip = request.META['REMOTE_ADDR']

            # AWS Load Balancer 를 쓸 경우
            # settings.USE_X_FORWARDED_HOST = True 여야,
            # HTTP_X_FORWARDED_HOST META 정보에 값이 설정됩니다.
            # post.ip = request.META['HTTP_X_FORWARDED_HOST']

            post.save()

            # post.author = request.user
            # post = form.save(commit=False)
            # post.category = get_object_or_404(Category, pk=1)
            # post.save()
            return redirect(post)
    else:
        form = PostForm()
    return render(request, 'blog/form.html', {
        'form': form,
    })
Beispiel #3
0
 def post(self, request, *args, **kwargs):
     print "post"
     create_post = PostForm(request.POST)
     if create_post.is_valid():
         print "valid"
         create_post.save()
     return HttpResponseRedirect("/")
Beispiel #4
0
def show_index(request):
    user = User.objects.get(username='******')
    context = {}

    if request.method == 'POST':
        form = PostForm(request.POST)
        context['form'] = form
        #import pdb;pdb.set_trace()
        if form.is_valid():
            title = form.cleaned_data['title']
            text = form.cleaned_data['text']
            post = Post(title=title, text=text)
            post.author = user
            post.save()

            return redirect(reverse('posts-index'))
    else:
        form = PostForm()
        context['form'] = form

    posts = Post.objects.all()
    context['posts'] = posts

    #return HttpResponse(json.dumps(data), content_type='application/json')
    return render(request, 'posts.html', context)
Beispiel #5
0
def post_edit(request, pk):

    # To check that the post is existing or not
    post = get_object_or_404(Post, pk=pk)
#    post = Post.objects.get(pk=pk)
    # To check about user
    if request.user != post.author:
        return redirect('blog.views.errors')

    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
#            post.published_date = timezone.now()
            post.save()
            if request.FILES.getlist("images", []):
                for resource in post.resources.all():
                    resource.delete()
                for image in request.FILES.getlist("images", []):
                    photo = Resource(post=post, image_file=image)
                    photo.save()
                return redirect('blog.views.post_detail', pk=post.pk)
            else:
                return redirect('blog.views.post_detail', pk=post.pk)
    else:
        postForm = PostForm(instance=post)
        formset = ResourceForm(instance=post)
    return render(request, 'blog/post_edit.html', {'postForm': postForm, 'formset': formset}, context_instance=RequestContext(request))
Beispiel #6
0
def edit(request, pk=0, template_name="blog/edit.html"):
  """ Edit a post """
  user = request.user
  post = None
  posts = Post.objects.all()
  if request.user.is_superuser:
    if pk:
      post = get_object_or_404(Post, pk=pk)
      posts = Post.objects.exclude(id=post.pk)
    posts = posts.filter(status__in=['draft', 'published'])
  else:
    if pk:
      post = get_object_or_404(Post, pk=pk, user=request.user)
      posts = Post.objects.exclude(id=post.pk)
    posts = posts.filter(user=request.user,status__in=['draft', 'published'])

  posts = posts.order_by('-pk')
  if post:
    user = post.user
  kwargs = dict(instance=post,user=user,initial={'publish_dt':datetime.datetime.now()})
  form = PostForm(request.POST or None, **kwargs)
  if request.POST and form.is_valid():
    post = form.save()
    messages.success(request,'Edited post "%s".' % post)
    return HttpResponseRedirect("/blog/admin/edit/%s/"%post.id)

  values = {
    'form': form,
    'post': post,
    'posts': posts,
    }
  return TemplateResponse(request, template_name, values)
Beispiel #7
0
def add():
    form = PostForm(request.form)
    if request.method == "POST" and form.validate():
        post = Post(title=form.title.data, slug=form.slug.data, content=form.content.data)
        post.put()
        return redirect(post.get_url())
    return render_template("form.html", form=form, section="add")
Beispiel #8
0
def post_new(request):

#    ImageFormSet = modelformset_factory(Resource, form=ResourceForm, extra=3)

    if request.method == "POST":
        postForm = PostForm(request.POST)
        formset = ResourceForm(request.POST, request.FILES)
        if postForm.is_valid():
            post = postForm.save(commit=False)
            post.author = request.user
            post.save()
            for image in request.FILES.getlist("images", []):
 #               img = image_resizing(image)
                photo = Resource(post=post, image_file=image)
                photo.save()
            return redirect('blog.views.post_detail', pk=post.pk)
        #        for form in formset.cleaned_data:
        #            image = form['image_file']
        #            photo = Resource(post=post, image_file=image)
        #            photo.save()

    else:
        postForm = PostForm()
        formset = ResourceForm()
        return render(request, 'blog/post_edit.html', {'postForm': postForm, 'formset': formset}, context_instance=RequestContext(request))
Beispiel #9
0
    def post(self, request, slug=None, *args, **kwargs):
        if not users.is_current_user_admin():
            return HttpResponseForbidden()

        post = self.get_object()
        if not post and slug:
            raise Http404()

        form = PostForm(request.POST)
        if not form.validate():
            error_msg = [
                "There are problems with the form:",
            ]
            error_msg = itertools.chain(error_msg, *form.errors.values())

            return HttpResponseBadRequest("<br/>".join(error_msg))

        # title has to exit at that point due to the validators
        new_slug = slugify(form.data["title"])
        if slug is None and Post.get_by_slug(new_slug):
            return HttpResponseBadRequest("Post with this title alread exit")

        created = False
        if not post:
            created = True
            post = Post()

        form.populate_obj(post)
        post.author = users.get_current_user().nickname()
        post.put()

        context = self.get_context_data(post=post, short=created)
        return self.render_to_response(context)
Beispiel #10
0
def edit(request, pk):
    post = get_object_or_404(Post, pk=pk)

    # 수정하려는 사용자와 작성한 유저가 다르면 에러
    if post.author != request.user:
        pass

    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save()

            # post = form.save(commit=False)
            # post.author = request.user
            # post.save()

            # 만약 폼에서 지정하지 못한 필수 필드가 있다면 아래와 같이
            # 서버딴에서 필수 필드의 기본값을 설정하여 주는 방법으로 해결
            # post = form.save(commit=False)
            # post.category = get_object_or_404(Category, pk=1)
            # post.save()

            # return redirect('blog:detail', post.pk)

            # models.py에서 get_absolute_url 함수가 정의된 경우 post만 넘겨도 가능하다.
            return redirect(post)
    else:
        form = PostForm(instance=post)
    return render(request, "blog/form.html", {"form": form})
def post_update(request, post_id=None):

    if not post_id:
        return redirect('blog:index')

    title = 'DevInCafe | UPDATE'
    context = {
        'WEB_TITLE': title,
    }

    try:
        post = Post.objects.get(id=post_id, author=request.user)
    except ObjectDoesNotExist:
        return redirect('blog:index')

    if request.method == 'POST':
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            form.save()
            return redirect('blog:index')
    else:
        form = PostForm(instance=post)

    context.update({'form': form})
    return render(request, 'blog/pages/add_post.html', context)
Beispiel #12
0
def create_post(request, slug):
    blog = get_object_or_404(Blog, slug=slug)

    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            slug = generate_slug(post.title)

            conflicts = Post.objects.filter(slug__startswith=slug)
            if conflicts:
                slug = get_unique_slug(slug, conflicts)

            post.slug = slug
            post.author = request.user
            post.blog = blog
            post.save()

            # We don't want to start sending garbage requests while testing,
            # and we only want to do this on the first save of a published post,
            # not every update, otherwise we might get IP banned.
            if not settings.DEBUG:
                post.send_pingbacks()

            return redirect('view_post', post.created.year, post.get_formatted_month(), post.slug)
    else:
        form = PostForm()

    context = {
        'blog': blog,
        'post_form': form,
    }
    return render_to_response('blog/create_post.html', context, RequestContext(request))
Beispiel #13
0
def view_post(request, post_id):
    form = PostForm()
    blog_post = BlogPost.get_by_id(int(post_id))
    if request.method == 'POST':
        submitted_form = PostForm(request.POST)
        if submitted_form.is_valid():
            title = submitted_form.cleaned_data['title']
            body = submitted_form.cleaned_data['body']
            comment = Comment(title=title, body=body,
                    parent=blog_post)
            comment.put()
            return redirect(request.path)
        else:
            form = submitted_form
    comments = Comment.all()
    comments.ancestor(blog_post.key())
    comments.order('-created')
    return render(request, 'post_detail.html', {
        'post': blog_post,
        'comments': comments,
        'form': form,
        'auth_string': _get_auth_string(request.path),
        'current_user': users.get_current_user(),
        'is_admin': users.is_current_user_admin(),
        })
Beispiel #14
0
def edit_blog_post(request, post_id, post_slug):
    """Render the page edit an existing post."""
    post = get_object_or_404(Post, id=post_id, slug=post_slug)
    current_user = request.user

    # Only the author can edit the post, and the author must still be listed
    # as a contributor.
    if (current_user != post.author or
            current_user not in post.blog.authors.all()):
        raise Http404

    if request.method == 'POST':
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            return save_post_and_redirect(form, request)

    else:
        form = PostForm(instance=post)
        form.fields['author'].widget = forms.HiddenInput()

        # Limit blogs dropdown to those the current user can edit
        blogs = Blog.objects.filter(authors__in=[current_user])
        form.fields['blog'].queryset = blogs

    context = {'form': form, 'post': post}
    return render(request, 'edit_post.html', context)
Beispiel #15
0
def new_blog_post(request):
    """Render the page to create a new post."""
    current_user = request.user

    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            # TODO: I think this check is overkill, but maybe good to have
            if (current_user != form.cleaned_data['author'] or
                    current_user not in
                    form.cleaned_data['blog'].authors.all()):
                raise Http404
            return save_post_and_redirect(form, request)

    else:
        blogs = Blog.objects.filter(authors__in=[current_user])

        if 'blog' in request.GET:
            blog = get_object_or_404(Blog, slug=request.GET.get('blog'))
            if blog not in blogs:
                blog = None
        else:
            blog = None

        form = PostForm(initial={'blog': blog, 'author': current_user})
        form.fields['author'].widget = forms.HiddenInput()
        form.fields['blog'].queryset = blogs

    context = {'form': form}
    return render(request, 'new_post.html', context)
Beispiel #16
0
def admin_edit_post(request, post_id):
    
    if users.is_current_user_admin():
        
        post = Post.get_by_id(int(post_id))
        if not post:
            raise Http404
        
        if request.method == 'GET':
            tp = Tag_Post.all().filter('post', post)
            
            tags = ''
            # Get all tags
            for tag in tp:
                tags += tag.tag.title + ','
                
            form = PostForm({'title':post.title, 'category':post.category.key(), 'content':post.content, 'tags':tags})
            
        elif request.method == 'POST':
            
            form = PostForm(request.POST)
            
            if form.is_valid():
                
                # delete related tag_post
                for tp in post.tags:
                    tp.delete()

                p = form.save(commit=False)
                post.author = users.get_current_user()
                post.category = p.category
                post.content = p.content
                post.put()

                # add tag_post
                tagText = request.POST['tags']
                if tagText:
                    tags = tagText.split(',')
                    for tag in tags:
                        if tag:
                            tag = string.lower(string.strip(tag))

                            t = Tag.all().filter("title = ", unicode(tag, "utf-8")).get()
                            if not t:

                                t = Tag(title=unicode(tag, "utf-8"))
                                t.put()
                            Tag_Post(tag=t, post=post).put()

            return HttpResponseRedirect('/admin')
        
        return render_to_response('admin/edit.html',
                                      dictionary={ 'form':form,
                                                    'type': 'Edit Post',
                                                     },
                                      context_instance=RequestContext(request)
                                    )
    else:
        return HttpResponseRedirect('/')
Beispiel #17
0
def add_post(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        post = form.save(commit=False)
        post.author = request.user
        post.save()
        return redirect(post)
    return render_to_response('add_post.html',{ 'form': form },context_instance=RequestContext(request))
Beispiel #18
0
def edit(post_id):
    post = Post.get_by_id(post_id)
    form = PostForm(request.form, obj=post)
    if request.method == "POST" and form.validate():
        form.populate_obj(post)
        post.put()
        return redirect(post.get_url())
    return render_template("form.html", form=form)
Beispiel #19
0
 def post(self, request, slug):
     form = PostForm(request.POST, instance=self.postobj, request=request)
     if form.is_valid():
         newpost = form.save()
         return HttpResponseRedirect(reverse('post', args=[newpost.slug,]))
     return render(request, self.template_name, {
         'form': form
     })
Beispiel #20
0
def add_post(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        post = form.save(commit=False)
        post.id = None
        post.author = request.user
        post.save()
        return redirect('/blog/archive')
    return render(request, 'blog/add_post.html', {'form': form})
Beispiel #21
0
def index(request):
    print("DIGGU >>>>>>>>>>>>>>>>>>>>>>>")
    if request.method == "GET":
        form_post = PostForm()
        return render(request, 'form.html', {'form': form_post.as_table()})
    elif request.method == "POST":
        form_post = PostForm(request.POST)
        form_post.save()
        return render(request, 'index.html', {})
def add_post(request,blog):
    post=Post(author=request.user)
    form=PostForm(data=request.POST or None, instance=post)
    if form.is_valid():
        post=form.save()
        return HttpResponseRedirect('/blog/preview/%d/'%post.id)
    return render_to_response('blog/edit_post.html',
                              {'form':form,},
                              context_instance =  RequestContext(request)) 
Beispiel #23
0
def create(request):
	form = PostForm(request.POST)
	if form.is_valid():
		post = form.save()
		post.add_tags(request.POST['tags'])
		return redirect(post.uri())
	else:
		logging.error(form.errors)
	return render(request, 'blog/edit.html', {'post':form.instance})
Beispiel #24
0
 def add(self, request, *args, **kwargs):
     form = PostForm(data=request.POST if request.POST else None, files=request.FILES if request.POST else None)
     if form.is_valid():
         post = form.save(commit=False)
         post.blog = request.blog
         post.user = request.user
         post.save()
         return HttpResponseRedirect(request.blog.get_url())
     return {"post_add_form": form}
Beispiel #25
0
def post_new(request):
	if request.method == 'POST':
		form = PostForm(request.POST, request.FILES)
		if form.is_valid():
			post = form.save()
			return redirect('blog:post_detail', post.pk)
	else:
		form = PostForm()
	return render(request, 'blog/post_form.html', {'form':form,})
Beispiel #26
0
def edit_post(request, post_id):
    blog_entry = get_object_or_404(BlogEntry, pk=post_id)
    if request.method == 'POST':
        form = PostForm(request.POST, instance=blog_entry)
        if form.is_valid():            
            form.save()
            return render_to_response('viewpost.html', {'blog_entry': blog_entry})
    form = PostForm(instance=blog_entry)
    csrfContext = RequestContext(request, {'form':form, 'blog_entry':blog_entry})
    return render_to_response('editpost.html', csrfContext)
Beispiel #27
0
def form2(request):
    
    if request.method == 'GET':
        return render(request, 'form2.html', { 'form' : PostForm(), 'site_header' : 'THIS' })
    elif request.method == 'POST':
        form_post = PostForm(request.POST)
        if form_post.is_valid():
            form_post.save()
            return redirect('/blog/')
        return render(request, 'form2.html', { 'form' : form_post })
Beispiel #28
0
def post_edit(request, pk):
	post = get_object_or_404(Post, pk=pk)
	if request.method == 'POST':
		form = PostForm(request.POST, request.FILES, instance=post)
		if form.is_valid():
			post = form.save()
			return redirect(post)
	else:
		form = PostForm(instance=post)
	return render(request, 'blog/post_new.html', {'form':form})
Beispiel #29
0
def add_post(request):
  if request.method == 'POST':
    form = PostForm(request.POST)
    if form.is_valid():
      form.save()
      post = Post.objects.get(title=form.cleaned_data['title'])
      return HttpResponseRedirect(reverse('blog.views.get_post',args=(post.slug,)))
  else:
    form = PostForm()
  return render_to_response('post_form.html', {'form':form, 'new':True}, RequestContext(request))
Beispiel #30
0
def post_new(request):
    form = PostForm()
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
        else:
            return redirect('post_edit')
    return render_to_response('blog/post_edit.html', {'form': form}, RequestContext(request))
Beispiel #31
0
 def get(self, request, post_id):
     post = Post.objects.get(id=post_id)
     if request.user != post.user:
         raise PermissionDenied
     if request.GET.get('delete'):
         file_id = request.GET.get('delete')
         f = File.objects.get(id=file_id)
         f.on_delete = True
         f.save()
     if request.GET.get('restore'):
         file_id = request.GET.get('restore')
         f = File.objects.get(id=file_id)
         f.on_delete = False
         f.save()
     post_form = PostForm(instance=post)
     file_form = FileForm()
     return render(request,
                   'blog/create_edit_post.html',
                   context={
                       'post_form': post_form,
                       'title': 'Редактировать запись',
                       'post': post,
                       'file_form': file_form
                   })
Beispiel #32
0
def post_delete(request,post_pk):
    if request.method == 'POST':
        form = PostForm(request.POST)
        lgr.info(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.creator = request.user
            post.site = request.site
            post.save()
            lgr.info("Created New Post: {}".format(post))

        return redirect(reverse('admin:posts:list'))
    else:
        form = PostForm()

    context = {
        'form': form
    }
    return render(request, 'blog/post/create.html', context)
def post_create(request):
    post_form = PostForm(request.POST)
    if request.method == "POST":

        if post_form.is_valid():
            instance = post_form.save(commit=False)
            instance.user = request.user
            instance.save()
            ErrorLogging.objects.create_error('A new post was created by ' +
                                              str(instance.user.username) +
                                              ' the post is titled ' +
                                              str(instance.title))
            return redirect('/blog')
        else:
            print(post_form.errors)
    else:
        post_form = PostForm()
    args = {'post_form': post_form}
    return render(request, 'blog/post_create.html', args)
Beispiel #34
0
def post_new(request):
    # GET request doesnt allow you to submit forms! /// POST == EX: changing something (text)
    if request.method == 'POST':
        # requesting form from forms.py (title and text)
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            # The user is automatically the author
            post.author = request.user
            post.save()
            # using redirect instead of render so when you refresh page it doesnt submit the form again
            return redirect('post_detail', pk=post.pk)
    else:
        # the else is basically saying run this code if its a GET request
        # form is calling the post_edit.html form, which equals the PostForm function
        form = PostForm()
        # a new stuff_for_frontend except with the form
        stuff_for_frontend = {'form': form}
    return render(request, 'blog/post_edit.html', stuff_for_frontend)
Beispiel #35
0
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(
                commit=False
            )  #save but do not commit to the database yet until user has been confirmed
            # print("before, ", post)
            post.author = request.user
            #post.published_date = timezone.now()
            # print("after, ", post)
            post.save()
            return redirect('blog:post_detail', pk=post.pk)
    else:
        form = PostForm()
    template_name = 'blog/post_edit.html'
    context = {
        'form': form,
    }
    return render(request, template_name, context)
Beispiel #36
0
def create_post(request):
    if request.method == "POST":
        post_form = PostForm(data=request.POST)
        if post_form.is_valid():
            new_article = post_form.save(commit=False)
            new_article.author = User.objects.get(id=request.user.id)
            new_article.categories = Category.objects.get(
                id=request.POST['categories'])
            new_article.save()
            return redirect('blog:index')
        else:
            return HttpResponse('表单信息有误,请重新输入~')
    else:
        post_form = PostForm()
        categories = Category.objects.all()
        context = {
            'post_form': post_form,
            'categories': categories,
        }
        return render(request, 'blog/create.html', context)
Beispiel #37
0
def post_edit(request, pk):
    resp, form = None, None
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            if post.published_date is None:
                post.publish()
            else:
                post.save()
            resp = redirect('post_detail', pk=post.pk)

    if form is None:
        form = PostForm(instance=post)
    if resp is None:
        resp = render(request, 'blog/post_edit.html', {'form': form})

    return resp
def create_hail(request):
    if not request.user.is_authenticated:
        return HttpResponseRedirect('accounts/login')

    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            message = f"Your hail has been added!"
            messages.add_message(request, messages.SUCCESS, message)

            return redirect('home')
    else:
        form = PostForm()

    return render(request, 'posts/create_post.html', {
        'form': form,
    })
Beispiel #39
0
def post_update(request, pk):
    post = get_object_or_404(Post, pk=pk)

    # If request is POST, create a bound form(form with data)
    if request.method == "POST":
        f = PostForm(request.POST, instance=post)

        # check whether form is valid or not
        # if the form is valid, save the data to the database
        # and redirect the user back to the update post form

        # If form is invalid show form with errors again
        if f.is_valid():
            f.save()
            return redirect(reverse('post_update', args=[post.id]))

    # if request is GET the show unbound form to the user, along with data
    else:
        f = PostForm(instance=post)

    return render(request, 'cadmin/post_update.html', {
        'form': f,
        'post': post
    })
Beispiel #40
0
def edit_post(
    request,
    pk,
):
    if request.method == "GET":
        instance = Post.objects.get(pk=pk)
        context = {
            'form': PostForm(instance=instance),
            'next': request.GET.get('next', reverse('all-blog-posts')),
        }
        return render(request, 'edit_post.html', context)

    elif request.method == "POST":
        instance = Post.objects.get(pk=pk)
        form = PostForm(request.POST, request.FILES, instance=instance)
        if form.is_valid():
            form.save()
            next = request.GET.get('next', reverse('all-blog-posts'))
            return HttpResponseRedirect(next)

    context = {
        'form': PostForm(request.POST, instance=instance),
    }
    return render(request, 'edit_post.html', context)
Beispiel #41
0
def post_edit(request, pk):
    # 글을 수정해야 하기 때문에 기존에 입력되어 있던 자료를 가져오는게 먼저임.
    post = get_object_or_404(Post, pk=pk)
    # get방식 post방식 구분
    if request.method == "POST":
        # post 방식인 경우는 기존 자료 post에 새로 들어온 정보를 덮어씌움.
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            # published_date를 다시 현재 서버시간으로 변경.
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        # 만약 post방식이 아닌 경우라면 get방식 이므로 수정 직전임
        # 따라서 폼으로 다시 연결해줘야함. 이 떄 의 폼은 수정용 폼이며
        # 수정용 폼에는 기존에 써놨었던 글이 먼저 입력되어 있어야 하므로
        # 감안해서 기존 글의 내용이 담겨있는 post를 폼에 instance로 넘겨줌
        form = PostForm(instance=post)
    return render(request, 'blog/post_edit.html', {'form': form})
Beispiel #42
0
def post_edit(request, post_id):
    if Post.objects.filter(id=post_id):
        post = get_object_or_404(Post, id=post_id)
        if request.method == "POST":
            form = PostForm(request.POST, instance=post)
            if form.is_valid():
                post = form.save(commit=False)
                words = post.content.split()
                if len(words) > 42:
                    msg = 'Max allowed words are 42.'
                    return JsonResponse({'message': msg})
                post.save()
                return redirect(post.get_absolute_url())
        elif post.author.user.username == request.user.username:
            form = PostForm(instance=post)
            return render(request, 'blog/post/create_post.html',
                          {'form': form})
        else:
            return JsonResponse({'message': 'You can\'t edit this post'})
    else:
        return JsonResponse({'message': 'Post not found'})
Beispiel #43
0
def new_post(request):
    # Http 请求包括 POST 和 GET 两种,一般提交数据都是用 POST 请求
    # 因此当 request.method 为 POST 的时候才需要处理表单数据
    if request.method == 'POST':
        # 用户提交的信息存在 request.POST 中,相当于一个字典取值
        form = PostForm(request.POST)
        # 判断表单是否有效,django 自动校验表单数据是否合理,根据模型的字段类型来判断
        if form.is_valid():
            # commit=False 表示只生成模型类的实例,不马上保存到数据库
            post = form.save(commit=False)
            # 将作者和文章进行关联
            post.author = request.user
            # 通过调用 save() 方法将数据存入数据库
            post.save()
            # return render('post_detail', pk=post.pk)
            # 如果模型类中定义了 get_absolute_url 方法,可以用以下方式跳转
            # 会直接跳转 get_absolute_url 方法所指向的地址
            return redirect(post)
    else:
        # 如果不是 POST 重定向到空白的新建页面
        form = PostForm()
    return render(request, 'blog/post_new.html', locals())
Beispiel #44
0
def post_edit(request, pk):
    ## use 'get_object_or_404' to take you to the post if it is exist, if not send you to 404 page
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        # use 'instance' way because we need to update existing form not create new one
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            # to create the post data inside the data base but not save it yet
            post = form.save(commit=False)
            # to set the author to who ever create the post
            post.author = request.user
            # to  set the publish date to time we create the post
            #post.published_date = timezone.now()
            # to save the post date inside the data base
            post.save()
            # to take you to post detail page when you submit the post
            # we add redirect to take you in other page, because if you refresh the page will let you create the post again, need to use redirect method in case you have page of checkout because you don't want to pay money every time you refresh the page
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)
        stuff_for_frontend = {'form': form, 'post': post}
    return render(request, 'blog/post_edit.html', stuff_for_frontend)
Beispiel #45
0
def post_edit(request, pk):

    if request.user.is_superuser:
        post = get_object_or_404(Post, pk=pk)

    else:
        query = Post.objects.filter(author=request.user)
        post = get_object_or_404(query, pk=pk)

    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            if not post.publish_time:
                if post.status == 'published':
                    post.publish_time = timezone.now()

            soup = BeautifulSoup(post.text, 'html.parser')
            images = soup.find_all('img')
            para = soup.findAll(text=re.compile('^.+$'))
            para = " ".join(para)
            post.excerpt_text = para[0:500]
            # para = " ".join(para)
            if images:
                imageUrl = images[0].get('src')
                post.home_image = imageUrl

            post.updated = timezone.now()
            print("###################################")
            post.save()
            return HttpResponseRedirect(reverse('blog:dashboard'))

        else:
            return render(request, 'blog/post_edit.html', {'form': form})
            # return JsonResponse(form.errors,status=400)
    else:
        form = PostForm(instance=post)
    return render(request, 'blog/post_edit.html', {'form': form})
Beispiel #46
0
def post_new(request):
    # request.method는 현재 이 함수를 실행하기 위해 들어온 요청이
    # POST 방식이라면 문자열 "POST"를 , GET방식이라면 "GET"
    # 를 출력한다. 따라서 POST 방식인지를 구분부터 해준다.
    if request.method == "POST":
        # form 변수에 빈 칸이 채워진 Form 양식을 받아옴
        form = PostForm(request.POST)
        # .is_valid()는 form에서 요청한 자료가 모두 기입되었는지
        # 체크한느 매서드, 만약 모두 기입되지 않았다면 False
        # 모두 기입되었다면 True를 반환한다.
        if form.is_valid():
            # .save()는 아무것도 입력을 안하면 DB에 바로
            # 데이터를 적재해버리기 때문에 우선 form 양식 이외에
            # 작성자, 퍼블리싱 시간을 추가 적재하기 위해 임시로
            # DB에 올리기만 하기 위해 commit=False
            post = form.save(commit=False)
            # 현재 로그인된 유저를 글쓴이 정보에 저장
            post.author = request.user
            # 퍼블리싱 날짜는 현재 시간으로 저장
            post.published_date = timezone.now()
            # 모든 작업 완료 후 실제 DB에 저장
            post.save()
            # POST방식으로 들어왔으며, 자료 적재도 완전히 끝나면
            # 쓴 글을 확인할 수 있는 상세페이지로 이동
            # redirect('url 패턴', 우아한 url변수명=넣을자료)
            return redirect('post_detail', pk=post.pk)

    # 폼 작성시 어떤 양식을 따라갈 것인지 지정
    # 현재 우리가 forms.py에 작성한 PostForm을 활용해
    # 폼을 자동으로 구성할 예정임
    else:
        # get 방식으로 들어오는 경우는 자료를 반영하지 않고
        # 그냥 다시 post방식 작성을 유도하기 위해 폼으로
        # 이동시키는 로직 실행
        form = PostForm()
    # render에서는 먼저 템플릿 파일 연결 후 폼 정보를 가진
    # form 변수를 같이 넘겨준다.
    return render(request, 'blog/post_edit.html', {'form': form})
Beispiel #47
0
def post_add(request):
    if request.method == "POST":
        request.POST = request.POST.copy()
        request.POST["author"] = request.user.pk
        # request.POST["status"] = "published"
        form = PostForm(request.POST, request.FILES)
        # import pdb; pdb.set_trace()
        if form.is_valid():
            instance = form.save()
            # import pdb; pdb.set_trace()
            if request.POST["action"] == "published":
                return redirect(instance.get_absolute_url())
            elif request.POST["action"] == "draft":
                return redirect(reverse("blog:my_stories"))
    template = "blog/posts/new_post.html"

    form = PostForm()
    tags = Tag.objects.all()
    # import pdb; pdb.set_trace()

    categories = PostCategory.approved.all()
    context = {"form": form, "categories": categories, "tags": tags}
    return render(request, template, context)
Beispiel #48
0
def admin_add_post(request):

    if users.is_current_user_admin():
        if request.method == 'GET':
            form = PostForm()

        elif request.method == 'POST':
            form = PostForm(request.POST)

            if form.is_valid():
                post = form.save(commit=False)
                post.author = users.get_current_user()
                post.put()

                tagText = request.POST['tags']
                tags = tagText.split(',')
                for tag in tags:
                    if tag:
                        tag = string.lower(string.strip(tag))

                        t = Tag.all().filter("title = ",
                                             unicode(tag, "utf-8")).get()
                        if not t:
                            t = Tag(title=unicode(tag, "utf-8"))
                            t.put()
                        Tag_Post(tag=t, post=post).put()

                return HttpResponseRedirect('/admin')

        return render_to_response('admin/edit.html',
                                  dictionary={
                                      'form': form,
                                      'type': 'Add Post',
                                  },
                                  context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/')
Beispiel #49
0
def post_new(request):
    # works when you submit a post
    # checking when you create post by method POST pass the information you input to them on the form
    if request.method == 'POST' :
        form = PostForm(request.POST)
        # to check if the user put valid text inside the fields , to make sure doesn't try to hack us or so
        if form.is_valid():
            # to create the post data inside the data base but not save it yet
            post = form.save(commit=False)
            # to set the author to who ever create the post
            post.author = request.user
            # to  set the publish date to time we create the post
            #post.published_date = timezone.now()
            # to save the post date inside the data base
            post.save()
            # to take you to post detail page when you submit the post
            # we add redirect to take you in other page, because if you refresh the page will let you create the post again, need to use redirect method in case you have page of checkout because you don't want to pay money every time you refresh the page
            return redirect ('post_detail', pk=post.pk)
    # work when you go to  page to create the post
    else:
        form = PostForm()
        # save value of variable above(form) in stuff_for_frontend to return it to the page
        stuff_for_frontend = {'form': form}
    return render(request, 'blog/post_edit.html' , stuff_for_frontend)
Beispiel #50
0
def post(request, user_id):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.text = form.cleaned_data['text']
            post.title = form.cleaned_data['title']
            post.user_id = user_id
            post.save()

            files1 = request.FILES.getlist('img')
            for file in files1:
                img = Pic(image=file, post=post)
                img.save()
            files2 = request.FILES.getlist('video')
            for file in files2:
                vid = Video(content=file, post=post)
                vid.save()
        return redirect('blog:show')

    else:
        form = PostForm()
        user = User.objects.get(id=user_id)
        return render(request, 'blog/blogEdit.html', {'user':user, 'form': form})
Beispiel #51
0
def edit_post(request, post_id):
    post = get_object_or_404(Post, pk=post_id)
    if request.method == "POST":
        new_post_form = PostForm(request.POST, instance=post)
        if new_post_form.is_valid():
            post = new_post_form.save(commit=False)
            post.title = new_post_form.cleaned_data['title']
            post.text = new_post_form.cleaned_data['text']
            post.mod_date = datetime.datetime.now()
            post.save()

            files1 = request.FILES.getlist('img')
            for file in files1:
                img = Pic(image=file, post_id=post_id)
                img.save()
            files2 = request.FILES.getlist('video')
            for file in files2:
                vid = Video(content=file, post_id=post_id)
                vid.save()

            return redirect(reverse('blog:post_detail', args=(post_id,)))
    else:
        new_post_form = PostForm(instance=post)
        return render(request, 'blog/blogEdit.html', {'new_post_form': new_post_form, 'post_id':post_id})
Beispiel #52
0
def edit_post(request, post_slug):
    try:
        post = Post.objects.get(slug=post_slug)
    except Post.DoesNotExist:
        return HttpResponseRedirect(reverse('blog:add_post'))

    if request.method == 'POST':  # Save the data
        form = PostForm(request.POST)
        if form.is_valid():
            post.title = form.cleaned_data['title']
            post.body = form.cleaned_data['body']
            post.tease = form.cleaned_data['tease']
            post.status = form.cleaned_data['status']
            post.slug = encode(form.cleaned_data['title'])
            post.save()

            # Get the list of tags
            if request.POST['tags'] != '':
                tags = request.POST['tags']
                tag_list = tags.split(' ')
                for tag_string in tag_list:
                    if tag_string != '':
                        tag = Tag.objects.get_or_create(name=tag_string)[0]
                        post.tags.add(tag)
                        post.save()
            else:
                for tag in post.tags.all():
                    tag.post_set.remove(post)

            if request.POST['category'] != '':
                category_name = request.POST['category']
                category_slug = encode(category_name)
                category = Category.objects.get_or_create(
                    name=category_name, slug=category_slug)[0]
                post.category = category
                post.save()
            else:
                # If the category was made blank, then dissociate the category from the post
                try:
                    post.category.post_set.remove(post)
                except AttributeError:
                    pass

            return HttpResponseRedirect(reverse('blog:index'))
        else:
            print(form.errors)
    else:  # Populate the form with data
        form = PostForm({
            'title': post.title,
            'body': post.body,
            'tease': post.tease,
            'status': post.status,
            'tags': post.tags_as_string,
            'category': post.category_as_string
        })

    return render_to_response("blog/edit_post.html", {
        'post': post,
        'form': form,
        'sidebar': sidebar_dictionary()
    },
                              context_instance=RequestContext(request))
Beispiel #53
0
def add_post(request, post_slug=''):
    """
    The view for adding a new post.

    Template: "blog/add_post.html"

    Context:
        form
            The Post form that we want to save
        edit
            A boolean denoting whether we are in edit mode. The form action will then include the post_slug
        slug
            The post slug in order for the form action to redirect back here... with the post slug.

    :param request:
    :param post_slug: the optional argument for editing an existing post
    :return:
    """

    # Handle post upload
    if request.method == 'POST' and "submit_post" in request.POST:
        form = PostForm(request.POST)

        if form.is_valid():
            post = Post(title=form.cleaned_data['title'],
                        body=form.cleaned_data['body'],
                        tease=form.cleaned_data['tease'],
                        status=form.cleaned_data['status'],
                        slug=encode(form.cleaned_data['title']))
            post.save()

            if form.cleaned_data['category'] != '':
                category_name = request.POST['category']
                category_slug = encode(category_name)
                post.category = Category.objects.get_or_create(
                    name=category_name, slug=category_slug)[0]
                post.save()

            # Get the list of tags
            if request.POST['tags'] != '':
                tags = request.POST['tags']
                tag_list = tags.split(' ')
                for tag_string in tag_list:
                    # An extra space at the last tag will result in an empty tag
                    if tag_string != '':
                        tag = Tag.objects.get_or_create(name=tag_string)[0]
                        post.tags.add(tag)
                        post.save()

            return HttpResponseRedirect(reverse('blog:index'))
        else:
            print(form.errors)

    else:
        form = PostForm()

    return render_to_response('blog/add_post.html', {
        'form': form,
        'sidebar': sidebar_dictionary()
    },
                              context_instance=RequestContext(request))
Beispiel #54
0
 def test_post_form(self):
     # these fields are supposed to be required
     post_form = PostForm({'title': '', 'description': ''})
     self.assertFalse(post_form.is_valid())
     post_form = PostForm({'title': 'test', 'description': 'test'})
     self.assertTrue(post_form.is_valid())
Beispiel #55
0
def calendar(request):
	today = datetime.now()
	weekday = today.isoweekday()
	start = datetime.now()-timedelta(days=weekday-1)
	first_week = []
	second_week = []
	records_first_week = []
	records_second_week = []

	for i in range(0,14):
		x = ""
		x = Meeting.objects.filter(Q(leader__id=request.user.id) | Q(trader_1__id=request.user.id),
								   date__year=start.year,
								   date__month=start.month,
								   date__day=start.day).order_by('date')
		
		if i < 7:
			records_first_week.append(x)
		else:
			records_second_week.append(x)

		start = start + timedelta(days=1)

	start = datetime.now()-timedelta(days=weekday-1)
	for i in range(0,14):
		if i < 7:
			first_week.append(start+timedelta(days=i))
			records_first_week[i].dd = start+timedelta(days=i)

		else:
			second_week.append(start+timedelta(days=i))
			# records_second_week[i].d = start+timedelta(days=i)
	form = PostForm()

	if request.method == "POST":

		form = PostForm(request.POST)
		if form.is_valid():
			print("is valid")
			# city = form.cleaned_data['company']
			# print(city)
			instance = form.save(commit=False)
			instance.city = instance.company.city
			instance.leader_id = request.user.id
			instance.save()
			return redirect("blog-calendar")

	context = {
		'first_week': first_week,
		'second_week': second_week,
		'records_first_week': records_first_week,
		'records_second_week': records_second_week,
		'today': datetime.now() , 
		'cities': City.objects.all().order_by('name'),
		'employee': User.objects.all().exclude(id = request.user.id).order_by('first_name'),
		'form': form,
	}



	return render(request, 'blog/calendar.html', context)
Beispiel #56
0
def mystats(request):

	def color(pct):
		if pct < 50:
			return '-danger'
		elif pct < 100:
			return '-warning'
		else:
			return '-success'


	title = "pulpit"

	# All meetings for current user
	m_all = Meeting.objects.filter(Q(leader__id=request.user.id) | Q(trader_1__id=request.user.id)).order_by('date')
	m_planned = m_all.filter(status_id=1, date__gt=datetime.now())
	m_done = m_all.filter(status_id=2)

	# Monthly meetings
	mm_done = m_all.filter(status_id=2, date__month=datetime.now().month)
	mm_norm = UserNorm.objects.get(employee_id=request.user.id).meetings_month_norm
	mm_pct = int(100*len(mm_done)/mm_norm)
	m_to_acc = m_all.filter(status_id=1, date__lte=datetime.now())

	# All phonecalls for current user
	pc_all = PhoneCalls.objects.filter(employee_id=request.user.id)

	# Monthly phonecalls
	pcm_done = pc_all.filter(date__month=datetime.now().month)
	pcm_norm = UserNorm.objects.get(employee_id=request.user.id).phonecalls_month_norm
	pcm_pct = int(100*len(pcm_done)/pcm_norm)

	# Weekly phonecalls
	pcw_done = pc_all.filter(date__week=date.today().isocalendar()[1])
	pcw_norm = UserNorm.objects.get(employee_id=request.user.id).phonecalls_week_norm
	pcw_pct = int(100*len(pcw_done)/pcw_norm)

	m_form = PostForm()
	pc_form = PlanPhoneCallForm()


	if request.method == "POST":
		
		m_form = PostForm(request.POST)
		pc_form = PlanPhoneCallForm(request.POST)

		if m_form.is_valid():
			instance = m_form.save(commit=False)
			instance.city = instance.company.city
			instance.leader_id = request.user.id
			instance.status_id = 1
			instance.save()
			return redirect('blog-desktop')

		if pc_form.is_valid():
			print("ok")
			instance = pc_form.save(commit=False)
			instance.employee_id = request.user.id
			instance.save()
			return redirect('blog-desktop')



	context = {
		'title': title,
		'm_planned': m_planned,
		'm_to_acc': m_to_acc,
		'm_done_last_5': m_done[:5],
		'mm_done_len': len(mm_done),
		'mm_norm': mm_norm,
		'mm_pct': mm_pct,
		'mm_color': color(mm_pct),
		'pcw_norm': pcw_norm,
		'pcw_done_len': len(pcw_done),
		'pcw_pct': pcw_pct,
		'pcw_color': color(pcw_pct),
		'pcm_norm': pcm_norm,
		'pcm_done_len': len(pcm_done),
		'pcm_pct': pcm_pct,
		'pcm_color': color(pcm_pct),
		'm_form': m_form,
		'pc_form': pc_form,
	}

	return render(request, 'blog/mystats.html', context)
Beispiel #57
0
def post_new(request):
    form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})
Beispiel #58
0
def post_update(request, pk):
    post = get_object_or_404(Post, pk=pk)

    if request.method == 'POST':
        f = PostForm(request.POST, instance=post)

        if f.is_valid():
            if request.POST.get('author') == '' and request.user.is_superuser:
                updated_post = f.save(commit=False)
                updated_post.author = Author.objects.get(
                    user__username='******')
                updated_post.save()
                f.save_m2m()

            elif request.POST.get('author') and request.user.is_superuser:
                f.save()

            else:
                updated_post = f.save(commit=False)
                updated_post.author = Author.objects.get(
                    user__username=request.user.username)
                updated_post.save()
                f.save_m2m()

            messages.add_message(request, messages.INFO, 'Post updated')
            return redirect('post_update', pk=pk)

        else:
            print(f.errors)

    #If request is GET, prepopulate with current post data
    else:
        f = PostForm(instance=post)
    return render(request, 'cadmin/post_update.html', {
        'form': f,
        'post': post
    })
Beispiel #59
0
 def get(self, request, *args, **kwargs):
     context={'postform': PostForm()}
     return render(request,self.template_name,context)
Beispiel #60
0
def PostHandler(request, **args):
    """docstring for GetPost"""
    if args["action"] == 'get':
        post = Post.objects.get(id=args["id"])
        return render_to_response('desktop/post.html', {'post': post})

    if request.user.is_authenticated():
        if args["action"] == 'del':
            p = Post.objects.get(id=args["id"])
            p.delete()
            return HttpResponseRedirect("/home")
        if args["action"] == 'new':
            pageinfo = {
                'title': "New Post",
                'action': '/p/add',
                'button': 'Publish'
            }
            return render_to_response('desktop/edit.html',
                                      {'pageinfo': pageinfo})
        if args["action"] == 'add':
            if request.method == 'POST':
                form = PostForm(request.POST)
                if form.is_valid():
                    postform = form.cleaned_data
                    user = request.user
                    published = datetime.datetime.now()
                    post = Post(title=postform['title'],
                                url=postform['url'],
                                author=user,
                                content=postform['content'],
                                published=published)
                    post.save()

                    tags = postform['tags'].split(" ")
                    if tags:
                        for t in tags:
                            try:
                                tag = Tag.objects.get(name=t)
                            except Tag.DoesNotExist:
                                tag = Tag(name=t)
                                tag.save()
                            post.tags.add(tag)

            return HttpResponseRedirect('/home')

        if args["action"] == 'edit':
            pageinfo = {
                'title': "Edit Post",
                'action': '/p/update/' + args["id"],
                'button': 'Update'
            }
            postform = Post.objects.get(id=args["id"])
            # tags=[ t.tag.name  for t in Post2Tag.objects.filter(post=args["id"])]
            #             tags=' '.join(tags)
            tags = postform.tags.all()
            return render_to_response('desktop/edit.html', {
                'pageinfo': pageinfo,
                'postform': postform,
                'tags': tags
            })

        if args["action"] == 'update':
            if request.method == 'POST':
                form = PostForm(request.POST)
                if form.is_valid():
                    postform = form.cleaned_data
                    user = request.user
                    post = Post.objects.get(id=args["id"])
                    post.title = postform['title']
                    post.url = postform['url']
                    post.content = postform['content']
                    post.save()

                    newtags = [tag.strip() for tag in postform['tags'].split()]
                    oldtags = [tag.name for tag in post.tags.all()]

                    for t in list(set(oldtags).difference(set(newtags))):
                        post.tags.remove(Tag.objects.get(name=t))

                    for t in list(set(newtags).difference(set(oldtags))):
                        try:
                            tag = Tag.objects.get(name=t)
                        except Tag.DoesNotExist:
                            tag = Tag(name=t)
                            tag.save()
                        post.tags.add(Tag.objects.get(name=t))

            return HttpResponseRedirect('/home')
    else:
        return HttpResponseRedirect("/login")