예제 #1
0
    def test_article_get(self):
        r = self.client.get(self.url + '/article')
        self.assertEqual(r.status_code, 401)
        article = Article()
        article.title = 'title-test'
        article.slug = 'test'
        article.content = 'content ' * 20
        db.session.add(article)
        db.session.commit()
        r = self.client.get(self.url + '/article?slug=test')
        self.assertEqual(r.status_code, 401)

        tag = Tag()
        tag.name = 'tag'
        db.session.add(tag)
        category = Category()
        category.name = 'category'
        db.session.add(category)
        db.session.commit()
        article = Article()
        article.title = 'article'
        article.slug = 'slug'
        article.category = category
        article.content = 'content'
        article.tags = [tag]
        db.session.add(category)
        db.session.commit()
        r = self.client.get(self.url + '/article?slug=slug')
        self.assertEqual(r.status_code, 401)
예제 #2
0
    def post(self, request, *args, **kwargs):
        article_id = self.json_data.get("article_id")
        title = self.json_data.get("title")
        if not title:
            res = codedesc.JSON_ERR
            res["msg"] = u"标题不能为空"
            return JsonResponse(res)
        content = self.json_data.get("content")
        if not content:
            res = codedesc.JSON_ERR
            res["msg"] = u"内容不能为空"
            return JsonResponse(res)

        res = codedesc.OK
        if not article_id:
            article = Article(title=title,
                              content=content,
                              author=request.user)
        else:
            article = Article.objects.filter(id=article_id).first()
            if not article:
                res = codedesc.JSON_ERR
                res["msg"] = u"article_id有误"
                return JsonResponse(res)
            article.title = title
            article.content = content
        article.save()
        res["article_id"] = article.id

        return JsonResponse(res)
예제 #3
0
def post(request):

    now=time.localtime()
    article =Article()
    if request.POST.has_key('content'):
        article.author = cgi.escape(request.POST['author'].decode('utf-8'))
        article.content = request.POST['content'].decode('utf-8')
        article.tags = request.POST['tags'].decode('utf-8')
        article.title = cgi.escape(request.POST['title'].decode('utf-8'))
        now_date = datetime.datetime.now()+timedelta(hours=+8)        
        s = now_date.ctime()
        article.date = str(now_date)[:-7] 
        article.gmtdate = "%s, %s %s %s %s GMT" % (s[:3] ,s[8:10], s[4:7] ,s[-4:] ,s[11:19])
        article.year = str(datetime.datetime.now()+timedelta(hours=+8))[:4]
        article.month = str(datetime.datetime.now()+timedelta(hours=+8))[5:7]
        if not article.title:
            if len(article.content) > 11:
                article.title = article.content[:12] + '...'
            else:
                article.title=article.content

        article.id=time.strftime('%Y%m%d%H%M%S',now)
        if article.content:
            article.put()
            for tag_name in filter(None,article.tags.split(' ')):
                tag = Tag()
                tag.tag = tag_name
                tag.article_id = article.id
                tag.put()
    return HttpResponseRedirect("/blog/")
예제 #4
0
 def setUp(self):
     self.app = create_app('test')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     self.client = self.app.test_client()
     tag = Tag()
     tag.name = 'tagx'
     db.session.add(tag)
     category = Category()
     category.name = 'categoryx'
     db.session.add(category)
     db.session.commit()
     article = Article()
     article.title = 'articlex'
     article.slug = 'slugx'
     article.category = category
     article.content = 'contentx'
     article.tags = [tag]
     db.session.add(category)
     db.session.commit()
     user = User()
     user.name = 'admin'
     user.password = '******'
     db.session.add(user)
     db.session.commit()
