Beispiel #1
0
def manage_blogs(request, blog_id=None):
    if request.method == 'POST':
        form = BlogForm(request.POST)
        if form.is_valid():
            niche = NicheModel.objects.get(id=int(request.POST['niche']))
            newblog = BlogModel(address=request.POST['address'],
                                user=request.POST['user'],
                                password=request.POST['password'],
                                niche=niche)
            newblog.save()
            return HttpResponseRedirect('/manage_blogs/')
    else:
        initial_data = None
        if blog_id:
            try:
                edit_blog = BlogModel.objects.get(pk=blog_id)
                initial_data = edit_blog.get_data()
            except Exception:
                pass
        form = BlogForm(initial_data)
        blogs = BlogModel.objects.all()
        return render_to_response('manage_blogs.html', {
            'blogs': blogs,
            'form': form,
            'blog_id': blog_id
        },
                                  context_instance=RequestContext(request))
Beispiel #2
0
def blog_add(request):
    if request.method == 'POST':
        form = BlogForm(request.POST)
        tag = TagForm(request.POST)
        if form.is_valid() and tag.is_valid():
            cd = form.cleaned_data
            cdtag = tag.cleaned_data
            tagname = cdtag['tag_name']
            for taglist in tagname.split():
                Tag.objects.get_or_create(tag_name=taglist.strip())
            title = cd['caption']
            author = Author.objects.get(id=1)
            content = cd['content']
            blog = Blog(caption=title, author=author, content=content)
            blog.save()
            for taglist in tagname.split():
                blog.tags.add(Tag.objects.get(tag_name=taglist.strip()))
                blog.save()
            id = Blog.objects.order_by('-publish_time')[0].id
            return HttpResponseRedirect('blog/%s' % id)
    else:
        form = BlogForm()
        tag = TagForm(initial={'tag_name': 'notags'})
    return render_to_response('blog_add.html',
        {'form': form, 'tag': tag}, context_instance=RequestContext(request))
Beispiel #3
0
def create(request, template_name='main/form.html'):
    form = BlogForm(request.POST or None)
    if form.is_valid():
        form.save()
        messages.success(request, 'Post has been created')
        return redirect('index')
    return render(request, template_name, {'form': form})
Beispiel #4
0
def edit_blog(user_id):
    blog = session.query(Blog).filter_by(user_id=user_id).one()
    old_img = blog.profile_img
    form = BlogForm(obj=blog)
    if form.validate_on_submit():
        blog.last_modified = time()
        form.populate_obj(blog)
        if form.image.data and allowed_file(form.image.data.filename):
            if old_img:
                # first delete the previous file in the upload_folder
                deleting_file = os.path.join(app.config['UPLOAD_FOLDER'],
                                             old_img)
                os.remove(deleting_file)
            # then upload the new file
            file = form.image.data
            # upload the file with prefix(blog_id), suffix(last_modified)
            blog.profile_img = upload(file, str(login_session['blog_id']),
                                      str(int(blog.last_modified)))

        session.add(blog)
        session.commit()
        return redirect(url_for('view_blog', user_id=user_id))
    return render_template('blog_profile.html',
                           form=form,
                           user_id=login_session.get('user_id'),
                           username=login_session.get('username'))
def editBlog(id):
    blog_id = id
    org_blog = session.query(BlogModel).get(blog_id)
    form = BlogForm()
    if form.validate_on_submit():
        name = form['title'].data
        content = form['content'].data
        if org_blog.author != current_user.id:
            return "Permission Denied"
        session.query(BlogModel).filter(BlogModel.id == blog_id).update({
            "name":
            name,
            "content":
            content,
            "edited_on":
            datetime.datetime.now()
        })

        session.commit()
        flash("Blog edited successfully")
        return redirect("/blog/%d" % id)
    else:
        blog = session.query(BlogModel).get(blog_id)
        if blog.author == current_user.id:
            form.title.data = blog.name
            form.content.data = blog.content
            return render_template('edit_blog.html',
                                   title=blog.name,
                                   content=blog.content,
                                   blog_id=blog_id,
                                   form=form)
        else:
            return "Sign in with correct user"
