Exemplo n.º 1
0
 def test_creating_a_new_comment_and_saving_it_to_the_database(self):
     # start by create one Category and one post
     category = Category()
     category.name = "First"
     category.slug = "first"
     category.save()
     
     # create new post
     post = Post()
     post.category = category
     post.title = "First post"
     post.content = "Content"
     post.visable = True
     post.save()
     
     # create one comment
     comment = Comment()
     comment.name = "John"
     comment.content = "This is cool"
     comment.post = post
     
     # check save
     comment.save()
     
     # now check we can find it in the database
     all_comment_in_database = Comment.objects.all()
     self.assertEquals(len(all_comment_in_database), 1)
     only_comment_in_database = all_comment_in_database[0]
     self.assertEquals(only_comment_in_database, comment)
     
     # and check that it's saved its two attributes: name and content
     self.assertEquals(only_comment_in_database.name, comment.name)
     self.assertEquals(only_comment_in_database.content, comment.content)
Exemplo n.º 2
0
 def handle(self, *args, **options):
     with open('upload-temp') as f:
         sep = '\n' + ('-' * 70) + '\n'
         fields = f.read().split(sep)
         if options['edit']:
             try:
                 p = Post.objects.get(slug=fields[1])
                 p.edited = datetime.now()
             except Post.DoesNotExist:
                 raise CommandError('no post with slug "%s" exists'
                                    % fields[1]) 
         else:
             p = Post()
             p.created = datetime.now()
             p.edited = None
         p.title = fields[0]
         p.slug = fields[1]
         p.preview = fields[3]
         p.content = fields[4]
         p.save()
         p.categories.clear()
         for cat in fields[2].split(', '):
             try:
                 c = Category.objects.get(name=cat)
             except Category.DoesNotExist:
                 c = Category(name=cat, slug=slugify(cat))
                 c.save()
             p.categories.add(c)
         p.save()
Exemplo n.º 3
0
    def test_create_post(self):
        # Create the post
        post = Post()
        category = Category(id=1)

        # Set the attributes
        post.title = 'My first post'
        post.text = 'This is my first blog post'
        post.pub_date = timezone.now()
        category.title = 'My category'
        post.category = category

        # Save it
        post.save()

        # Check we can find it
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)
        only_post = all_posts[0]
        self.assertEquals(only_post, post)

        # Check attributes
        self.assertEquals(only_post.title, 'My first post')
        self.assertEquals(only_post.text, 'This is my first blog post')
        self.assertEquals(only_post.pub_date.day, post.pub_date.day)
Exemplo n.º 4
0
 def test_creating_a_new_post_and_saving_it_to_the_database(self):
     # start by create one Category
     category = Category()
     category.name = "First"
     category.slug = "first"
     category.save()
     
     # create new post
     post = Post()
     post.category = category
     post.title = "First post"
     post.content = "Content"
     post.visable = True
     
     # check we can save it
     post.save()
     
     # check slug
     self.assertEquals(post.slug, "first-post")
     
     # now check we can find it in the database
     all_post_in_database = Post.objects.all()
     self.assertEquals(len(all_post_in_database), 1)
     only_post_in_database = all_post_in_database[0]
     self.assertEquals(only_post_in_database, post)
     
     # check that it's saved all attributes: category, title, content, visable and generate slug
     self.assertEquals(only_post_in_database.category, category)
     self.assertEquals(only_post_in_database.title, post.title)
     self.assertEquals(only_post_in_database.content, post.content)
     self.assertEquals(only_post_in_database.visable, post.visable)
     self.assertEquals(only_post_in_database.slug, post.slug)
Exemplo n.º 5
0
    def test_create_post_without_tag(self):
        # Create the category
        category = Category()
        category.name = 'python'
        category.description = 'The Python programming language'
        category.save()

        # Log in
        self.client.login(username='******', password="******")

        # Check response code
        response = self.client.get('/admin/blog/post/add/')
        self.assertEquals(response.status_code, 200)

        # Create the new post
        response = self.client.post('/admin/blog/post/add/', {
            'title': 'My first post',
            'text': 'This is my first post',
            'pub_date_0': '2013-12-28',
            'pub_date_1': '22:00:04',
            'slug': 'my-first-post',
            # 'site': '1',
            'category': '1'
        },
                                    follow=True
        )
        self.assertEquals(response.status_code, 200)

        # Check added successfully
        self.assertTrue('added successfully' in response.content)

        # Check new post now in database
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)
Exemplo n.º 6
0
    def test_all_post_feed(self):
        # Create the category
        category = Category()
        category.name = 'python'
        category.description = 'The Python programming language'
        category.save()

        # Create the tag
        tag = Tag()
        tag.name = 'python'
        tag.description = 'The Python programming language'
        tag.save()

        # Create the author
        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # Create the site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()
 
        # Create a post
        post = Post()
        post.title = 'My first post'
        post.text = 'This is my first blog post'
        post.slug = 'my-first-post'
        post.pub_date = timezone.now()
        post.author = author
        post.site = site
        post.category = category

        # Save it
        post.save()

        # Add the tag
        post.tags.add(tag)
        post.save()

        # Check we can find it
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)
        only_post = all_posts[0]
        self.assertEquals(only_post, post)

        # Fetch the feed
        response = self.client.get('/feeds/posts/')
        self.assertEquals(response.status_code, 200)

        # Parse the feed
        feed = feedparser.parse(response.content)

        # Check length
        self.assertEquals(len(feed.entries), 1)

        # Check post retrieved is the correct one
        feed_post = feed.entries[0]
        self.assertEquals(feed_post.title, post.title)
        self.assertEquals(feed_post.description, post.text)
Exemplo n.º 7
0
    def test_edit_category(self):
        # Create the category
        category = Category()
        category.name = 'python'
        category.description = 'The Python programming language'
        category.save()

        # Log in
        self.client.login(username='******', password="******")

        # Edit the category
        response = self.client.post('/admin/blogengine/category/1/', {
            'name': 'perl',
            'description': 'The Perl programming language'
            }, follow=True)
        self.assertEquals(response.status_code, 200)

        # Check changed successfully
        self.assertTrue('changed successfully' in response.content)

        # Check category amended
        all_categories = Category.objects.all()
        self.assertEquals(len(all_categories), 1)
        only_category = all_categories[0]
        self.assertEquals(only_category.name, 'perl')
        self.assertEquals(only_category.description, 'The Perl programming language')
