Example #1
0
def blogpost(request, pk=None):
    context = RequestContext(request)
    context_dict = {}

    if request.method == "POST":
        form = BlogPostForm(request.POST)

        if form.is_valid():

            if pk is not None:
                p = BlogPost.objects.get(pk=pk)
                p.title = form.cleaned_data['title']
                p.body = form.cleaned_data['body']
                p.save()

            else:
                title = form.cleaned_data['title']
                body = form.cleaned_data['body']
                BlogPost.objects.create(title=title, body=body, creator=request.user)

            return HttpResponseRedirect(reverse('blog.views.index'))
        else:
            return HttpResponse(form.errors)
    else:
        if pk is not None:
            p = BlogPost.objects.get(pk=pk)
            context_dict['edit'] = True
            context_dict['pk'] = pk
            context_dict['title'] = p.title
            context_dict['body'] = strip_paragraph_elements(p.body)
            print context

        return render_to_response('blog/newblogpost.html', context_dict, context)
Example #2
0
def edit_post(request, slug):

    if not utils.user_has_admin_rights(request.user):
        raise PermissionDenied

    blog_post = get_object_or_404(BlogPost, slug=slug)

    if blog_post.author_user_id != request.user.username:
        raise PermissionDenied

    if request.method == "POST":
        # Create a form instance and populate it with data from the request:
        form = BlogPostForm(request.POST, instance=blog_post)

        if form.is_valid():

            form.save()

            # Go back to the admin page
            return redirect("blog.views.admin")

    else:
        # Create a form from the existing blog post
        form = BlogPostForm(instance=blog_post)

    templateDict = get_template_dict("Admin", request.user)
    templateDict["form"] = form
    templateDict["editing_post"] = True
    templateDict["edit_link"] = blog_post.get_absolute_edit_url()

    return render(request, "blog/add_edit_post.html", templateDict)
 def test_form(self):
     form_data = {
         'author': 1,  # Id of user
         'title': 'test title'
     }
     form = BlogPostForm(data=form_data)
     self.assertTrue(form.is_valid())
Example #4
0
def add_post(request):

    if not utils.user_has_admin_rights(request.user):
        raise PermissionDenied

    if request.method == "POST":
        # Create a form instance and populate it with data from the request:
        form = BlogPostForm(request.POST)

        if form.is_valid():

            newPost = form.save(commit=False)
            newPost.author_user_id = request.user.username
            newPost.author_email = request.user.email
            newPost.save()
            pk = newPost._get_pk_val()

            # Go back to the admin page, but pas back the primary key of the
            # new object so that we can find it
            response = redirect("blog.views.admin")
            response["Location"] += "?pk=" + str(pk)
            return response

    else:
        # Create a blank form
        form = BlogPostForm()

    templateDict = get_template_dict("Admin", request.user)
    templateDict["form"] = form

    return render(request, "blog/add_edit_post.html", templateDict)
Example #5
0
 def test_fail_normal_user(self):
     form = BlogPostForm({
         'title': 'foo',
         'content': 'bar',
         'author': self.normal.id
     })
     self.assertFalse(form.is_valid())
 def test_invalid_form_1(self):
     form_data = {
         'author': 1,
         'title': None  # No title
     }
     form = BlogPostForm(data=form_data)
     self.assertFalse(form.is_valid())
 def test_valid(self):
     form_data={"title": "My blog", "content": "Blog content", 
                "image": "test_img.jpeg",
                "tag": "Meta", "published_date": "2020-06-15 00:00:00",
                "writer": "User"}
     form= BlogPostForm(data=form_data)
     self.assertTrue(form.is_valid())