Beispiel #6
0
def blog_edit_formset(request,id):
    blog = Blog.objects.get(id=id)

    form = BlogForm(request.POST if request.method =="POST" else None ,
                    instance=blog,prefix='blog')
    medias = media_formset(request,blog.medias.all())

    if request.method == "POST":

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

        if medias.is_valid():
            for media in medias.forms:
                if media.is_valid() and media.instance.data:
                    if media.cleaned_data.get('removing',False):
                        blog.medias.remove(media.instance)
                    else:
                        media.instance.user = request.user if request.user.is_authenticated() else None
                        media.save()
                        blog.medias.add(media.instance)
        else:
            #: error handling
            print medias.errors

            #: for increase medias.extra_forms after adding new mediafile

        medias = media_formset(None,blog.medias.all())

    return render_to_response('blogs/blog/edit_formset.html',
            {'form': form,'medias':medias, },
        context_instance=template.RequestContext(request))
Beispiel #7
0
def new_blog(request):
    if request.method == "POST":
        form = BlogForm(request.POST)
        if form.is_valid():
            _blog = form.save(commit=False)
            req_url = BASE_URL % (_blog.name, TEST_API_KEY)
            # parse json
            req = requests.get(req_url)
            jsonlist = json.loads(req.content)
            response = jsonlist['response']
            posts = response['posts']
            blog = response['blog']
            # for post in posts:
            # 	print post['body']

            _blog.title = blog['title']
            _blog.url = blog['url']
            _blog.save()

            for post in posts:
                article = Article()
                article.title = post['title']
                article.url = post['post_url']
                article.description = post['body']
                # article.published_date =
                # datetime.datetime.fromtimestamp(float(post['timestamp']))
                # print article.published_date
                article.blog = _blog
                article.save()
            return redirect('blogs.views.articles_list')
    else:
        form = BlogForm()
    return render(request, "new_blog.html", {"form": form})
Beispiel #8
0
def blog():
    # connect to the db and get the users
    conn = sqlite3.connect('survivor.db')
    conn.row_factory = dict_factory
    c = conn.cursor() 
    
    c.execute('SELECT user_nm FROM CompUser')
    results = c.fetchall()
    users = [(results.index(item), item) for item in results]
        
    form = BlogForm()
    form.username.choices = users
    if form.validate_on_submit():
        # get the users choice
        choices = form.username.choices
        user = (choices[form.username.data][1])
        time_ = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
        content = form.content.data
       
        query = "insert into Blog VALUES ('" + time_ + \
            "'," + "'" + user + "'," + "'" + content + "')"
        c.execute(query)
        conn.commit()

        flash(f'Blog created for {user}!', 'success')
        return redirect(url_for('home'))

    return render_template('blog.html', form=form)
def blog():
    form = BlogForm()
    if form.validate_on_submit():
        # get the users choice
        time_ = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
        content = form.content.data

        # insert the blog message into the database
        c, conn = get_db()
        query = 'insert into Blog (time_, user_nm, comp_nm, post) VALUES ("{}","{}", "{}", "{}")'.format(time_, USERNM.name, COMPNAME, content)
        c.execute(query)
        conn.commit()

        return redirect(url_for('blog'))

    conn = sqlite3.connect('survivor.db')

    #Display all blogs from the 'blogs' table
    conn.row_factory = dict_factory
    c = conn.cursor()
    c.execute("SELECT * FROM Blog \
        ORDER BY time_ DESC")
    blogs = c.fetchall()

    return render_template('blog.html', posts=blogs, form=form, user_nm=USERNM.name)
Beispiel #10
0
 async def get(self, id=None):
     form = BlogForm()
     blog = dict()
     if id:
         blog = await self.application.objects.get(Blog, id=id)
         form = BlogForm(title=blog.title, text=blog.text)
     self.render("blog_create.html", blog=blog, form=form)
Beispiel #11
0
def update(request, blog_id, template_name='main/form.html'):
    post = get_object_or_404(Blog, pk=blog_id)
    form = BlogForm(request.POST or None, instance=post)
    if form.is_valid():
        form.save()
        messages.success(request, 'Post has been updated')
        return redirect('index')
    return render(request, template_name, {'form': form})
Beispiel #12
0
def update(blog_id):
    blog_form = BlogForm(user_id=current_user.id)
    if blog_form.validate_on_submit():
        Blog.update(blog_id, blog_form.data)
        return redirect(url_for('.detail', blog_id=blog_id))
    else:
        flash('修改博客失败')
        return redirect(url_for('.edit', blog_id=blog_id))