Exemplo n.º 8
0
def async_add_category(request):
    if not request.POST:
        raise Http404
    
    data = {}
    
    name = request.POST.get('name', False)
    slug = request.POST.get('slug', False)
    if name == False or slug == False:
        data.update({"status": False, "message": "Invalid data."})
    elif len(name) == 0 or len(slug) == 0:
        data.update({"status": False, "message": "Neither field can be blank."})
    else:
        try:
            cat = Category(name=slug,label=name) # Stupid naming of the model.  Don't feel like fixing all references..
            cat.save()
            data.update({"status": True, "message": "Category successfully added.", 
                         "slug": cat.name, "name": cat.label})
        except:
            data.update({"status": False, "message": "An unknown error occured. Please reload the page."})
    
    return HttpResponse(simplejson.dumps(data), mimetype="application/javascript")

### END AJAX VIEWS ###
    
Exemplo n.º 9
0
def add(request):
  errors = []
  if request.method == 'POST':
    print request.POST
    if check_edit_post_param(request.POST):
      Category.insert_from_dic(request.POST.copy())
      return HttpResponseRedirect('/admin/category/show/')
  return render(request, 'admin/error.html', {'errors':errors})
Exemplo n.º 10
0
    def __create_category(self, lang, title, desc):
        cat = Category(lang=lang, title=title, desc=desc)

        cat.save()
        print(
            "Created category : {} | {} | {} | ".format(lang, title, desc))

        return cat
Exemplo n.º 11
0
    def test_edit_posts(self):
        category = Category()
        category.name = 'python'
        category.description = 'The python language'
        category.save()

        # Create the tag
        tag = Tag()
        tag.name = 'python'
        tag.description = 'The Python programming language'
        tag.save()

        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # site = Site()
        # site.name = 'nunfuxgvn.com'
        # site.domain = 'nunfuxgvn.com'
        # site.save()


        post = Post()
        post.title = 'First Post'
        post.content = 'My first post -yay'
        post.slug = 'first-post'
        post.pub_date = timezone.now()
        post.author = author
        # post.site = site
        post.save()
        post.tags.add(tag)
        post.save()

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/blog/post/1/', {
            'title': 'Second Post',
            'text': 'This is my second post',
            'pub_date_0': '2014-07-17',
            'pub_date_1': '11:49:24',
            'slug': 'second-post',
            # 'site': '1',
            'category': '1',
            'tags': '1'
        },
                                    follow=True
        )
        self.assertEquals(response.status_code, 200)

        # Check post successfully changed
        self.assertTrue('changed successfully' in response.content)

        # Check post amended 
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)
        only_post = all_posts[0]
        self.assertEquals(only_post.title, 'Second Post')
        self.assertEquals(only_post.content, 'This is my second post')
Exemplo n.º 12
0
def add_category(request):
	try:
		req = convertRequest(request)

		category_name = req['category_name']
		category = Category(category_name=category_name)
		category.save()
		return HttpResponse(response_json.success())
	except Exception, e:
		return HttpResponse(response_json.fail(traceback.format_exc()))
Exemplo n.º 13
0
def addCategory(request):
    name = request.POST['name']
    slug = request.POST['slug']
    desc = request.POST['desc']
    type = request.POST['type']
    pid = request.POST['category_parent']
    if pid == '0':
        pid = None
    if type and type == 'add':
        try:
            cats=Category.objects.filter(name=name)
            if cats.count() >= 1:
                messages.add_message(request,messages.INFO,'categry [%s] already exits!'%(name))
            else:
                cat = Category(name=name,slug=slug,desc=desc,parent_id=pid)
                cat.save()
                messages.add_message(request,messages.INFO,'categry [%s] save ok!'%(name))
        except Exception as e:
            print 'exception:',e
    elif type and type == 'edit':
        id = request.POST.get('id','')
        cat = Category.objects.get(id=id)
        cat.name=name
        cat.slug=slug
        cat.desc=desc
        cat.parent_id = pid
        cat.save()
    return HttpResponseRedirect('/admin/categories')
Exemplo n.º 14
0
    def test_delete_post(self):
        # Create the category
        category = Category()
        category.name = 'python'
        category.description = 'The Python programming language'
        category.save()

        # Create the tag
        tag = Tag()
        tag.name = 'python'
        tag.description = 'The Python programming language'
        tag.save()

        # Create the author
        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # Create the site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()
        
        # Create the post
        post = Post()
        post.title = 'My first post'
        post.text = 'This is my first blog post'
        post.slug = 'my-first-post'
        post.pub_date = timezone.now()
        post.site = site
        post.author = author
        post.category = category
        post.save()
        post.tags.add(tag)
        post.save()

        # Check new post saved
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)

        # Log in
        self.client.login(username='******', password="******")

        # Delete the post
        response = self.client.post('/admin/blogengine/post/1/delete/', {
            'post': 'yes'
        }, follow=True)
        self.assertEquals(response.status_code, 200)

        # Check deleted successfully
        self.assertTrue('deleted successfully' in response.content)

        # Check post deleted
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 0)
Exemplo n.º 15
0
    def test_category_page(self):
        # Create the category
        category = Category()
        category.name = 'python'
        category.description = 'The Python programming language'
        category.save()

        # Create the author
        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # Create the site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()

        # Create the post
        post = Post()
        post.title = 'My first post'
        post.text = 'This is [my first blog post](http://127.0.0.1:8000/)'
        post.slug = 'my-first-post'
        post.pub_date = timezone.now()
        post.author = author
        post.site = site
        post.category = category
        post.save()

        # Check new post saved
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)
        only_post = all_posts[0]
        self.assertEquals(only_post, post)

        # Get the category URL
        category_url = post.category.get_absolute_url()

        # Fetch the category
        response = self.client.get(category_url)
        self.assertEquals(response.status_code, 200)

        # Check the category name is in the response
        self.assertTrue(post.category.name in response.content)

        # Check the post text is in the response
        self.assertTrue(markdown.markdown(post.text) in response.content)

        # Check the post date is in the response
        self.assertTrue(str(post.pub_date.year) in response.content)
        self.assertTrue(post.pub_date.strftime('%b') in response.content)
        self.assertTrue(str(post.pub_date.day) in response.content)

        # Check the link is marked up properly
        self.assertTrue('<a href="http://127.0.0.1:8000/">my first blog post</a>' in response.content)
