def test_unpublished_articles_does_appears_if_the_author_is_logged(self): login_user(self) Article(title='Article that must appear', content='<p>content</p>', author=self.user).save() result = self.client.get('/@emailtest/') self.assertIn(b'Article That Must Appear', result.data) self.assertEqual(result.status_code, 200)
def deal(request): if request.method == "POST": title = request.POST.get('title') content = request.POST.get('content') article = Article(title=title, content=content) article.save() ret = {"ret": 0, 'title': title, 'content': content} return HttpResponse(json.dumps(ret))
def article_new(request): article = Article() form = ArticleForm(request.POST, instance=article) if form.is_valid(): form.save() # Quoiqu'il arrive, on affiche la page du formulaire. return render(request, 'blog/article.html', locals())
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 = "nice" rsp = search(s, None) 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()
def save(self, username, article=None): cd = self.cleaned_data title = cd['title'] title_zh = title now = datetime.datetime.now() content_md = cd['content'] content_html = markdown.markdown(cd['content']) re_title = '<h\d>(.+)</h\d>' data = content_html.split('\n') for line in data: title_info = re.findall(re_title, line) if title_info: title_zh = title_info[0] break url = '/article/%s' % (title) tags = cd['tags'] if article: id_before = article.id created_before = article.created article.delete() article = Article( id = id_before, url = url, title = title, title_zh = title_zh, author = username, content_md = content_md, content_html = content_html, tags = tags, created = created_before, updated = now ) else: article = Article( url=url, title=title, title_zh=title_zh, author=username, content_md=content_md, content_html=content_html, tags=tags, views=0, created=now, updated=now) article.save()
def setUpTestData(cls): tag = Tag.objects.create(name=set('Fruit',)) tag.save() user = User() user.save() article = Article( title='New article') article.(tag, user,) article.save() Comment.objects.create(user=User, email='*****@*****.**', name='Nik', text='Some text', article='New article')
def test_unpublished_articles_does_not_appears_if_the_author_not_logged( self): Article(title='Article that must not appear', content='<p>content</p>', author=self.user, publication_date=None).save() result = self.client.get('/@emailtest/') self.assertNotIn(b'Article That Must Not Appear', result.data) self.assertEqual(result.status_code, 200)
def test_date_is_current_datetime(self): """ Test that an article must have a datetime associated with it that is by default the current UTC time. """ current_datetime = utc.localize(datetime.utcnow()) article = Article() time_difference = article.date - current_datetime self.assertAlmostEqual(time_difference.total_seconds(), 0, places=2)
def create_article(article_details): new_article = Article(title=article_details["title"], slug=article_details["url"], content=article_details["content"]) new_article.save() for tag in article_details["tags"]: new_article.tags.add(tag)
def AddArticle(request): """ Add a new blog. """ if not request.user.is_authenticated(): return render_to_response("user/login.html", RequestContext(request)) if request.method == 'POST': title = request.POST.get('title', '') body = request.POST.get('body', '') status = request.POST.get('status', '') abstract = request.POST.get('abstract', '') keywords = request.POST.get('keywords', '') en_keywords = request.POST.get('en_keywords', '') topped = request.POST.get('topped', '') price = request.POST.get('price', '') attachment = request.POST.get('attachment', '') category = request.POST.get('category', '') tag = request.POST.get('tag', '') myFile = request.FILES.get("attachment", None) if not myFile: return HttpResponse('Please upload file.') destination = open(os.path.join(settings.MEDIA_ROOT, myFile.name), 'wb+') for chunk in myFile.chunks(): destination.write(chunk) destination.close() attachedFile = Attachment() attachedFile.name = myFile.name attachedFile.attachment = myFile.name newFile = attachedFile.save() article = Article() article.title = title article.body = body article.status = status article.abstract = abstract article.keywords = keywords article.en_keywords = en_keywords article.topped = topped article.price = price article.attachment = Attachment.objects.filter(name=myFile.name)[0] article.category = Category.objects.filter(id=category)[0] article.tag = Tag.objects.filter(id=tag)[0] article.user = User.objects.filter(id=request.user.id)[0] article.save() article_id = Article.objects.filter(title=title, status=article.status, category=article.category, tag=article.tag)[0] url = "article/" + str(article_id.id) return HttpResponseRedirect(url)
def test_all_sections_must_be_filled(self): article = Article(author=None, title='', text='', description='', tags='', created_date='') with self.assertRaises(ValidationError): article.save() article.full_clean()
def submit(request): try: cont = request.POST['content'] except (KeyError): return render(request, 'blog/index.html', context={'all_articles': all_articles, 'message': 'Write something!'}) else: article = Article(content=cont, written_date=timezone.now()) article.save() return HttpResponseRedirect('/blog')
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])
def main(): user = User.objects.all()[0] categories = Category.objects.all() for i in range(1000): article = Article( slug=f'article_{i}', title=f'Article Title {i}', content=CONTENT_STRING, user=user, ) article.save()
def Article_Formu(request): article = Article() if request.method == 'POST': form = ArticleForm(request.POST, instance=article) if form.is_valid(): form.save() envoi = True else: form = ArticleForm(request.POST, instance=article) return render(request, 'blog/HTML/creation_article.html', locals())
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)
def test_create_article_aready_exists(): Article(author='*****@*****.**', title='New Article', content='Super extra awesome article').save() cmd = CreateArticleCommand(author='*****@*****.**', title='New Article', content='Super awesome article') with pytest.raises(AlreadyExists): cmd.execute()
def create_article(request): """ Upload images """ from PIL import Image form = ArticleForm(request.POST, request.FILES) if form.is_valid(): # insert the article into db article = Article(client=request.user, title=form.cleaned_data['title'], body=form.cleaned_data['body'], image=form.cleaned_data['image']) article.save() # getting article topics article_topics = request.POST.get('article-topics', '') article_topics = json.loads(article_topics) # add topics to article for key, value in article_topics.iteritems(): topic_id = key.split('_')[-1] if value: topic = Topic.objects.get(id=topic_id) article.topics.add(topic) article.save() # IMAGE tasks # get article after inserting it article = Article.objects.latest('pk') # image article, extension and path image = article.image ext = image.name.split('.')[-1].lower() path = image.path # resize image image = Image.open(image) image = image.resize((800, 500)) image.save('blog/static/blog/img/articles/{}.{}'.format( article.id, ext)) article.image = 'blog/img/articles/{}.{}'.format(article.id, ext) article.save() # delete old image if os.path.exists(path): os.remove(path) return HttpResponseRedirect(reverse('blog:index'))
def fake_articles(count = 100): for i in range(count): article = Article( title = fake.sentence(), body = fake.text(3000), category = Category.query.get(random.randint(1, Category.query.count())), timestamp = fake.date_time_this_year(), count_read = random.randint(1,10000) ) db.session.add(article) db.session.commit()
def post(self): from blog.forms import AddContentModalForm from auth.models import User self._form = AddContentModalForm(request.form) from blog.models import Article a = Article() self._form.populate_obj(a) a.author = User.query.filter( User.email == session.get('email', None)).first() a.save() return self.redirect('blog.index')
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")
def execute(self) -> Article: try: Article.get_by_title(self.title) raise AlreadyExists except NotFound: pass article = Article(author=self.author, title=self.title, content=self.title).save() return article
def testdb(request): # 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE test1 = Article(title='老王的博客', content='这是老王的第一个博客', author_id=1) test1.save() # 另外一种方式 #Test.objects.filter(id=1).update(name='Google') # 修改所有的列 # Test.objects.all().update(name='Google') return HttpResponse("<p>修改成功</p>")
def _import_article(self, article_data): author = Author.objects.get(username=article_data['author']) article = Article(title=article_data['title'], content=article_data['content'], created_at=article_data['created_at'], author=author) article.save() tags = [] for tag in article_data['tags']: tag_instance, _ = Tag.objects.get_or_create(name=tag) tags.append(tag_instance) article.tags.add(*tags)
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='*****@*****.**'))) self.client.login(username='******', password='******') user = BlogUser.objects.filter(email='*****@*****.**')[0] user.is_superuser = True user.is_staff = True user.save() delete_view_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])
def add_article(): form = AddArticle() #Add comment if form.validate_on_submit(): article = Article(title=form.article_title.data, content=form.article_content.data, category=form.article_category.data) db.session.add(article) db.session.commit() return redirect(url_for('home')) return render_template('add_article.html', form=form)
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()
def test_get_article_by_id(): """ GIVEN ID of article stored in the database WHEN the execute method is called on GetArticleByIDQuery with id set THEN it should return the article with the same id """ article = Article(author='*****@*****.**', title='New Article', content='Super extra awesome article').save() query = GetArticleByIDQuery(id=article.id) assert query.execute().id == article.id
def post_content(request): try: blog_post = Article() except: data = {} data["invalid"] = "response is invalid" return Response(data) serialized = BlogSerializer(blog_post, data=request.data) if serialized.is_valid(): serialized.save() return Response({"sucess": "data is posted"}) else: return Response(serialized.error)
def article_detail(request, article_id): article_info = get_object_or_404(Article, id=article_id) if request.method == 'GET': try: next_article = article_info.get_previous_by_create_time() except Article.DoesNotExist: next_article = Article(id=article_id, title="没有了") try: pre_article = article_info.get_next_by_create_time() except Article.DoesNotExist: pre_article = Article(id=article_id, title="没有了") serializer = ArticleDetailSerializer(article_info) data = { 'data': serializer.data, 'pre_id': pre_article.id, 'pre_title': pre_article.title, 'next_id': next_article.id, 'next_title': next_article.title, } return Response(data, status=status.HTTP_200_OK)