Beispiel #13
0
def add():
    blog_form = BlogForm(user_id=current_user.id)
    if blog_form.validate_on_submit():
        Blog.new(blog_form.data)
        return redirect(url_for('.index'))
    else:
        flash('添加博客失败')
        return redirect(url_for('.new'))
Beispiel #14
0
def post_blog():
	form = BlogForm()
	if form.validate_on_submit():
		blog = form.get_blog()
		mongo.db.blogs.insert(blog)
		flash('发布成功')
		return redirect(request.args.get('next') or url_for('main.index'))

	return render_template('post.html', form=form)
Beispiel #15
0
def add_blog(request):
    if request.method == 'POST':
        form = BlogForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            return HttpResponseRedirect('/blogs')
        else:
            return HttpResponse('Some error occured please try again later.')
Beispiel #16
0
def edit_blog(blog_id):
	blog = mongo.db.blogs.find_one_or_404({'_id': ObjectId(blog_id)})
	form = BlogForm(data=blog)
	if form.validate_on_submit():
		formdata = form.get_blog()
		formdata.pop("time")
		formdata.pop("view_count")
		mongo.db.blogs.update({"_id": ObjectId(blog_id)}, {"$set": formdata}, True, False)
		flash('更新成功')
		return redirect(request.args.get('next') or url_for('main.index'))
	return render_template('post.html', form=form)
Beispiel #17
0
def edit_blog(id):
    blog = Blog.query.get_or_404(id)
    if current_user != blog.author and not current_user.is_administrator:
        abort(403)
    form = BlogForm(obj=blog)
    if form.validate_on_submit():
        form.populate_obj(blog)
        db.session.add(blog)
        db.session.commit()
        flash('博客已经更新', 'success')
        return redirect(url_for('front.blog', id=blog.id))
    return render_template('user/edit_blog.html', form=form)
Beispiel #18
0
def post_blog():
    # Check if user logged in to give access to page, otherwise direct to login
    form2 = BlogForm()
    if 'username' in session:
        if form2.validate_on_submit():
            with open('data/blog_posts.csv', 'a') as f:
                writer = csv.writer(f)
                writer.writerow([form2.blog_title.data, form2.content.data, form2.topic_area.data])
            return redirect(url_for('successful_post'))
        return render_template('Post_blog.html', form2=form2)
    else:
        flash('Log in first!')
        return redirect(url_for('login'))
Beispiel #19
0
def create_blog(request, id=False):
    if request.method == 'POST': # If the form has been submitted...
        form = BlogForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
           
            blog_id = int(request.POST['blog_id'])
            blog_name = form.cleaned_data['blog_name']
            blog_content = form.cleaned_data['blog_content']
            
            if blog_id == False:
                # Create blog entity
                blog_item = Blog(
                                 blog_name=blog_name,
                                 blog_content=blog_content)
            else:
                # retrieve existing blog entity
                blog_item = ndb.Key(Blog, blog_id).get()
          
                # update existing blog entity
                blog_item.blog_name = blog_name
                blog_item.blog_content = blog_content 
                
            # save request changes
            blog_item_key = blog_item.put()

            # redirect
            return HttpResponseRedirect('/blog') # Redirect after POST
    else:
        if id == False:
            # initialize form that creates form 
            form = BlogForm() # An unbound form
        else:
            # fetch the blog item based on the given id
            key = ndb.Key(Blog, int(id))
            selected_blog = key.get()
            
            # initialize form that edits form
            form = BlogForm(initial={
                                     'blog_name': selected_blog.blog_name,
                                     'blog_content': selected_blog.blog_content
                                      })

    # produce var for template
    variables = RequestContext(request, {
                                         'form' : form,
                                         'blog_id': int(id)                                                                                
                                         })
    
    return render_to_response( 'create_blog.html', variables )
Beispiel #20
0
def add_blog(request):
    if 'POST' == request.method:
        form = BlogForm(request.POST)
        if form.is_valid():
            # save the data
            form.save()
            messages.success(request, 'Blog details saved successfully.')
            return redirect('home')
        else:
            # error message 
            messages.error(request, 'Sumbitted form is invalid.')
    else:
        form = BlogForm()
    return render(request, 'blog/form.html', { 'form': form, 'action_title': 'Add Blog'})