Exemplo n.º 16
0
    def test_index(self):
        category = Category()
        category.name = 'python'
        category.description = 'The python language'
        category.save()

        # Create the tag
        tag = Tag()
        tag.name = 'perl'
        tag.description = 'The Perl programming language'
        tag.save()

        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # site = Site()
        # site.name = 'nunfuxgvn.com'
        # site.domain = 'nunfuxgvn.com'
        # site.save()

        post = Post()
        post.title = 'First Post'
        post.content = 'My [first post](http://127.0.0.1:8000/) -yay'
        post.slug = 'first-post'
        post.pub_date = timezone.now()
        post.author = author
        # post.site = site
        post.category = category
        post.save()
        post.tags.add(tag)

        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)

        # Fetch test_index
        response = self.client.get('/')
        self.assertEquals(response.status_code, 200)

        self.assertTrue(post.title in response.content)

        self.assertTrue(markdown.markdown(post.content) in response.content)

        self.assertTrue(post.category.name in response.content)

        post_tag = all_posts[0].tags.all()[0]
        self.assertTrue(post_tag.name in response.content)

        self.assertTrue(str(post.pub_date.year) in response.content)
        self.assertTrue(post.pub_date.strftime('%b') in response.content)
        self.assertTrue(str(post.pub_date.day) in response.content)

        self.assertTrue('<a href="http://127.0.0.1:8000/">first post</a>' in response.content)
Exemplo n.º 17
0
def addCategory(request):
    if request.method=='POST':
        name = request.POST['name']
        slug = request.POST['slug']
        desc = request.POST['desc']
        type = request.POST['type']
        if type and type == 'add':
            try:
                cats=Category.objects.filter(name=name)
                if cats.count() >= 1:
                    messages.add_message(request,messages.INFO,'categry [%s] already exits!'%(name))
                else:
                    cat = Category(name=name,slug=slug,desc=desc)
                    cat.save()
                    messages.add_message(request,messages.INFO,'categry [%s] save ok!'%(name))
            except:
                pass
                
        elif type and type == 'edit':
            id = request.POST.get('id','')
            cat = Category.objects.get(id=id)
            cat.name=name
            cat.slug=slug
            cat.desc=desc
            cat.save()
        return HttpResponseRedirect('/admin/categories')
Exemplo n.º 18
0
    def post(self):
        try:
            category_name = self.request.POST.get('category_name')
            category_description = self.request.POST.get('category_description')
            category_visible = self.request.POST.get('category_visible')
            edit_categoryid = self.request.POST.get('editcategoryid')

            if edit_categoryid:
                Category.update_category(edit_categoryid, category_name, category_description, category_visible == u'on')
            else:
                Category.create_category(category_name, category_description, category_visible == u'on')

            self.redirect('/admin/categorylist')
        except:
            self.redirect('/500.html')
Exemplo n.º 19
0
    def GET(self,slug=None):
        action=self.param("action")
        key=self.param('key')
        category=None
        if action and  action=='edit':
                try:

                    category=Category.get(key)

                except:
                    pass
        else:
            action='add'
        vals={'action':action,'category':category,'key':key,'categories':[c for c in Category.all() if not category or c.key()!=category.key()]}
        self.render2('views/admin/category.html',vals)
Exemplo n.º 20
0
 def post(self):
     self._context['form_args'] = {'heading':self._form_heading}
     self._form = self._form(request.form)
     if self._form.validate():
         from blog.models import Category
         c = Category.query.filter(Category.name==self._form.name.data).first()
         if c is None:
             c = Category()
             c.name = self._form.name.data
             c.description = self._form.description.data
             c.save()
             self.flash('You added category: {}'.format(c.name))
         else:
             self.flash('There is already a category by that name, try again')
     return self.render()
Exemplo n.º 21
0
def article_create():
    form = ArticleCreateForm()
    form.category_id.choices = Category.choices()
    if request.method == 'POST' and form.validate():
        if not g.user.is_admin():
            flash(u'非管理员不能创建文章!')
            return redirect(url_for('index'))
        else:
            nowtime = datetime.datetime.now()
            article = Article(title=form.title.data,
                              body=form.body.data,
                              user_id=g.user.id,
                              category_id=form.category_id.data,
                              text=request.form.get('textformat'),
                              timestamp=nowtime,
                              tag=form.tag.data,
                              is_open=form.is_open.data)
            article.post_date = nowtime
            db.session.add(article)
            db.session.commit()
            flash(u'文章已创建!')
            Blog_info.new_article()
            return redirect(url_for('article_edit', id=article.id))
    return render_template('article_create.html',
                           title=u'创建文章',
                           form=form)
Exemplo n.º 22
0
def addCategory(request):
	categories=Category.objects.all();
	addCategory=True;
	displayForm=True;	
	if request.method=='POST':
		form=CategoryForm(request.POST)
		if form.is_valid():
			title=form.cleaned_data['title'];
			envoi=True
			#creation of the section object
			category=Category(title=title)
			category.save();
			return home(request)
	else:
		form=CategoryForm()
	return render(request, 'blog/blogForm.html',locals())		