Example #8
0
def blog_post(request):
    '''
    博客发布界面
    :param request:
    :return:
    '''
    if request.method == 'POST':
        blog_post_form = BlogPostForm(data=request.POST)
        if blog_post_form.is_valid():
            check_data = blog_post_form.cleaned_data
            try:
                new_blog = blog_post_form.save(commit=False)
                # print('Title:{}\nContent:{}\nCategory:{}'.format(new_blog.title, new_blog.content, new_blog.category))
                new_blog.save()
                tag = random.choice(Tag.objects.all())

                new_blog.tag.add(tag)
                new_blog.save()

                return HttpResponse("1")
            except Exception as e:
                print(e)
                return HttpResponse("2")
        else:
            return HttpResponse("3")
    else:
        blog_post_form = BlogPostForm()
        context = {
            "blog_post_form": blog_post_form,
        }
        return render(request, 'blog/blog_post.html', context=context)
 def test_invalid_form_2(self):
     form_data = {
         'author': 1,
         'title': 'a' * 201  # over max length
     }
     form = BlogPostForm(data=form_data)
     self.assertFalse(form.is_valid())
Example #10
0
def create_blogpost(request):
    if request.method == 'POST':
        form = BlogPostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)  # 并不会真正保存数据
            post.timestemp = datetime.now()
            post.save()
    return HttpResponseRedirect('/blog/')
Example #11
0
def create(request):
    form = BlogPostForm(request.POST or None)
    ctx = {'form': form}

    if request.method == 'POST':
        if form.is_valid():
            form.save()
            return redirect('blog_index')
    return render(request, 'blog/create.html', ctx)
Example #12
0
 def test_create_object(self):
     count = BlogPost.objects.count()
     form = BlogPostForm({
         'title': 'foo',
         'content': 'bar',
         'author': self.staff.id
     })
     self.assertTrue(form.is_valid())
     form.save()
     self.assertEqual(count + 1, BlogPost.objects.count())
Example #13
0
def new_post_page(request):
    if request.method == "POST":
        form = BlogPostForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("/")
        else:
            return render(request, "new_post.html", {"form": form})
    form = BlogPostForm()
    return render(request, "new_post.html", {"form": form})
Example #14
0
 def test_blog_form_wont_accept_blank_body(self):
     form = BlogPostForm(data={
         "title": ".",
         "date": "1939-09-01",
         "body": "",
         "visible": True
     })
     self.assertFalse(form.is_valid())
     self.assertEqual(form.errors["body"],
                      ["You cannot submit a blog post with no body"])
    def post(self, request):
        form = BlogPostForm(data=request.POST)
        if not form.is_valid():
            return self.render_to_response({'errors': form.errors})

        blogpost = form.save(commit=False)
        blogpost.user = request.user
        blogpost.save()

        return HttpResponseRedirect(
            reverse('posts-detail', kwargs={'id': blogpost.id}))
 def test_invalid(self):
     form_data={"title": "", "content": "", "image": "",
                "tag": "", "published_date": "", "writer": ""}
     form= BlogPostForm(data=form_data)
     self.assertFalse(form.is_valid())
     self.assertEqual(
         form.errors["title"], [u"This field is required."])
     self.assertEqual(
         form.errors["content"], [u"This field is required."])
     self.assertEqual(
         form.errors["writer"], [u"This field is required."])
Example #17
0
 def test_blog_form_wont_accept_duplicate_dates(self):
     date = datetime.datetime(1990, 9, 28).date()
     BlogPost.objects.create(title=".", date=date, body=".", visible=True)
     form = BlogPostForm(data={
         "title": ".",
         "date": "1990-09-28",
         "body": ".",
         "visible": True
     })
     self.assertFalse(form.is_valid())
     self.assertEqual(form.errors["date"],
                      ["There is already a blog post for this date"])
Example #18
0
    def post(self, request):
        form = BlogPostForm(request.POST)

        if not form.is_valid():
            messages.error(request, 'Invalid form', extra_tags='dnager')
            return render('create_post')

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

        return redirect('blog_post', post_id=post.id)
Example #19
0
 def test_blog_form_wont_accept_blank_body(self):
     form = BlogPostForm(data={
      "title": ".",
      "date": "1939-09-01",
      "body": "",
      "visible": True
     })
     self.assertFalse(form.is_valid())
     self.assertEqual(
      form.errors["body"],
      ["You cannot submit a blog post with no body"]
     )