Beispiel #21
0
def blog_update(request, id=""):
    id = id
    if request.method == 'POST':
        form = BlogForm(request.POST)
        tag = TagForm(request.POST)
        if form.is_valid() and tag.is_valid():
            cd = form.cleaned_data
            cdtag = tag.cleaned_data
            tagname = cdtag['tag_name']
            tagnamelist = tagname.split()
            for taglist in tagnamelist:
                Tag.objects.get_or_create(tag_name=taglist.strip())
            title = cd['caption']
            content = cd['content']
            blog = Blog.objects.get(id=id)
            if blog:
                blog.caption = title
                blog.content = content
                blog.save()
                for taglist in tagnamelist:
                    blog.tags.add(Tag.objects.get(tag_name=taglist.strip()))
                    blog.save()
                tags = blog.tags.all()
                for tagname in tags:
                    tagname = unicode(str(tagname), "utf-8")
                    if tagname not in tagnamelist:
                        notag = blog.tags.get(tag_name=tagname)
                        blog.tags.remove(notag)
            else:
                blog = Blog(caption=blog.caption, content=blog.content)
                blog.save()
            return HttpResponseRedirect('/blog/%s' % id)
    else:
        try:
            blog = Blog.objects.get(id=id)
        except Exception:
            raise Http404
        form = BlogForm(initial={'caption': blog.caption, 'content': blog.content}, auto_id=False)
        tags = blog.tags.all()
        if tags:
            taginit = ''
            for x in tags:
                taginit += str(x) + ' '
            tag = TagForm(initial={'tag_name': taginit})
        else:
            tag = TagForm()
    return render_to_response('blog_add.html',
        {'blog': blog, 'form': form, 'id': id, 'tag': tag},
        context_instance=RequestContext(request))
def newBlog():
    form = BlogForm()
    if form.validate_on_submit():
        print(form)
        title = form['title'].data
        content = form['content'].data
        blog = BlogModel(name=title,
                         content=content,
                         author=current_user.id,
                         created_on=datetime.datetime.now())
        session.add(blog)
        session.commit()
        return redirect('/blog/{}'.format(blog.id))
    else:
        return render_template("post_blog.html", form=form)
Beispiel #23
0
def create(request, template_name='main/form.html'):
    """
        View to create a new blog post.
        Just for the SuperUser.
    """
    if request.user.is_superuser:
        form = BlogForm(request.POST or None)
        if form.is_valid():
            form.save()
            messages.success(request, 'Post has been created')
            return redirect('index')
        return render(request, template_name, {'form': form})
    else:
        messages.success(request, 'You are not authorized')
        return redirect('index')
Beispiel #24
0
def add(request):
    if request.method == 'POST':
        form = BlogForm(request.POST, error_class=DivErrorList)

        if form.is_valid():
            request_data = form.cleaned_data
            request_data['user_id'] = request.user
            blog_id = Blog.add_message(Blog(), request_data)
            return HttpResponseRedirect('/blog/post/' + blog_id)
    else:
        form = BlogForm(error_class=DivErrorList)
    c = {
        'form': form
    }
    return render_to_response('blog/add.html', c, context_instance=RequestContext(request))
Beispiel #25
0
def create(request, template_name='main/form.html'):
    """
        View to create a new blog post.
        Just for the SuperUser.
    """
    if request.user.is_superuser:
        form = BlogForm(request.POST or None)
        if form.is_valid():
            form.save()
            messages.success(request, 'Post has been created')
            return redirect('index')
        return render(request, template_name, {'form': form})
    else:
        messages.success(request, 'You are not authorized')
        return redirect('index')
Beispiel #26
0
def blog():
  form = BlogForm()

  if request.method == 'POST':
    if form.validate() == False:
      return render_template('blog.html', form=form)
    else:
      newpost = Post(request.form['title'], request.form['post'])
      #newpost = Post(form.title.data, form.post.data)
      db.session.add(newpost)
      db.session.commit()
      return redirect(url_for('home'))


  elif request.method == 'GET':
    return render_template('blog.html', form=form)