Exemplo n.º 23
0
    def GET(self,tags=None):
        try:
            all=self.param('all')
        except:
            all=False

        if(all):
            entries = Entry.all().order('-date')
            filename='micolog.%s.xml'%datetime.now().strftime('%Y-%m-%d')
        else:
            str_date_begin=self.param('date_begin')
            str_date_end=self.param('date_end')
            try:
                date_begin=datetime.strptime(str_date_begin,"%Y-%m-%d")
                date_end=datetime.strptime(str_date_end,"%Y-%m-%d")
                entries = Entry.all().filter('date >=',date_begin).filter('date <',date_end).order('-date')
                filename='micolog.%s.%s.xml'%(str(str_date_begin),str(str_date_end))
            except:
                self.render2('views/admin/404.html')

        cates=Category.all()
        tags=Tag.all()

        self.response.headers['Content-Type'] = 'binary/octet-stream'#'application/atom+xml'
        self.response.headers['Content-Disposition'] = 'attachment; filename=%s'%filename
        self.render2('views/wordpress.xml',{'entries':entries,'cates':cates,'tags':tags})
Exemplo n.º 24
0
def generate_sitemap():
	"""Deferred task to generate a Sitemap.xml for all published blog posts"""

	root = etree.Element('urlset', { 'attr': 'http://www.sitemaps.org/schemas/sitemap/0.9' })

	def add_url(location, last_modified=None, change_freq='always', priority=0.5):
		e = etree.SubElement(root, 'url')
		etree.SubElement(e, 'loc').text = location
		if last_modified:
			etree.SubElement(e, 'lastmod').text = last_modified.strftime('%Y-%m-%dT%H:%M:%S+00:00')
		etree.SubElement(e, 'changefreq').text = change_freq
		etree.SubElement(e, 'priority').text = str(priority)

	for p in Post.objects_published().order('-created_at'):
		add_url(p.absolute_url(external=True), p.updated_at)

	for c in Category.all():
		add_url(c.absolute_url(external=True))

	add_url(url_for('blog.index', _external=True), priority=1.0)
	add_url(url_for('blog.latest_posts', _external=True))

	logging.info('Generated sitemap.xml with %d blog posts', len(root))
	xml = etree.tostring(root, encoding='utf-8', pretty_print=True, xml_declaration=True)
	cache.set('blog_sitemaps', xml)
	return xml
Exemplo n.º 25
0
    def GET(self,tags=None):
        urls = []
        def addurl(loc,lastmod=None,changefreq=None,priority=None):
            url_info = {
                'location':   loc,
                'lastmod':    lastmod,
                'changefreq': changefreq,
                'priority':   priority
            }
            urls.append(url_info)

        addurl(self.blog.baseurl,changefreq='daily',priority=0.9 )

        entries = Entry.all().filter(published = True).order_by('-date')[0:self.blog.sitemap_entries]#.fetch(self.blog.sitemap_entries)

        for item in entries:
            loc = "%s/%s" % (self.blog.baseurl, item.link)
            addurl(loc,item.mod_date or item.date,'never',0.6)

        if self.blog.sitemap_include_category:
            cats=Category.all()
            for cat in cats:
                loc="%s/category/%s"%(self.blog.baseurl,cat.slug)
                addurl(loc,None,'weekly',0.5)

        if self.blog.sitemap_include_tag:
            tags=Tag.all()
            for tag in tags:
                loc="%s/tag/%s"%(self.blog.baseurl, urlencode(tag.tag))
                addurl(loc,None,'weekly',0.5)


##        self.response.headers['Content-Type'] = 'application/atom+xml'
        self.render('/admin/views/sitemap.xml', {'urlset':urls}, content_type='text/xml')#, content_type='application/xhtml+xml')
Exemplo n.º 26
0
def category_list(request):
	try:
		category_list = Category.objects.all()
		print request.session.session_key
		return HttpResponse(Category.to_json_list(category_list), content_type="application/json")
	except Exception, e:
		return HttpResponse(response_json.fail(traceback.format_exc()))
Exemplo n.º 27
0
def new_post(request):
    """
    Create a new Post
    """
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            #Separate the tags we have seen before from those we haven't
            tags = form.cleaned_data['tags'].split(' ')
            known_tags = list(Tag.objects.filter(tag__in=tags))
            unknown_tag_names = set(tags) - set(x.tag for x in known_tags)
            #Create the unknown tags
            unknown_tags = [Tag(tag=x) for x in unknown_tag_names]
            #Tag.objects.bulk_create(unknown_tags)  # Sadly, this doesn't work.
            [t.save() for t in unknown_tags]

            #If category doesn't exist, create it
            try:
                category = Category.objects.get(name=form.cleaned_data['category'])
            except Category.DoesNotExist:
                category = Category(name=form.cleaned_data['category'], description='')
                category.save()

            #Create the Post object
            post = Post(
                user = request.user,
                category = category,
                title = form.cleaned_data['title'],
                body = form.cleaned_data['body'],
                date = datetime.now()
            )
            post.save()
            #You must create a primary key (by saving an object),
            #before you can use a many to many relationship
            post.tags.add(*(known_tags + unknown_tags))
            post.save()
            return HttpResponseRedirect('/')
        else:
            messages.error(request, 'Invalid post')
            return HttpResponseRedirect(reverse('new_post'))
    else:
        form = PostForm()

    return render(request, 'new_post.html', {
        'form': form,
    })
Exemplo n.º 28
0
def init_data(**kwargs):
    link=Link(text="dengmin's blog",href="http://www.iyouf.info")
    link.save()
    
    default_cate=Category(name=u'未分类',slug='default',desc=u'未分类')
    default_cate.save()
    
    entry=Entry(title='Hello World!',content='<b>Hello World, welcome to use youflog! thank you!</a>',tags='youflog')
    entry.allow_comment=True
    entry.slug='hello-world'
    entry.category=default_cate
    entry.author_id=1
    entry.save(True)
    
    comment=Comment(author='admin',email='*****@*****.**',weburl='http://iyouf.info',content=u'测试第一条评论')
    comment.content_object=entry
    comment.save()
Exemplo n.º 29
0
    def test_delete_post(self):
        category = Category()
        category.name = 'python'
        category.description = 'The python language'
        category.save()

        # Create the tag
        tag = Tag()
        tag.name = 'python'
        tag.description = 'The Python programming language'
        tag.save()

        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # site = Site()
        # site.name = 'nunfuxgvn.com'
        # site.domain = 'nunfuxgvn.com'
        # site.save()

        post = Post()
        post.title = 'First Post'
        post.test = 'My first post'
        post.slug = 'first-post'
        post.pub_date = timezone.now()
        post.author = author
        # post.site = site
        post.save()
        post.tags.add(tag)
        post.save()

        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/blog/post/1/delete/', {
            'post': 'yes'
        }, follow=True)
        self.assertEquals(response.status_code, 200)

        self.assertTrue('deleted successfully' in response.content)

        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 0)