Example #20
0
def edit_post_page(request, post_id):
    blog_post = BlogPost.objects.get(pk=post_id)
    if request.method == "POST":
        form = BlogPostForm(request.POST, instance=blog_post)
        if form.is_valid():
            form.save()
            return redirect("/blog/")
        else:
            return render(request, "edit_post.html", {"form": form, "id": post_id})
    else:
        form = BlogPostForm(instance=blog_post)
        return render(request, "edit_post.html", {"form": form, "id": post_id})
    def post(self, request, id):
        blogpost = get_object_or_404(BlogPost, id=id)

        if blogpost.user != request.user:
            raise Http404

        form = BlogPostForm(data=request.POST, instance=blogpost)
        if not form.is_valid():
            return self.render_to_response({'errors': form.errors})

        blogpost = form.save()
        return HttpResponseRedirect(
            reverse('posts-detail', kwargs={'id': blogpost.id}))
Example #22
0
 def test_blog_form_wont_accept_duplicate_dates(self):
     date = datetime.datetime(1990, 9, 28).date()
     BlogPost.objects.create(title=".", date=date, body=".", visible=True)
     form = BlogPostForm(data={
      "title": ".",
      "date": "1990-09-28",
      "body": ".",
      "visible": True
     })
     self.assertFalse(form.is_valid())
     self.assertEqual(
      form.errors["date"],
      ["There is already a blog post for this date"]
     )
Example #23
0
def edit(request, pk=None):
    if pk is not None:
        post = get_object_or_404(BlogPost, pk=pk)
        form = BlogPostForm(request.POST or None, instance=post)
    else:
        post = None
        form = BlogPostForm(request.POST or None)

    if form.is_valid():
        form.save()
        messages.success(request, _('Post updated'))
        return redirect('blog_list')

    ctx = {'form': form, 'post': post}
    return render(request, 'blog/create.html', ctx)
Example #24
0
def manage_blog_post_add(request):
    assert isinstance(request, HttpRequest)  
    if request.method == "POST":
        form = BlogPostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('manage_blog_post_change', pk=post.pk)
    else:
        form = BlogPostForm()
    return render(request, 'app/manage_blog_post.html', 
                    {
                    'BlogPostForm': form
                    , 'title': 'Add Post'
                    }
                  )
Example #25
0
def post_add(request):
    if request.method == "GET":
        form = BlogPostForm()
        params = {"form": form}
        return blog_render(request, "post_add.html", params)

    elif request.method == "POST":
        form = BlogPostForm(request.POST)

        if form.is_valid():
            BlogPost.create(title=form.cleaned_data["title"],
                            content=form.cleaned_data["content"],
                            author=users.get_current_user().email())
        else:
            params = {"form": form}
            return blog_render(request, "post_add.html", params)

        return redirect("home")
Example #26
0
def post_add(request):
	if request.method == "GET":
		form = BlogPostForm()
		params = {"form": form}
		return blog_render(request, "post_add.html", params)

	elif request.method == "POST":
		form = BlogPostForm(request.POST)

		if form.is_valid():
			BlogPost.create(title=form.cleaned_data["title"],
			                content=form.cleaned_data["content"],
			                author=users.get_current_user().email())
		else:
			params = {"form": form}
			return blog_render(request, "post_add.html", params)

		return redirect("home")
Example #27
0
File: views.py Project: xxxt/blog
def article_create(request):
    if request.session['userid'] == 2:
        if request.method == "POST":
            article_post_form = BlogPostForm(data=request.POST)
            content_form = MDEditorForm(request.POST)
            if article_post_form.is_valid():
                new_article = article_post_form.save(commit=False)
                new_article.author = User.objects.get(
                    no=request.session['userid'])
                # if request.POST['category'] != 'none':
                # new_article.colum = Category.objects.get(id=request.POST['category'])

                # if request.POST['tag'] != 'none':
                #     new_article.tags = Category.objects.get(id=request.POST['tag'])
                # new_article.category.add(Category.objects.get[])
                # new_article.tags = '网络'
                new_article.save()
                article_post_form.save_m2m()
                if request.POST['category'] != 'none':
                    new_article.category.add(
                        get_object_or_404(Category,
                                          id=request.POST['category']))
                # if request.POST['tag'] != 'none':
                #     try:
                #         new_article.tags.add(get_object_or_404(Tag, id=request.POST['tag']))
                #     except:
                #         pass
                return redirect('blog:index')
            else:
                return HttpResponse("表单内容有误,请重新填写。")
        else:
            article_post_form = BlogPostForm()
            categories = Category.objects.all()
            tags = Tag.objects.all()
            context = {
                'article_post_form': article_post_form,
                'categories': categories,
                'tags': tags
            }
            return render(request, 'blog/create.html', context)
    else:
        return render(request, 'blog/create.html', {'error': '您无权发表文章'})