Beispiel #27
0
def update(request, blog_id, template_name='main/form.html'):
    """
        View to update a particular blog post.
        Just for the SuperUser.
    """
    if request.user.is_superuser:
        post = get_object_or_404(Blog, pk=blog_id)
        form = BlogForm(request.POST or None, instance=post)
        if form.is_valid():
            form.save()
            messages.success(request, 'Post has been updated')
            return redirect('index')
        return render(request, template_name, {'form': form})
    else:
        messages.success(request, 'You are not authorized')
        return redirect('index')
Beispiel #28
0
def update(request, blog_id, template_name='main/form.html'):
    """
        View to update a particular blog post.
        Just for the SuperUser.
    """
    if request.user.is_superuser:
        post = get_object_or_404(Blog, pk=blog_id)
        form = BlogForm(request.POST or None, instance=post)
        if form.is_valid():
            form.save()
            messages.success(request, 'Post has been updated')
            return redirect('index')
        return render(request, template_name, {'form': form})
    else:
        messages.success(request, 'You are not authorized')
        return redirect('index')
Beispiel #29
0
def create(request):
    if not admin():
        return HttpResponseRedirect(users.create_login_url("/blogs"))
    form = BlogForm(request.POST)
    form.fields["category"].choices = [("", "请选择")] + [(category.key(), category.name) for category in Category.all()]
    if form.is_valid():
        blog = Blog()
        blog.title = form.cleaned_data["title"]
        blog.content = form.cleaned_data["content"]
        if form.cleaned_data["category"]:
            blog.category = Category.get(form.cleaned_data["category"])
        elif form.cleaned_data["user_tag"]:
            blog.category = Category.get_or_insert(form.cleaned_data["user_tag"], name=form.cleaned_data["user_tag"])
        blog.create()
        return HttpResponseRedirect("/blogs")
    else:
        return new(request)
Beispiel #30
0
def create(request):
    if not admin():
        return HttpResponseRedirect(users.create_login_url('/blogs'))
    form = BlogForm(request.POST)
    form.fields['category'].choices = [('', '请选择')] + [(category.key(), category.name) for category in Category.all()]
    if form.is_valid():
        blog = Blog()
        blog.title = form.cleaned_data['title']
        blog.content = form.cleaned_data['content']
        if form.cleaned_data['category']:
            blog.category = Category.get(form.cleaned_data['category'])
        elif form.cleaned_data['user_tag']:
            blog.category = Category.get_or_insert(form.cleaned_data['user_tag'], name=form.cleaned_data['user_tag'])
        blog.create()
        return HttpResponseRedirect('/blogs')
    else:
        return new(request)
Beispiel #31
0
def new_blog():
    """Blog List."""
    error = None
    form = BlogForm(request.form)
    if form.validate_on_submit():
        print 'hi'
        new_message = BlogPost(form.title.data, form.description.data,
                               current_user.id)
        db.session.add(new_message)
        db.session.commit()
        flash('New entry was successfully posted. Thanks.')
        return redirect(url_for('blog.blogs'))
    else:
        posts = db.session.query(BlogPost).all()
        return render_template('new_blog.html',
                               posts=posts,
                               form=form,
                               error=error)
Beispiel #32
0
def new_post():
    form = BlogForm()
    if request.method == 'POST':
        if not form.validate():
            return render_template('newpost.html', form=form)
        else:

            owner = User.query.filter_by(username=session['username']).first()
            blog_title = form.blog_title.data
            blog_post = form.blog_post.data

            new_blog = Blog(blog_title, blog_post, owner)
            db.session.add(new_blog)
            db.session.commit()

            return redirect(url_for('blog', id=new_blog.id))

    return render_template('newpost.html', form=form, title="Add a Blog Entry")
Beispiel #33
0
    async def post(self, id=None):
        title = self.get_argument("title")
        text = self.get_argument("text")

        form = BlogForm(title=title, text=text)
        if form.validate():
            if id:
                blog = await self.application.objects.get(Blog, id=id)
                blog.title = title
                blog.text = text
                blog.updated_at = datetime.datetime.now()
                await self.application.objects.update(blog)
                return self.redirect(self.reverse_url("blog_detail", id))
            blog = await self.application.objects.create(Blog,
                                                         title=title,
                                                         text=text)
            return self.redirect(self.reverse_url("blog_detail", blog.id))
        return self.render("blog_create.html", form=form)