예제 #5
0
    def post(self, request, format=None):
        try:
            ser = SubmitAricleSerializer(data=request.data)
            if ser._valid():
                title = ser.data.get('title')
                cover = request.FILES['cover']
                content = ser.data.get('content')
                category_id = ser.data.get('category_id')
                author_id = ser.data.get('author_id')
                promote = ser.data.get('promote')
            else:
                return Response({'status':'Bad request ...', status=status.HTTP_200_OK})
        
            user = User.objects.get(id=author_id)
            author = UserProfile.objects.get(user=user)
            category = Category.objects.get(id=category_id)
            
            article = Article()
            article.title = title
            article.cover = cover
            article.content = content
            article.category = category 
            article.author = author
            article.promote = promote
            article.save()

            return Response('status':'OK', status = status.HTTP_200_OK)

        except:
            return Response({'status': 'server error .....'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 def handle(self, *args, **options):
     superuser_username = options["superuser_username"]
     try:
         superuser = User.objects.get(username=superuser_username)
     except ObjectDoesNotExist:
         raise (CommandError(
                "Can't found the superuser with username '{}'!"
                .format(superuser_username)))
     legacy_articles = LegacyArticle.objects.all()
     for legacy_article in legacy_articles:
         article = Article()
         article.pk = legacy_article.pk
         article.author = superuser
         # MySQL returns `long` type for all `IntegerField`s.
         article.created = (datetime
                            .fromtimestamp(int(legacy_article.created)))
         # Field `last_updated` is not set always.
         if legacy_article.last_updated:
             article.modified = (datetime.fromtimestamp(
                                 int(legacy_article.last_updated)))
         article.title = legacy_article.title
         article.content = legacy_article.content
         article.slug = defaultfilters.slugify(legacy_article.title)
         if legacy_article.tweet_id:
             article.tweet_id = int(legacy_article.tweet_id)
         article.save()
     (self.stdout.write(
      "Import was successful! Total of {} articles were imported.\n"
      .format(legacy_articles.count())))
예제 #7
0
    def test_create_article(self):
        # Create the post
        post = Article()

        # Set the attributes
        post.name = 'My first post'
        post.slug = 'my-first-post'
        post.short_content = 'This is my first blog post'
        post.content = 'blablabla'
        post.published = True
        post.created_at = timezone.now()
        post.updated_at = timezone.now()

        # Save it
        post.save()

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

        # Check attributes
        self.assertEquals(only_post.name, 'My first post')
        self.assertEquals(only_post.slug, 'my-first-post')
        self.assertEquals(only_post.short_content,
                          'This is my first blog post')
        self.assertEquals(only_post.content, markdown('blablabla'))
        self.assertEquals(only_post.created_at, post.created_at)
        self.assertEquals(only_post.updated_at, post.updated_at)
예제 #8
0
    def test_delete_post(self):
        # Create the post
        post = Article()
        post.name = 'My first post'
        post.slug = 'my-first-post'
        post.short_content = 'This is my first blog post'
        post.content = 'This is my first blog post'
        post.published = True
        post.save()

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

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

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

        # Check deleted successfully
        self.assertTrue(b'Select article to change' in response.content)

        # Check post amended
        all_posts = Article.objects.all()
        self.assertEquals(len(all_posts), 0)
예제 #9
0
    def test_edit_post(self):
        # Create the post
        post = Article()
        post.name = 'My first post'
        post.slug = 'my-first-post'
        post.short_content = 'This is my first blog post'
        post.content = 'This is my first blog post'
        post.published = True
        post.save()

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

        # Edit the post
        response = self.client.post('/admin/blog/article/3/', {
            'name': 'My second post',
            'slug': 'my-second-post',
            'short_content': 'This is my second blog post',
            'content': 'This is my second blog post',
        },
                                    follow=True)
        self.assertEquals(response.status_code, 200)

        # Check changed successfully
        self.assertTrue(b'Select article to change' in response.content)

        # Check post amended
        all_posts = Article.objects.all()
        self.assertEquals(len(all_posts), 1)
        only_post = all_posts[0]
        self.assertEquals(only_post.name, 'My second post')
        self.assertEquals(only_post.content,
                          markdown('This is my second blog post'))
예제 #10
0
파일: views.py 프로젝트: PamlJam/hzone_test
def write(request):
    user = request.user
    context = {}

    if not user.is_authenticated:
        raise Http404('None')

    if request.method == 'GET':
        context['types'] = ArticleType.objects.all()
        response = render(request, 'write.html', context)
        return response

    if request.method == 'POST':
        title = request.POST.get('title', '')
        content = request.POST.get('content', '')
        type = request.POST.get('type', '')
        if not type:
            context = {'status': 'NONE'}
            return JsonResponse(context)
        if title and content:
            new_article = Article()
            new_article.type = get_object_or_404(ArticleType, title=type)
            new_article.author = user
            new_article.title = title
            new_article.content = content
            new_article.save()
            context = {'status': 'SUCCESS'}
        else:
            context = {'status': 'NULL'}

        return JsonResponse(context)
예제 #11
0
 def test_articles(self):
     article = Article()
     article.title = 'a'
     article.slug = 'skg'
     article.content = 'content xxx'
     db.session.add(article)
     db.session.commit()
     r = self.client.get(self.url + '/articles?page=1', )
     self.assertEqual(r.status_code, 200)
     r = self.client.get(self.url + '/articles?page=-1', )
     self.assertEqual(r.status_code, 404)
예제 #12
0
def add(request):
    user = ''
    nt = time.asctime(time.localtime(time.time()))
    if request.POST:
        if request.POST.has_key('_save'):
            addblog = Article()
            addblog.category = request.POST['category']
            addblog.content = request.POST['content']

            p = r'<p>(<img src=.+\.jpg)'
            pp = re.compile(p)
            pic = pp.findall(addblog.content)
            if pic == []:
                addblog.picture = 0
            else:
                for j in pic:
                    addblog.picture = j + '/>'
                    break
            if (Article.objects.filter(
                    category=request.POST['category']).filter(
                        content=request.POST['content'])):
                addblog.update_time = nt
            else:
                addblog.pub_date = nt
            addblog.title = request.POST['title']
            addblog.save()
            return HttpResponseRedirect("/hello")
        if request.POST.has_key('_addanother'):
            addblog = Article()
            addblog.category = request.POST['category']
            addblog.content = request.POST['content']
            if (Article.objects.filter(
                    category=request.POST['category']).filter(
                        content=request.POST['content'])):
                addblog.update_time = nt
            else:
                addblog.pub_date = nt
            addblog.title = request.POST['title']
            addblog.save()
            return HttpResponseRedirect("/add")
    return render(request, "add.html")
예제 #13
0
def save(contents):
    for content in contents:
        b = Article()
        b.cateid = 1
        b.catename = '绘画'
        b.title = content['title']
        b.content = content['content']
        b.url = content['url']
        b.author = content['author']
        b.abstract = content['abstract']
        b.pubtime = datetime.utcnow()
        b.status = 0
        b.save()
예제 #14
0
파일: views.py 프로젝트: BUGLAN/rest-blog
 def post(self):
     post_parser = reqparse.RequestParser()
     post_parser.add_argument('slug',
                              type=str,
                              required=True,
                              help='the argument cannot be blank')
     post_parser.add_argument('title',
                              type=str,
                              required=True,
                              help='the argument cannot be blank')
     post_parser.add_argument('content',
                              type=str,
                              required=True,
                              help='the argument cannot be blank')
     post_parser.add_argument('category_id',
                              type=blank_and_int,
                              help='the argument cannot be blank')
     post_parser.add_argument('tag_ids',
                              type=int,
                              action='append',
                              help='the argument cannot be blank')
     args = post_parser.parse_args()
     try:
         article = Article()
         article.title = args['title']
         article.slug = args['slug']
         # raw_content -> html
         article.raw_content = args['content']
         article.content = markdown.markdown(
             article.raw_content,
             extensions=[
                 'markdown.extensions.extra',
                 'markdown.extensions.codehilite',
                 'markdown.extensions.toc',
             ])
         article.category = Category.query.get(args['category_id'])
         article.tags = [
             Tag.query.get_or_404(id) for id in args['tag_ids']
         ] if args['tag_ids'] else []
         db.session.add(article)
         db.session.commit()
     except sqlalchemy.exc.IntegrityError:
         db.session.rollback()
         return {'status': 400, 'msg': '字段冲突'}, 400
     except sqlalchemy.exc.InvalidRequestError:
         db.session.rollback()
         return {'status': 400, 'msg': '字段冲突'}, 400
     except LookupError:
         db.session.rollback()
         return {'status': 400, 'msg': '编码冲突'}, 400
     return {'status': 200, 'msg': '新建文章成功'}
예제 #15
0
 def get(self):
     from .models import Blog, Article, Tag, Category
     data = dict(
         date_added=request.args.get('date_added',None),
         date_end=request.args.get('date_end',None),
         name=request.args.get('name',None),
         description=request.args.get('description',None),
         slug=request.args.get('slug',None),
         short_url=request.args.get('short_url',None),
         title=request.args.get('title',None),
         add_to_nav=request.args.get('add_to_nav',None),
         add_sidebar=request.args.get('add_sidebar',None),
         visible=request.args.get('visible',None),
         meta_title=request.args.get('meta_title',None),
         content=request.args.get('content',None),
         template=request.args.get('template',None),
         category=request.args.get('category',None),
         tags=request.args.get('tags',None),
         use_base_template=request.args.get('use_base_template',None),
     )
     blog = Blog.get_current_blog()
     post = Article.query.filter(Article.name==data['name'])\
                         .filter(Article.blog==blog)\
                         .first()
     if post is not None:
         res = 0
     else:
         tags = [x.name for x in Tag.query.all()]
         new_tags = []
         for tag in data['tags']:
             if not tag in tags:
                 t = Tag()
                 t.name = tag
                 new_tags.append(t.save())
         new_tags = new_tags + tags
         post = Article()
         post.tags = new_tags
         post.name = data.get('name')
         post.date_added = data.get('date_added')            
         post.description = data.get('description',None)
         post.slug = data.get('slug',None)
         post.url = data.get('short_url',None)
         post.title = data.get('title',None)            
         post.visible = data.get('visible',None)
         post.meta_title = data.get('meta_title',None)
         post.content = data.get('content',None)
         post.category = data.get('category',None)
         post.save()
         res = 1
     return jsonify(result=res,content=data['content'])
예제 #16
0
def add(request):
    art = Article()
    if request.method == "POST":
        username = request.session.get('username')
        user_id = User.objects.get(user_name=username).id
        art.user_id = user_id
        art.page_view = randint(1, 20)
        art.category_id = randint(1, 5)
        art.title = request.POST.get('title')
        #print(art.title)
        art.content = request.POST.get('content')
        art.date_publish = datetime.today().strftime("%Y/%m/%d/%H/%M/%S")
        art.save()
    return render(request, 'blog/add.html')
예제 #17
0
 def get(self):
     from .models import Blog, Article, Tag, Category
     data = dict(
         date_added=request.args.get('date_added', None),
         date_end=request.args.get('date_end', None),
         name=request.args.get('name', None),
         description=request.args.get('description', None),
         slug=request.args.get('slug', None),
         short_url=request.args.get('short_url', None),
         title=request.args.get('title', None),
         add_to_nav=request.args.get('add_to_nav', None),
         add_sidebar=request.args.get('add_sidebar', None),
         visible=request.args.get('visible', None),
         meta_title=request.args.get('meta_title', None),
         content=request.args.get('content', None),
         template=request.args.get('template', None),
         category=request.args.get('category', None),
         tags=request.args.get('tags', None),
         use_base_template=request.args.get('use_base_template', None),
     )
     blog = Blog.get_current_blog()
     post = Article.query.filter(Article.name==data['name'])\
                         .filter(Article.blog==blog)\
                         .first()
     if post is not None:
         res = 0
     else:
         tags = [x.name for x in Tag.query.all()]
         new_tags = []
         for tag in data['tags']:
             if not tag in tags:
                 t = Tag()
                 t.name = tag
                 new_tags.append(t.save())
         new_tags = new_tags + tags
         post = Article()
         post.tags = new_tags
         post.name = data.get('name')
         post.date_added = data.get('date_added')
         post.description = data.get('description', None)
         post.slug = data.get('slug', None)
         post.url = data.get('short_url', None)
         post.title = data.get('title', None)
         post.visible = data.get('visible', None)
         post.meta_title = data.get('meta_title', None)
         post.content = data.get('content', None)
         post.category = data.get('category', None)
         post.save()
         res = 1
     return jsonify(result=res, content=data['content'])
예제 #18
0
    def test_article(self):
        # 这里就简单的测试创建5篇文章
        for i in range(1, 6):
            article = Article()
            article.category = self.category
            article.author = self.superuser
            article.title = 'title' + str(i)
            article.content = 'content' + str(i)
            article.save()

        self.assertEqual(len(Article.objects.all()), 5 + 1)
        article_detail_res = self.client.get(
            Article.objects.first().get_absolute_url())
        self.assertEqual(article_detail_res.status_code, 200)
예제 #19
0
def main():
    content_list = []
    files = os.listdir(data_path)
    for name in files:
        os.path.join(data_path, name)
        with open(f, 'r', encoding='utf-8') as f:
            content = f.read()
            item = (name[:-4], content[:100], content)
            content_list.append(item)
    for item in content_list:
        print('saving article: %s' % item[0])
        article = Article()
        article.title = item[0]
        article.brief_content = item[1]
        article.content = item[2]
        article.save()
예제 #20
0
def insert(request):
    if (request.method == 'POST'):
        print(1)
        title = request.POST.get('title')
        brief_content = request.POST.get('brief_content')
        content = request.POST.get('content')

        a = Article()
        a.title = title
        a.brief_content = brief_content
        a.content = content
        a.save()

        return render(request, 'insert.html')
    else:
        print(2)
        return render(request, 'insert.html')
예제 #21
0
def publish(request):
    login_value = get_login_value(request)
    if login_value['state'] == 2:
        return HttpResponseRedirect("../home")
    if request.method == 'POST':
        article = Article()
        article.title = request.POST['title']
        article.category = request.POST['category']
        article.introduction = request.POST['description']
        html = request.POST['markdown'].replace('&nbsp;', ' ').replace('\\n', '\n').replace('&lt;', '<').replace('&gt;',
                                                                                                                 '>')
        html = append_script(html)
        article.content = html
        article.save()
        return HttpResponseRedirect("../user")
    else:
        return HttpResponseRedirect("../home")
예제 #22
0
def main():
    content_list = []
    files = os.listdir(data_path)
    for name in files:
        f = os.path.join(data_path, name)
        with open(f, 'r', encoding='utf-8') as f:
            content = f.read()
            item = (name[:-4], content[:content[:200].rfind(' ')], content)
            content_list.append(item)
    random.shuffle(content_list)
    Article.objects.all().delete()
    for item in content_list:
        print('saving article: %s' % item[0])
        article = Article()
        article.title = item[0]
        article.brief_content = item[1]
        article.content = item[2]
        article.save()
예제 #23
0
def add_article(request):
    title = request.POST['title']
    describe = request.POST['describe']
    cover = request.POST['cover']
    content = request.POST['content']
    token = request.POST['token']
    user_token = Token.objects.filter(key=token)
    if len(user_token) == 0:
        return Response('nologin')
    if len(title) == 0:
        return Response('notitle')
    new_article = Article(title=title)
    new_article.save()
    soup = BeautifulSoup(content, 'html.parser')  # 解析富文本html文档
    imgList = soup.find_all('img')
    for img in range(0, len(imgList)):
        src = imgList[img]['src']
        if 'http://' in src or 'https://' in src:
            image = requests.get(src)
            image_data = Image.open(BytesIO(image.content))
            image_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '-' + str(new_article.id) + '-' + str(img)
            image_data.save('upload/' + image_name + '.png')
            new_src = hostUrl + 'upload/' + image_name + ".png"
            content = content.replace(src, new_src)
            if cover == src:
                cover = new_src
        else:
            image_data = base64.b64decode(src.split(',')[1])
            image_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '-' + str(new_article.id) + '-' \
                         + str(img) + '.' + src.split(',')[0].split('/')[1].split(';')[0]
            image_url = os.path.join('upload', image_name).replace('\\', '/')
            with open(image_url, 'wb') as f:
                f.write(image_data)
            new_src = hostUrl + image_url
            content = content.replace(src, new_src)
            if cover == src:
                cover = new_src
    new_article.content = content
    new_article.belong = user_token[0].user
    new_article.cover = cover
    new_article.describe = describe

    new_article.save()
    return Response("ok")
예제 #24
0
def publish(request):
    logging_status = get_logging_status(request)
    if logging_status['login_state'] == BLOGSETTING.UNLOGGED:
        return HttpResponseRedirect("../home")
    if request.method == 'POST':
        article = Article()
        article.title = request.POST['title']
        article.category = request.POST['category']
        article.introduction = request.POST['description']
        html = request.POST['html'].replace('&nbsp;', ' ').replace('\\n', '\n') \
            .replace('&lt;', '<').replace('&gt;', '>')
        html = append_script(html)

        markdown = request.POST['markdown'].replace('&nbsp;', ' ').replace('\\n', '\n') \
            .replace('&lt;', '<').replace('&gt;', '>')
        article.markdown = markdown
        article.content = html
        article.save()
        return HttpResponseRedirect("../user")
    else:
        return HttpResponseRedirect("../home")
예제 #25
0
def write(request):
    if request.method == 'GET':
        aform = ArticleForm()
        return render(request, 'write.html', context={'aform': aform})
    else:
        aform = ArticleForm(request.POST)
        print(aform)
        if aform.is_valid():
            data = aform.cleaned_data
            article = Article()
            article.title = data.get('title')
            article.desc = data.get('desc')
            article.content = data.get('content')
            article.image = data.get('image')
            article.user = data.get('user')  #1对多,可直接赋值
            article.save()
            article.tags.set(data.get('tags'))  #多对多,必须文章生成后有了文章id才能添加标签
            return redirect(reverse('blog:index'))
        else:
            print('校验失败')
        return HttpResponse('TEST')
예제 #26
0
파일: views.py 프로젝트: oencoding/mybgi
def createAritcle(request):
    if request.method == 'POST':
        username = request.session.get('name')
        user = User.objects.get(name=username)
        article = Article()
        title = request.POST.get('title')
        author = request.POST.get('author')
        content = request.POST.get('content')
        columnname = request.POST.get('column')
        column = Column.objects.get(name=columnname)
        article.author = author
        article.title = title
        article.content = content
        article.column = column
        article.user = user
        article.save()
        articles = mdToHtml([article])
        try:
            comments = Comment.objects.filter(article=article)
            # comments.objects.order_by('pubTime')
            i = 1
            for comment in comments:
                comment.floor = i
                i += 1
            comments = mdToHtml(comments)
        except:
            comments = None
        context = {'config': configList,
                   'articles': articles, 'comments': comments, 'user': user, 'message': '新增文章成功,你今天的每份努力,明天都会获得更多,加油!'}
        return render(request, 'blogs.html', context=context)
    else:
        username = request.session.get('name')
        try:
            user = User.objects.get(name=username)
        except:
            user = None
        columns = getAllColumn()
        context = {'config': configList, 'user': user, 'columns': columns, }
        return render(request, 'createArticle.html', context=context)
예제 #27
0
    def test_index(self):
        # Create the post
        post = Article()
        post.name = 'My first post'
        post.slug = 'my-first-post'
        post.short_content = 'This is my first blog post'
        post.content = 'This is my first blog post'
        post.published = True
        post.save()

        # Check new post saved
        all_posts = Article.objects.filter(published=True)
        self.assertEquals(len(all_posts), 1)

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

        # Check the post title is in the response
        self.assertTrue(b'My first post' in response.content)

        # Check the post text is in the response
        self.assertTrue(b'This is my first' in response.content)
예제 #28
0
def new_article():
    try:
        title = request.json.get('title')
        slug = request.json.get('slug')
        category_id = request.json.get('category')
        tag_ids = request.json.get('tags')
        content = request.json.get('content')
    except AttributeError:
        abort(400)
    if title and content:
        article = Article()
        article.title = title
        article.slug = slug
        try:
            article.category = Category.query.get(category_id)
        except Exception:
            pass
        article.tags = [Tag.query.get(int(id)) for id in tag_ids]
        article.content = content
        db.session.add(article)
        db.session.commit()
        return jsonify({'status': 200})
    return jsonify({'status': 404}), 404
예제 #29
0
파일: views.py 프로젝트: h1608531788/lianxi
    def post(self, request, *args, **kwargs):
        # 获取参数
        title = request.POST.get('title')
        content = request.POST.get('content')
        pic = request.FILES.get("pic")
        type_id = request.POST.getlist('type_id')
        # 当前时间
        pubtime = datetime.datetime.today()
        name = request.COOKIES.get('name')
        user = User.objects.filter(name=name).first()
        Type_id = Type.objects.filter(pk__in=type_id)

        article = Article()
        article.title = title
        article.content = content
        article.pic = pic
        article.pubtime = pubtime
        article.user = user
        article.save()
        for type in Type_id:
            article.type.add(type)
        article.save()
        return render(request, 'index.html', {'name': name})
예제 #30
0
3、删除django_migrations表的记录
4、删除数据表

pycharm配置sql连接
Comment: settings.py全路径
File: db.sqlite3全路径


进入django shell环境,小范围调试
python manage.py shell

from blog.models import Article
a.title = "title02"
a = Article()
a.brief_content = "brief02"
a.content = 'content02'

a.save()

articles = Article.objects.all()
article = articles[0]
print(article.title)


django admin  后台管理模块
python manage.py createsuperuser
用户 admin
邮箱不填
密码 adminadmin

python manage.py runserver
예제 #31
0
def add(request,*arg,**kwarg):
	uid=int(-1)
	userInfos=common.Users(request,uid)
	currentUser=userInfos["currentuser"]

	categoryList=common.categoryList(currentUser.id)
	channelList=Channel.objects.all()

	if request.POST.has_key('ok'):
		channel1Id=int(utility.GetPostData(request,'channel1',0))
		channel2Id=int(utility.GetPostData(request,'channel1',0))
		cateId=int(utility.GetPostData(request,'category'))
		category=Category.objects.get(id=utility.GetPostData(request,'category'))
		
		title = utility.GetPostData(request,'title')
		pic = utility.GetPostData(request,'pic')
		tags=utility.GetPostData(request,'tags')
		summary=utility.GetPostData(request,'summary')
		content = utility.GetPostData(request,'content')
		status = utility.GetPostData(request,'status')
		
		ishome=utility.GetPostData(request,'ishome')
		isrecommend = utility.GetPostData(request,'isrecommend')
		istop = utility.GetPostData(request,'istop')
		isoriginal=utility.GetPostData(request,'isoriginal')
		cancomment = utility.GetPostData(request,'cancomment')
		password = utility.GetPostData(request,'password')

		if summary=="":
			tempContent=utility.RemoveTags(content)
			summary=tempContent[0:200] if len(tempContent)>200 else tempContent
		else:
			summary=utility.RemoveTags(summary)

		articleInfo=Article(category=category)

		articleInfo.channel1_id=channel1Id
		articleInfo.channel2_id=channel2Id
		articleInfo.category=category
		articleInfo.title = title
		articleInfo.pic=pic
		articleInfo.tags=tags
		articleInfo.summary=summary
		articleInfo.content = content
		articleInfo.createtime=datetime.datetime.now()
		articleInfo.views=0
		articleInfo.comments=0
		articleInfo.goods=0
		articleInfo.bads=0
		articleInfo.status=1 if status else 0
		articleInfo.user_id=currentUser.id
		articleInfo.username=currentUser.username

		articleInfo.ishome=1 if ishome else 0
		articleInfo.isrecommend=1 if isrecommend else 0
		articleInfo.istop=1 if istop else 0
		articleInfo.isoriginal=1 if isoriginal else 0
		articleInfo.cancomment=1 if cancomment else 0
		articleInfo.password=password

		articleInfo.save()

		#更新分类统计信息 不是默认分类并且是发布的文章
		if category.id !=1 and status:
			category.articles+=1
			category.save()

		#更新用户文章统计信息
		currentBlog=userInfos["currentblog"]
		currentBlog.articles+=1
		currentBlog.save()

		if channel1Id>0:
			channel1=Channel.objects.get(id=channel1Id)
			channel1.articles+=1
			channel1.save()
		if channel2Id>0:
			channel2=Channel.objects.get(id=channel2Id)
			channel2.articles+=1
			channel2.save()

		return HttpResponseRedirect('/%d/' %request.user.id)
	else:
		
		articleInfo=Article()

		return utility.my_render_to_response(request,"pub/articleedit.html",locals())
예제 #32
0
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
                      "mysite.settings")  # project_name 项目名称
django.setup()

from blog.models import Blog, Article

blog = Blog()
blog.title = '标题1'
blog.content = 'content1'
blog.save()

article = Article()
article.title = 'article-title-1'
article.content = 'article-content-1'
article.save()
#blog.save(using='db1')
예제 #33
0
def add_article(request):
    token = request.POST['token']
    if request.method == "PUT":
        permList = ['blog.change_article']
        checkUser = userLoginAndPerm(token, permList)
        print(checkUser)
        if checkUser != 'perm_pass':
            return Response(checkUser)

        lanmu_id = request.POST['lanmu_id']
        article_id = request.POST['article_id']

        lanmu = Lanmu.objects.get(id=lanmu_id)
        article = Article.objects.get(id=article_id)
        article.belong_lanmu = lanmu
        article.save()
        return Response('ok')

    title = request.POST['title']
    describe = request.POST['describe']
    cover = request.POST['cover']
    content = request.POST['content']

    user_token = Token.objects.filter(key=token)
    if len(user_token) == 0:
        return Response('nologin')
    if len(title) == 0:
        return Response('notitle')

    # 保存文章
    new_article = Article(title=title)
    new_article.save()
    # 解析富文本html文档
    soup = BeautifulSoup(content, 'html.parser')
    # 获取所有img标签 图片
    imgList = soup.find_all('img')
    # print(imgList)
    for img in range(0, len(imgList)):
        src = imgList[img]['src']
        # 判断图片 是远程 还是 本地
        if 'http://' in src or 'https://' in src:
            # print('远程图片')
            # 请求远程图片
            image = requests.get(src)
            # 转化二进制
            image_data = Image.open(BytesIO(image.content))
            print(image_data)
            # 设定文件名称
            image_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S')+'-' + \
                str(new_article.id)+'-'+str(img)
            image_data.save("upload/" + image_name + ".png")
            new_src = hostUrl + "upload/" + image_name + ".png"
            content = content.replace(src, new_src)
            # 封面设定
            if cover == src:
                cover = new_src
        else:
            # print('本地图片')
            image_data = base64.b64decode(src.split(',')[1])
            image_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S')+'-'+str(new_article.id) + \
                '-' + str(img)+'.' + \
                src.split(',')[0].split('/')[1].split(';')[0]
            # print(image_name)
            image_url = os.path.join('upload', image_name).replace('\\', '/')
            with open(image_url, 'wb') as f:
                f.write(image_data)
            # print(image_url)
            new_src = hostUrl + image_url
            content = content.replace(src, new_src)
            # 封面设定
            if cover == src:
                cover = new_src

    new_article.content = content
    new_article.describe = describe
    new_article.cover = cover
    new_article.belong = user_token[0].user
    new_article.save()
    return Response('ok')