Exemplo n.º 30
0
def new_category():
    form = CategoryForm()
    if form.validate_on_submit():
        name = form.name.data
        category = Category(name=name)
        db.session.add(category)
        db.session.commit()
        return redirect(url_for('.manage_category'))
    return render_template('admin/new_category.html', form=form)
Exemplo n.º 31
0
def post_detail(request, post_id):
    post = Post.objects.filter(id=post_id).first()
    handle_visited(request, post_id)
    context = {
        'post': post,
        'sidebars': SideBar.get_all(),
    }
    context.update(Category.get_navs())
    return render(request, 'blog/detail.html', context=context)
Exemplo n.º 32
0
def categoryAdd(request):
    if request.method == "POST":
        name = request.POST.get("name")
        try:
            category = Category()
            category.name = name
            category.save()
            result = {
                "code": "1",
                "msg": "添加成功!",
            }
        except Exception as e:
            print(e)
            result = {
                "code": "0",
                "msg": "添加失败!",
            }
        return JsonResponse(result)
Exemplo n.º 33
0
    def test_creating_a_new_category_and_saving_it_to_the_database(self):
        # start by createing a new Category object
        category = Category()
        category.name = "First"
        category.slug = "first"

        # check we can save it to the database
        category.save()

        # now check we can find it in the database again
        all_category_in_database = Category.objects.all()
        self.assertEquals(len(all_category_in_database), 1)
        only_category_in_database = all_category_in_database[0]
        self.assertEquals(only_category_in_database, category)

        # and check that it's saved its two attributes: name and slug
        self.assertEquals(only_category_in_database.name, category.name)
        self.assertEquals(only_category_in_database.slug, category.slug)
Exemplo n.º 34
0
 def setUp(self):
     self.u = User("Test User", "*****@*****.**", "password")
     self.c = Category("Test Category")
     self.p = Post("Test Post Title",
                   "Test Post Content",
                   self.u,
                   self.c,
                   code=True,
                   hidden=True)
Exemplo n.º 35
0
    def test_saving_retrieving_post(self):
        category = Category(name="テストカテゴリー")
        category.save()
        tag = Tag(name="テストタグ")
        tag.save()
        post = Post(category=category,
                    title="test_title",
                    body="test_body",
                    published=1)
        post.save()

        saved_posts = Post.objects.all()
        actual_post = saved_posts[
            0]  #0は、saved_postsというリストから最初の値を取り出すという意味。2番目の値を取り出すなら1

        self.assertEqual(actual_post.title, "test_title")
        self.assertEqual(actual_post.body, "test_body")
        self.assertEqual(actual_post.published, 1)
Exemplo n.º 36
0
def post_detail(request, post_id=None):
    try:
        post = Post.objects.get(id=post_id)
    except Post.DoesNotExist:
        post = None

    context = {'post': post, 'sidebars': SideBar.get_all()}
    context.update(Category.get_navs())
    return render(request, 'blog/detail.html', context=context)
Exemplo n.º 37
0
    def test_validate_comment(self):
        site = get_current_site().domain
        user = BlogUser.objects.create_superuser(email="*****@*****.**",
                                                 username="******", password="******")

        self.client.login(username='******', password='******')

        c = Category()
        c.name = "categoryccc"
        c.created_time = datetime.datetime.now()
        c.last_mod_time = datetime.datetime.now()
        c.save()

        article = Article()
        article.title = "nicetitleccc"
        article.body = "nicecontentccc"
        article.author = user
        article.category = c
        article.type = 'a'
        article.status = 'p'
        article.save()
        s = TextMessage([])
        s.content = "nicetitleccc"
        rsp = search(s, None)
        self.assertTrue(rsp != '没有找到相关文章。')
        rsp = category(None, None)
        self.assertIsNotNone(rsp)
        rsp = recents(None, None)
        self.assertTrue(rsp != '暂时还没有文章')

        cmd = commands()
        cmd.title = "test"
        cmd.command = "ls"
        cmd.describe = "test"
        cmd.save()

        cmdhandler = CommandHandler()
        rsp = cmdhandler.run('test')
        self.assertIsNotNone(rsp)
        s.source = 'u'
        s.content = 'test'
        msghandler = MessageHandler(s, {})

        #msghandler.userinfo.isPasswordSet = True
        #msghandler.userinfo.isAdmin = True
        msghandler.handler()
        s.content = 'y'
        msghandler.handler()
        s.content='idcard:12321233'
        msghandler.handler()
        s.content='weather:上海'
        msghandler.handler()
        s.content='admin'
        msghandler.handler()
        s.content='123'
        msghandler.handler()

        s.content = 'exit'
        msghandler.handler()
Exemplo n.º 38
0
def post():

    if session.get('user') is None:

        return redirect(url_for('login'))

    form = PostForm()

    categories = Category.query.all()

    if request.method == 'POST':

        if form.validate_on_submit():

            if form.category.data:

                category = form.category.data

            elif form.new_category.data:

                category = form.new_category.data
                new_category = Category(category)
                db.session.add(new_category)
                db.session.commit()

            else:

                return "Not Category Entered by User !!"

            title = form.title.data
            body = form.body.data

            #print("Category = {0}".format(category))

            #slug = slugify(title).encode('utf-8')
            slug = title
            author_id = Author.query.filter_by(name=session['user']).first().id
            category_id = Category.query.filter_by(
                name=str(category)).first().id
            blog_id = Blog.query.first().id
            publish_date = datetime.utcnow()

            #print('Slug = {0},Author ID = {1}, Category = {2}'.format(slug, author_id, category_id))

            post = Post(title, body, slug, blog_id, author_id, category_id,
                        publish_date)
            db.session.add(post)
            db.session.commit()

            return render_template('blog/post_helper.html',
                                   post=post,
                                   categories=categories)

    return render_template('author/post.html',
                           form=form,
                           categories=categories)