Beispiel #34
0
def edit(request):
	if request.method == 'POST':
		form = BlogForm(request.POST)
		if form.is_valid():
			caption = form.clean_data['caption']
			article_id = form.clean_data['article_id']
			category = form.clean_data['category']
			content = form.clean_data['content']
				
			blog = Blog(caption=caption,
				    article_id=article_id,
				    category=category,
				    content=content)
			blog.save()
			return HttpResponseRedirect("/bloglist/")
	else:
		form = BlogForm()
	return render_to_response('edit.html', {'form': form}, context_instance=RequestContext(request))
Beispiel #35
0
def create(request):
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404
    form = BlogForm(
        request.POST or None,
        request.FILES,
    )
    if form.is_valid():
        instance = form.save(commit=False)
        instance.owner = request.user
        instance.save()
        messages.success(
            request,
            _('created successfully! <a href="/">See the item</a>'),
            extra_tags='alert alert-success safe')
    context = {
        'form': form,
    }
    return render(request, 'create.html', context)
Beispiel #36
0
def addBlog():
        title = {'title': 'Add Blog', 'year': forDate()}
        form = BlogForm()
        if form.validate_on_submit():
            '''---------------Add blog to database--------------'''
            blogTitle = request.form.get('blogTitle')
            auther = request.form.get('auther')
            blogContent = request.form.get('blogContent')
            tags = request.form.get('tags')
            now = datetime.now()
            now = now.strftime('%Y-%m-%d %H:%M:%S')
            dbconn = pymysql.connect(host="localhost", user="******", password="******", db="mooz")
            curr = dbconn.cursor()
            curr.execute("INSERT INTO posts (userId,title,Auther,post,tags,created) values ('" + '1' + "','" + blogTitle + "','" + auther + "','" + blogContent + "','" + tags + "','" + now + "')")
            dbconn.commit()
            flash("User Adding his blog of {} Title ".format(form.blogTitle.data))
            return redirect(url_for('home'))

        return render_template('addBlog.html',title=title,form=form)
Beispiel #37
0
def adminBlogEdit(post_id=1):
    # logout_user()

    blog = BlogPost.query.get(post_id)
    form = BlogForm()
    form.content.data = blog.content
    form.preview.data = blog.preview
    form.published.data = blog.published
    # print blog.content
    # print(request.args.get('value'))
    # print("what!")
    if form.validate_on_submit():
        # continue editing hereself.
        # b = BlogPost(blogTitle = form.title.data, date= datetime.now(), content=form.content.data, preview=form.preview.data, published=form.published.data, views=0, previewImage="../static/images/seattle.jpg" )
        # db.session.add(b)
        pdb.set_trace()
        blog.blogTitle = form.title.data
        blog.content = form.content.raw_data[0]
        blog.preview = form.preview.raw_data[0]
        blog.published = form.published.label.text

        print form.published.data
        print form.published.data
        print form.published.data
        print blog.content
        print blog.preview
        print blog.published

        db.session.add(blog)
        db.session.commit()
        # print "I just updated something!"
    else:
        # print "Form failed validation"

        print blog.comments

    published_blogs = BlogPost.query.filter_by(published=True)
    unpublished_blogs = BlogPost.query.filter_by(published=False)
    return render_template(
        "admin.html", published_blogs=published_blogs, unpublished_blogs=unpublished_blogs, current_blog=blog, form=form
    )
Beispiel #38
0
def blog(request):
    latest_blog_list = Blog.objects.order_by('-created_time')[:5]
    # latest_comment_list = Comment.objects.order_by('-comment_date')[:5]
    template = loader.get_template('blogs.html')
    context = RequestContext(
        request,
        {
            'latest_blog_list': latest_blog_list,
            # 'latest_comment_list':latest_comment_list,
            'template_name': 'blogs.html',
            'form_blog': BlogForm,
            'form_comment': CommentForm,
            'success_url': '/thanks/',
        })
    if request.method == 'POST':
        if 'blog_body' in request.POST:
            form = BlogForm(request.POST)
        elif 'comment_data' in request.POST:
            form = CommentForm(request.POST)
        if form.is_valid():
            blog_form = form.save(commit=False)
            if 'comment_data' in request.POST:
                blog = Blog.objects.get(id=request.POST['blog'])
                comment_count = blog.comment_set.aggregate(
                    Count('comment_data')).values()
                if comment_count[0] != None:
                    comment_count = blog.comment_set.aggregate(
                        Count('comment_data')).values()[0]
                else:
                    comment_count = int(request.POST['comment_data'])
                blog.overall_comment = comment_count
                blog.save()

            # commit=False tells Django that "Don't send this to database yet.
            # I have more things I want to do with it."
            blog_form.user = User.objects.get(username=request.user)
            # Set the user object here
            blog_form.save()
            # Now you can send it to DB

    return HttpResponse(template.render(context))