Example #28
0
def post_edit(request, post_id):
    post = BlogPost.get_by_id(int(post_id))
    user = users.get_current_user()
    if request.method == "GET" and post.author == user.email():
        form = BlogPostForm({"title": post.title, "content": post.content})
        params = {"form": form, "post": post}
        return blog_render(request, "post_edit.html", params)
    elif request.method == "POST" and post.author == user.email():
        form = BlogPostForm(request.POST)

        if form.is_valid():
            BlogPost.edit(post_id=int(post_id),
                          title=form.cleaned_data["title"],
                          content=form.cleaned_data["content"])
        else:
            params = {"form": form}
            return blog_render(request, "post_add.html", params)

        return redirect("home")
    else:
        return redirect("forbidden")
Example #29
0
def post_edit(request, post_id):
	post = BlogPost.get_by_id(int(post_id))
	user = users.get_current_user()
	if request.method == "GET" and post.author == user.email():
		form = BlogPostForm({"title": post.title, "content": post.content})
		params = {"form": form, "post": post}
		return blog_render(request, "post_edit.html", params)
	elif request.method == "POST" and post.author == user.email():
		form = BlogPostForm(request.POST)

		if form.is_valid():
			BlogPost.edit(post_id=int(post_id),
			              title=form.cleaned_data["title"],
			              content=form.cleaned_data["content"])
		else:
			params = {"form": form}
			return blog_render(request, "post_add.html", params)

		return redirect("home")
	else:
		return redirect("forbidden")
Example #30
0
def manage_blog_post_change(request, pk):
    assert isinstance(request, HttpRequest)
    post = get_object_or_404(blog_post, pk=pk)
    if (request.user == post.author):
        if request.method == "POST":
            form = BlogPostForm(request.POST, instance=post)
            if form.is_valid():
                post = form.save(commit=False)
                post.save()
                return redirect(manage_blog_post_list)
        else:
            form = BlogPostForm(instance = post)
            return render(request
                          , 'app/manage_blog_post.html', 
                            {
                            'BlogPostForm': form
                            , 'title': 'Edit Post: ' + post.title
                            }
                          )
    else:
        return redirect('manage_blog_post_list')    
Example #31
0
def add_blog_post(request, surface_id):
 
    surface = get_object_or_404(BlogSurface, id=surface_id)
    print surface.slug
    if request.method == 'POST':
        form = BlogPostForm(request.POST, auto_id=True)
        if form.is_valid():
            blog_item = form.save(commit=False)
            blog_item.blog_surface = surface
            blog_item.save()
            return HttpResponseRedirect(reverse('surface_map', args=(surface.slug,)))
 
    else:
        # There is no GET - the form is included on the main surface page
        return HttpResponseNotFound("There isn't a page for blog post GETs")

    context_vars = {    'form' : form,
                        'surface' : surface,
                   }
 
    return render_to_response(  'add_blog_post.html',
                                context_vars,
                                context_instance=RequestContext(request)
                             )
Example #32
0
 def test_title_is_required(self):
     form = BlogPostForm({'title': ''})
     self.assertFalse(form.is_valid())
     self.assertIn('title', form.errors.keys())
     self.assertEqual(form.errors['title'][0], 'This field is required.')
Example #33
0
 def test_no_data(self):
     form = BlogPostForm()
     self.assertFalse(form.is_valid())