Exemplo n.º 39
0
def addcategory():
    form=CategoryForm()
    if form.validate_on_submit():
        name=form.name.data
        category=Category(name=name)
        db.session.add(category)
        db.session.commit()
        flash(f'Category Created Successfully','success')
        return redirect(url_for('index'))
    return render_template('addcategory.html',form=form)
Exemplo n.º 40
0
def add_category():
    form = category_form()
    if form.validate_on_submit():
        name = form.name.data
        category = Category(name=name)
        db.session.add(category)
        db.session.commit()
        flash('Added', 'success')
        return redirect(url_for('.manage_category'))
    return render_template('manage/add_category.html', form=form)
Exemplo n.º 41
0
    def setUp(self):
        super(AdminTestCase, self).setUp()
        self.login()

        category = Category(name='Default')
        post = Post(title='Hello', category=category, body='Blah...')
        comment = Comment(body='A comment', post=post, from_admin=True)
        link = Link(name='GitHub', url='https://github.com/greyli')
        db.session.add_all([category, post, comment, link])
        db.session.commit()
Exemplo n.º 42
0
def category():
    form=CategoryForm()
    if form.validate_on_submit():
        category=Category(name=form.name.data)
        db.session.add(category)
        db.session.commit()
        flash('Your Category Created Succefully','success')
        return redirect(url_for('category'))

    return render_template('category.html',title='New Post',form=form)
Exemplo n.º 43
0
def _get_form_category_data(form):

    if form.new_category.data:
        new_category = Category(form.new_category.data)
        db.session.add(new_category)
        db.session.flush()
        category = new_category
    else:
        category = form.category.data
    return category
Exemplo n.º 44
0
def new_category():
    form = CategoryForm()
    if form.validate_on_submit():
        name = form.name.data
        category = Category(name=name)
        db.session.add(category)
        db.session.commit()
        flash('Category created.', 'success')
        return redirect(url_for('blog.index'))
    return render_template('admin/new_category.html', form=form)
Exemplo n.º 45
0
class TestCategoryView(TestCase):
    def setUp(self):
        self.c = Category(title="MyTitle")
        self.c.save()

    def test_view_url_exists_at_desired_location(self):
        resp = self.client.get('/blog/categories/%s/' % self.c.id)
        self.assertEqual(resp.status_code, 200)

    def test_view_url_accessible_by_name(self):
        resp = self.client.get(
            reverse('blog:view_blog_category', args=(self.c.id, )))
        self.assertEqual(resp.status_code, 200)

    def test_view_uses_correct_template(self):
        resp = self.client.get(
            reverse('blog:view_blog_category', args=(self.c.id, )))
        self.assertEqual(resp.status_code, 200)
        self.assertTemplateUsed(resp, 'blog/view_category.html')
    def handle(self, *args, **kwargs):

        num_users = kwargs['user']
        num_categories = kwargs['category']
        num_posts = kwargs['post']

        self.stdout.write("Cleaning database...")

        User.objects.all().delete()
        Category.objects.all().delete()
        Post.objects.all().delete()

        # Create users
        self.stdout.write(
            self.style.HTTP_NOT_MODIFIED(f"Creating { num_users } users..."))

        users = [User(name=f'User-{ index }') for index in range(num_users)]
        User.objects.bulk_create(users)

        # Create profiles
        self.stdout.write(
            self.style.HTTP_NOT_MODIFIED(
                f"Creating { num_users } profiles..."))

        profiles = [
            Profile(address=f'Address-{ user.name }', user=user)
            for user in User.objects.all()
        ]
        Profile.objects.bulk_create(profiles)

        # Create categories
        self.stdout.write(
            self.style.HTTP_NOT_MODIFIED(
                f"Creating { num_categories } categories..."))
        categories = [
            Category(name=f'Category-{ index }')
            for index in range(num_categories)
        ]
        Category.objects.bulk_create(categories)

        # Create posts
        self.stdout.write(
            self.style.HTTP_NOT_MODIFIED(
                f"Creating { num_posts*num_users } posts..."))

        for user in User.objects.all():
            for i in range(num_posts):
                new_post = Post(title=f"Post-{ i + 1 }", owner=user)
                new_post.save()
                new_post.categories.add(Category.objects.first())

        self.stdout.write(
            self.style.SUCCESS(
                f"SUCCESS: { num_users } users, { num_users } profiles, { num_categories } categories, { num_posts*num_users } posts"
            ))
Exemplo n.º 47
0
def post():
    form = PostForm()
    tags_field = request.values.get('tags_field', '')

    if form.validate_on_submit():
        image_id = None

        # картинка
        if form.image.data:
            f = form.image.data
            image_id = str(uuid.uuid4())
            file_name = image_id + '.png'
            file_path = os.path.join(
                BLOG_POST_IMAGES_PATH, file_name
            )
            Image.open(f).save(file_path)
            # приведем изображение к рамзеру 600 на 300 pix
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 600, 'lg')
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 300, 'sm')
        # проверка есть ли искомая категория поста
        if form.new_category.data:
            new_category = Category(form.new_category.data)
            db.session.add(new_category)
            db.session.flush() #
            category = new_category
        else:
            category = form.category.data
 
        author = Author.query.get(session['id'])
        title = form.title.data.strip()
        body = form.body.data.strip()
        post = Post(
            author=author,
            title=title,
            body=body,
            image = image_id,
            category=category,
        )

        _save_tags(post, tags_field)

        db.session.add(post)
        db.session.commit()

        slug = slugify(str(post.id) + '-' + post.title)
        post.slug = slug
        db.session.commit()

        flash('Сообщение опубликовано')
        return redirect(url_for('.article', slug=slug))

    return render_template('blog/post.html', form=form, 
                                             action="new", 
                                             tags_field=tags_field
                )  #action for editing    
Exemplo n.º 48
0
 def setUpClass(cls):
     cls.app = app.test_client()
     db.create_all()
     test_user = User("Test User", "*****@*****.**", "password")
     db.session.add(test_user)
     test_category = Category("Test Category")
     db.session.add(test_category)
     test_post = Post("Post Title", "Post Content", test_user,
                      test_category)
     db.session.add(test_post)
     db.session.commit()