Beispiel #39
0
def index():
    '''网站首页'''
    form = BlogForm()
    # 凡是登录成功的用户,就有写博客的权限
    if current_user.is_authenticated:
        if form.validate_on_submit():
            blog = Blog()
            form.populate_obj(blog)
            blog.author = current_user
            db.session.add(blog)
            db.session.commit()
            flash('成功发布博客', 'success')
            return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    pagination = Blog.query.order_by(Blog.time_stamp.desc()).paginate(
        page, per_page=current_app.config['BLOGS_PER_PAGE'], error_out=False)
    blogs = pagination.items
    return render_template('index.html',
                           form=form,
                           blogs=blogs,
                           pagination=pagination)
Beispiel #40
0
def new_post(request):
	if request.method == 'POST':
		print request
		# create a form instance and populate it with data from the request
		form = BlogForm(request.POST)
		# check if it is valid
		if form.is_valid():
			# process data and redirect to a new URL
			title = form.cleaned_data['title']
			description = form.cleaned_data['description']
			content = form.cleaned_data['content']
			new = Post(title=title, content=content, description=description,
						published=form['published'], slug=slugify(unicode(title)))
			new.save()
			return HttpResponseRedirect('/blog/')
	# GET or other methods, create a blank form
	else:
		print "GET HERE"
		form = BlogForm()
		print form
	return render(request, 'blog/new.html', {'form': form})
Beispiel #41
0
def blog(request, id=None):
    if id != None:
        latest_blog_list = Blog.objects.filter(id=id)
    else:
        latest_blog_list = Blog.objects.order_by('-created_date')[:5]
    # latest_comment_list = Comment.objects.order_by('-comment_date')[:5]
    template = loader.get_template('blogs.html')
    context = RequestContext(request, {
        'latest_blog_list': latest_blog_list,
        # 'latest_comment_list':latest_comment_list,
        'template_name': 'blogs.html',
        'form_blog': BlogForm,
        'form_comment': CommentForm,
        'success_url': '/thanks/',
    })
    if request.method == 'POST':
        if 'blog_body' in request.POST:
            form = BlogForm(request.POST)
        elif 'comment_data' in request.POST:
                form = CommentForm(request.POST)
        if form.is_valid():
            blog_form = form.save(commit=False)
            if 'comment_data' in request.POST:
                blog = Blog.objects.get(id=request.POST['blog'])
                comment_count = blog.comment_set.aggregate(Count('comment_data')).values()
                if comment_count[0] != None:
                    comment_count = blog.comment_set.aggregate(Count('comment_data')).values()[0]
                else:
                    comment_count = int(request.POST['comment_data'])
                blog.overall_comment = comment_count
                blog.save()

            # commit=False tells Django that "Don't send this to database yet.
            # I have more things I want to do with it."
            blog_form.user = User.objects.get(username=request.user)
            # Set the user object here
            blog_form.save()
            # Now you can send it to DB

    return HttpResponse(template.render(context))