Exemplo n.º 49
0
def post():
    form = PostForm()
    tags_field = request.values.get('tags_field', '')

    if form.validate_on_submit():
        image_id = None

        if form.image.data:
            # process image
            f = form.image.data
            image_id = str(uuid.uuid4())
            file_name = image_id + '.png'
            file_path = os.path.join(BLOG_POST_IMAGES_PATH, file_name)
            Image.open(f).save(file_path)

            # create sizes
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 600, 'lg')
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 300, 'sm')

        if form.new_category.data:
            new_category = Category(form.new_category.data)
            db.session.add(new_category)
            db.session.flush()
            category = new_category
        else:
            category = form.category.data

        author = Author.query.get(session['id'])
        title = form.title.data.strip()
        body = form.body.data.strip()
        post = Post(author=author,
                    title=title,
                    body=body,
                    category=category,
                    image=image_id)

        # process tags
        _save_tags(post, tags_field)

        db.session.add(post)
        db.session.commit()

        # do the slug
        slug = slugify(str(post.id) + '-' + post.title)
        post.slug = slug
        db.session.commit()

        flash('Article posted')
        return redirect(url_for('.article', slug=slug))

    return render_template('blog/post.html',
                           form=form,
                           action="new",
                           tags_field=tags_field)
Exemplo n.º 50
0
def seed():
    """Seeds test data"""
    PostCategory.query.delete()
    Category.query.delete()
    Comment.query.delete()
    Post.query.delete()
    User.query.delete()

    programming = Category(name="programming")
    finance = Category(name="finance")
    travel = Category(name="travel")
    general = Category(name="general")
    categories = [programming, finance, travel, general]

    comments = []
    for _ in range(1000):
        comments.append(
            Comment(
                commenter=fake.user_name(),
                comment=fake.sentence(nb_words=30, variable_nb_words=True),
            )
        )

    for _ in range(100):
        user = User(username=fake.user_name(), email=fake.email())
        for _ in range(100):
            post = Post(
                title=fake.bs(),
                body=fake.paragraph(nb_sentences=30, variable_nb_sentences=True),
            )
            post.comments = fake.random_elements(
                comments, length=fake.random_int(0, 100), unique=True
            )
            post.categories = fake.random_elements(
                categories, length=fake.random_int(1, 4), unique=True
            )
            user.posts.append(post)
        db.session.add(user)

    db.session.commit()
    db.session.close_all()
Exemplo n.º 51
0
    def test_edit_category(self):
        # Create the category
        category = Category()
        category.name = 'python'
        category.description = 'The Python programming language'
        category.save()

        # Log in
        self.client.login(username='******', password="******")

        # Edit the category
        response = self.client.post(
            '/admin/blog/category/1/', {
                'name': 'perl',
                'description': 'The Perl programming language'
            },
            follow=True)
        self.assertEquals(response.status_code, 200)

        # Check modificado com sucesso
        self.assertTrue('modificado com sucesso' in response.content)

        # Check category amended
        all_categories = Category.objects.all()
        self.assertEquals(len(all_categories), 1)
        only_category = all_categories[0]
        self.assertEquals(only_category.name, 'perl')
        self.assertEquals(only_category.description,
                          'The Perl programming language')