Beispiel #42
0
def edit(request, id=None):
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404
    instance = get_object_or_404(Blog, id=id)

    # check just owner and superuser can edit current post
    if not request.user.is_superuser and request.user != instance.owner:
        raise PermissionDenied

    form = BlogForm(request.POST or None,
                    request.FILES or None,
                    instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.owner = request.user
        form.save()
        messages.success(request,
                         _('updated successfully!!'),
                         extra_tags='alert alert-success')
        return HttpResponseRedirect(instance.get_absolute_url())

    context = {
        'form': form,
    }
    return render(request, 'edit.html', context)
Beispiel #43
0
def update(request, key):
    if not admin():
        return HttpResponseRedirect(users.create_login_url('/blogs'))
    form = BlogForm(request.POST)
    form.fields['category'].choices = [('', '请选择')] + [(category.key(), category.name) for category in Category.all()]
    if form.is_valid():
        blog = Blog.get(key)
        blog_category_db=blog.category
        blog.title = form.cleaned_data['title']
        blog.content = form.cleaned_data['content']
        if form.cleaned_data['category']:
            blog.category = Category.get(form.cleaned_data['category'])
        elif form.cleaned_data['user_tag']:
            blog.category = Category.get_or_insert(form.cleaned_data['user_tag'], name=form.cleaned_data['user_tag'])
        else:
            blog.category = None
        blog.put()
        if blog_category_db and blog_category_db.blog_set.count() == 0:
            blog_category_db.delete()
        return HttpResponseRedirect('/blogs')
    else:
        return edit(request, key)
Beispiel #44
0
def manage_blogs(request, blog_id=None):
    if request.method == 'POST':
        form = BlogForm(request.POST)
        if form.is_valid():
            niche = NicheModel.objects.get(id=int(request.POST['niche']))
            newblog = BlogModel(address=request.POST['address'],
                                user=request.POST['user'],
                                password=request.POST['password'],
                                niche=niche)
            newblog.save()
            return HttpResponseRedirect('/manage_blogs/')
    else:
        initial_data = None
        if blog_id:
            try:
                edit_blog = BlogModel.objects.get(pk=blog_id)
                initial_data = edit_blog.get_data()
            except Exception:
                pass
        form = BlogForm(initial_data)
        blogs = BlogModel.objects.all()
        return render_to_response('manage_blogs.html',
            {'blogs': blogs, 'form': form, 'blog_id': blog_id}, context_instance=RequestContext(request))
Beispiel #45
0
def edit(request, message_id):
    blog = Blog.objects.get(id=message_id)
    if request.user == blog.user_id:
        if request.method == 'POST':
            form = BlogForm(request.POST, error_class=DivErrorList)
            if form.is_valid():
                request_data = form.cleaned_data
                request_data['user_id'] = request.user
                request_data['id'] = message_id
                blog_id = Blog.edit_message(Blog(), request_data)
                return HttpResponseRedirect('/blog/post/' + blog_id)
        else:
            form = BlogForm(initial={'title': blog.title, 'message': blog.message}, error_class=DivErrorList)
            c = {
                'form': form,
                'model': blog,
                'message': 'success'
            }
    else:
        c = {
            'message': 'error',
        }
    return render_to_response('blog/edit.html', c, context_instance=RequestContext(request))
Beispiel #46
0
def new_post(request):
    if request.method == 'POST':
        print request
        # create a form instance and populate it with data from the request
        form = BlogForm(request.POST)
        # check if it is valid
        if form.is_valid():
            # process data and redirect to a new URL
            title = form.cleaned_data['title']
            description = form.cleaned_data['description']
            content = form.cleaned_data['content']
            new = Post(title=title,
                       content=content,
                       description=description,
                       published=form['published'],
                       slug=slugify(unicode(title)))
            new.save()
            return HttpResponseRedirect('/blog/')
    # GET or other methods, create a blank form
    else:
        print "GET HERE"
        form = BlogForm()
        print form
    return render(request, 'blog/new.html', {'form': form})
Beispiel #47
0
def blog_edit_simple(request,id):
    blog = Blog.objects.get(id=id)

    if request.method == "GET":
        form = BlogForm(instance=blog,prefix='blog')
        media_form = MediaFileForm(prefix='media')
    else:
        form = BlogForm(request.POST,instance=blog,prefix='blog')
        media_form = MediaFileForm(
            request.POST,request.FILES,prefix='media')

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

        if media_form.is_valid():
            media_form.instance.user = request.user
            media_form.instance.slug = uuid.uuid1().hex
            media_form.save()
            blog.medias.add(media_form.instance)
            media_form = MediaFileForm(prefix='media')

    return render_to_response('blogs/blog/edit_simple.html',
            {'form': form,'media_form':media_form, },
        context_instance=template.RequestContext(request))
Beispiel #48
0
def edit(blog_id):
    blog = Blog.query.get(blog_id)
    blog_auth(blog)
    blog_form = BlogForm(user_id=current_user.id)
    blog_form.content.data = blog.content
    return render_template('/blog/edit.html', form=blog_form, blog=blog)
Beispiel #49
0
def new():
    blog_form = BlogForm(user_id=current_user.id)
    return render_template('/blog/add.html', form=blog_form)