Exemplo n.º 52
0
    def test_create_post_without_tag(self):
        # Create the category
        category = Category()
        category.name = 'python'
        category.description = 'The Python programming language'
        category.save()

        # Log in
        self.client.login(username='******', password="******")

        # Check response code
        response = self.client.get('/admin/blog/post/add/')
        self.assertEquals(response.status_code, 200)

        # Create the new post
        response = self.client.post('/admin/blog/post/add/', {
            'title': 'My first post',
            'text': 'This is my first post',
            'pub_date_0': '2013-12-28',
            'pub_date_1': '22:00:04',
            'slug': 'my-first-post',
            'site': '1',
            'category': '1'
        },
                                    follow=True)
        self.assertEquals(response.status_code, 200)

        # Check added successfully
        self.assertTrue('adicionado com sucesso' in response.content)

        # Check new post now in database
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)
Exemplo n.º 53
0
    def test_validate_register(self):
        self.assertEquals(0, len(BlogUser.objects.filter(email='*****@*****.**')))
        response = self.client.post(reverse('account:register'), {
            'username': '******',
            'email': '*****@*****.**',
            'password1': 'password123!q@wE#R$T',
            'password2': 'password123!q@wE#R$T',
        })
        self.assertEquals(1, len(BlogUser.objects.filter(email='*****@*****.**')))
        user = BlogUser.objects.filter(email='*****@*****.**')[0]
        sign = get_md5(get_md5(settings.SECRET_KEY + str(user.id)))
        path = reverse('accounts:result')
        url = '{path}?type=validation&id={id}&sign={sign}'.format(path=path, id=user.id, sign=sign)
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        self.client.login(username='******', password='******')
        user = BlogUser.objects.filter(email='*****@*****.**')[0]
        user.is_superuser = True
        user.is_staff = True
        user.save()
        delete_sidebar_cache(user.username)
        category = Category()
        category.name = "categoryaaa"
        category.created_time = datetime.datetime.now()
        category.last_mod_time = datetime.datetime.now()
        category.save()

        article = Article()
        article.category = category
        article.title = "nicetitle333"
        article.body = "nicecontentttt"
        article.author = user

        article.type = 'a'
        article.status = 'p'
        article.save()

        response = self.client.get(article.get_admin_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get(reverse('account:logout'))
        self.assertIn(response.status_code, [301, 302, 200])

        response = self.client.get(article.get_admin_url())
        self.assertIn(response.status_code, [301, 302, 200])

        response = self.client.post(reverse('account:login'), {
            'username': '******',
            'password': '******'
        })
        self.assertIn(response.status_code, [301, 302, 200])

        response = self.client.get(article.get_admin_url())
        self.assertIn(response.status_code, [301, 302, 200])
Exemplo n.º 54
0
def article_edit(id):
    form = ArticleEditForm()
    form.category_id.choices = Category.choices()
    article = Article.find_by_id(int(id))
    form.title.data = article.title
    form.body.data = article.body
    form.tag.data = article.tag
    form.category_id.data = article.category_id
    form.is_open.data = article.is_open
    form.id.data = id
    return render_template('article_edit.html',
                           title=u'编辑' + article.title,
                           form=form)
Exemplo n.º 55
0
def list_category(request, category_id):
    category = Category.get_by_id( int(category_id) )

    posts = category.posts.order('-create_time')

    return object_list(request,
                       template_object_name = 'post',
                       queryset = posts,
                       extra_context = { 'cort':category, 'type':'Category' },
                       allow_empty = True,
                       template_name = 'page.html',
                       paginate_by = LIST_PER_PAGE,
                       )
Exemplo n.º 56
0
def new_category():
    try:
        category = request.json.get('category')
        article_ids = request.json.get('articles')
    except AttributeError:
        abort(400)
    print(category)
    if category:
        try:
            articles = [Article.query.get(id) for id in article_ids]
        except BaseException:
            abort(400)
        try:
            c = Category()
            c.name = category
            c.articles = articles
            db.session.add(c)
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            return jsonify({'status': '400', 'msg': '分类名重复'}), 400
        return jsonify({'status': 200})
    return jsonify({'status': 404}), 404
Exemplo n.º 57
0
    def test_category_page(self):
        # Create the category
        category = Category()
        category.name = 'python'
        category.description = 'The Python programming language'
        category.save()

        # Create the author
        author = User.objects.create_user('testuser', '*****@*****.**',
                                          'password')
        author.save()

        # Create the site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()

        # Create the post
        post = Post()
        post.title = 'My first post'
        post.text = 'This is [my first blog post](http://127.0.0.1:8000/)'
        post.slug = 'my-first-post'
        post.pub_date = timezone.now()
        post.author = author
        post.site = site
        post.category = category
        post.save()

        # Check new post saved
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)
        only_post = all_posts[0]
        self.assertEquals(only_post, post)

        # Get the category URL
        category_url = post.category.get_absolute_url()

        # Fetch the category
        response = self.client.get(category_url)
        self.assertEquals(response.status_code, 200)

        # Check the category name is in the response
        self.assertTrue(post.category.name in response.content)

        # Check the post text is in the response
        self.assertTrue(
            markdown.markdown(post.text).encode() in response.content)

        # Check the post date is in the response
        self.assertTrue(str(post.pub_date.year) in response.content)
        self.assertTrue(
            _date(post.pub_date, "F").encode('utf-8') in response.content)
        self.assertTrue(str(post.pub_date.day) in response.content)

        # Check the link is marked up properly
        self.assertTrue(
            '<a href="http://127.0.0.1:8000/">my first blog post</a>' in
            response.content)
Exemplo n.º 58
0
def post_detail(request, post_id=None):
    # return HttpResponse('detail')
    # return render(request, 'blog/detail.html', context={'name': 'post_detail'})
    try:
        post = Post.objects.get(id=post_id)
    except Post.DoesNotExist:
        post = None
    context = {
        'post': post,
        'sidebars': SideBar.get_all(),
    }
    context.update(Category.get_navs())
    return render(request, 'blog/detail.html', context={'post': post})
Exemplo n.º 59
0
def post_list(request, category_id=None, tag_id=None):
    tag = None
    category = None

    '''
    if tag_id:
        try :
            tag = Tag.objects.get(id=tag_id)
        except Tag.DoesNotExist:
            post_list = []
        else:
            post_list = tag.post_set.filter(status=Post.STATUS_NORMAL)
    else:
        post_list = Post.objects.filter(status=Post.STATUS_NORMAL)
        if category_id:
            try:
                category = Category.objects.get(id=category_id)
            except Category.DoesNotExist:
                category = None
            else:
                post_list = post_list.Filter(category_id=category_id)

    context = {
        'category':category,
        'tag':tag,
        'post_list':post_list,
    }
    return render(request, 'blog/list.html', context=context)
    '''

    '''
    如果查询到不存在的对象,需要通过try...except...来捕获并处理异常,避免当数据不存在时出现错误
    tag与post是多对多关系,因此需要先获取tag对象,接着通过该对象来获取对应的文章列表。
    '''
    if tag_id:
        post_list, tag = Post.get_by_tag(tag_id)
    elif category_id:
        post_list, category = Post.get_by_category(category_id)
    else:
        post_list = Post.latest_posts()


    from config.models import SideBar
    context = {
        'category':category,
        'tag': tag,
        'post_list': post_list,
        'sidebars': SideBar.get_all(),
    }
    context.update(Category.get_navs())
    return render(request, 'blog/list.html', context=context)
Exemplo n.º 60
0
def edit(slug):
    post = Post.query.filter_by(slug=slug).first_or_404()
    form = PostForm(obj=post)
    tags_field = request.values.get('tags_field', _load_tags_field(post))

    if form.validate_on_submit():
        original_image = post.image
        original_title = post.title
        form.populate_obj(post)

        if form.image.data:
            f = form.image.data
            image_id = str(uuid.uuid4())
            file_name = image_id + '.png'
            file_path = os.path.join(BLOG_POST_IMAGES_PATH, file_name)
            Image.open(f).save(file_path)

            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 600, 'lg')
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 300, 'sm')

            post.image = image_id
        else:
            post.image = original_image

        if form.new_category.data:
            new_category = Category(form.new_category.data)
            db.session.add(new_category)
            db.session.flush()
            post.category = new_category

            #if form.new_goverment.data:
            #    new_goverment = Goverment(form.new_goverment.data)
            #    db.session.add(new_goverment)
            #    db.session.flash()
            post.goverment = new_goverment

        if form.title.data != original_title:
            post.slug = slugify(str(post.id) + '-' + form.title.data)

        _save_tags(post, tags_field)

        db.session.commit()
        flash('Article edited')
        return redirect(url_for('.article', slug=post.slug))

    return render_template('blog/post.html',
                           form=form,
                           post=post,
                           action="edit",
                           tags_field=tags_field)