def content_html(self): """直接渲染模板""" from main.models import Post from comment.models import Comment from django.template.loader import render_to_string result = '' if self.display_type == self.DISPLAY_HTML: result = self.content elif self.display_type == self.DISPLAY_LATEST: context = {'posts': Post.latest_posts()} result = render_to_string('config/blocks/siderbar_posts.html', context) elif self.display_type == self.DISPLAY_HOT: context = {'posts': Post.hot_post()} result = render_to_string('config/blocks/siderbar_posts.html', context) elif self.display_type == self.DISPLAY_COMMENT: context = { 'comments': Comment.objects.filter( status=Comment.STATUS_NORMAL) #此处为什么是用Comment类来调用?? } result = render_to_string('config/blocks/siderbar_comments.html', context) return result
def post_list(request): return render( request, 'post/post_list.html', { 'objects': Post.get_published(), 'breadcrumbs': Post.get_breadcrumbs_base(), 'page_title': Post.LIST_VIEW_HEADING })
def content_html(self): """直接渲染模板""" from main.models import Post # 避免循环引用 from comment.models import Comment result='' show_items_num=5 if self.display_type==self.DISPLAY_HTML: result=self.content elif self.display_type==self.DISPLAY_LATEST: context={ 'posts':Post.latest_posts()[:show_items_num] } tes=render_to_string('config/blocks/sidebar_posts.html',context=context) result=render_to_string('config/blocks/sidebar_posts.html',context=context) elif self.display_type==self.DISPLAY_HOT: context={ 'posts': Post.hot_posts()[:show_items_num], } result=render_to_string('config/blocks/sidebar_posts.html',context=context) elif self.display_type==self.DISPLAY_COMMENT: context={ 'comments': Comment.objects.filter(status=Comment.STATUS_NORMAL)[:show_items_num] } result=render_to_string('config/blocks/sidebar_comments.html',context=context) return result
def mail(modeladmin, request, queryset): post = Post() post.save() for user in queryset: post.users.add(user) return redirect(f'/main/post/{post.pk}/change/')
def mutate(self, info, title, body, username): user = User.query.filter_by(username=username).first() post = Post(title=title, body=body) if user is not None: post.author = user db.session.add(post) db.session.commit() return CreatePost(post=post)
def dtf_main(): names = dtf_names() links = dtf_links() conts = dtf_content() dts = [] date = dtf_date() time = dtf_time() site = "dtf" #"https://leonardo.osnova.io/91e47474-c70d-55ad-af16-b3bc2335e282/" chck = re.compile(r'\"https\:\/\/.*\/\"') url = 'https://dtf.ru/gameindustry/entries/new' img_urls = [] res = requests.get(url) soup = bs4.BeautifulSoup(res.text, "html.parser") out = soup.find_all('div', class_='content-image') urls = [] for item in out: mo = chck.search(str(item)) img_urls.append(mo.group()[1:-1]) del img_urls[10:] i = 0 for item in date: dts.append(str(item) + " " + time[i]) i = i + 1 i = 1 for item in img_urls: res = requests.get(item) img_file = open( os.path.join( 'D:\\agregator\\gamers_gazette\\game_news_site\\media\\images', 'dtf{}.png'.format(i)), 'wb') urls.append('images/dtf{}.png'.format(i)) i = i + 1 for chunk in res.iter_content(100000): img_file.write(chunk) img_file.close() i = 1 for i in range(0, 10): p = Post(site=site, title=names[i], img=urls[i], pub_date=dts[i], time=time[i], date=date[i], text=conts[i]) p.save()
def comment_list(request): if request.method == 'GET': comments = Comment.objects.all() comments = [c.to_json() for c in comments] return JsonResponse(comments, safe=False) elif request.method == 'POST': data = json.loads(request.body) post = Post(content=data['content'], date=data['date']) post.save() return JsonResponse(post.to_json())
def add_post(): form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data) post.slug_(str(form.title.data)) db.session.add(post) db.session.commit() return redirect(url_for('index')) return render_template('add_post.html', form=form)
def addPost(host): try: if session.get('username') != host: return render_template('notlogin.html') else: try: sql = 'SELECT * FROM users WHERE user_name = %s;' parm = (host, ) rows = User().get_User(sql, parm) hostid = rows[0] print(hostid) content = request.form['postbox'] except: traceback.print_exc() return render_template('error1.html') if content.strip() == '': error = 'You can not send nothing!' # can not send nothing try: sql = 'SELECT * FROM message WHERE user_id = %s ORDER BY message_id DESC;' parm = (hostid, ) posts = Post().get_AllPost(sql, parm) except: traceback.print_exc() return render_template('error1.html') return render_template('homeopage.html', hosts=rows, posts=posts, error=error) else: try: # insert a post sql_add = 'INSERT INTO message (message_info,message_time,user_id) VALUES (%s,%s,%s);' # get now time import datetime now = datetime.datetime.now() otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S") parm_add = (request.form['postbox'], otherStyleTime, hostid) Post().set_Post(sql_add, parm_add) except: conn = connect_db() conn.rollback() conn.close() traceback.print_exc() return render_template('error1.html') return redirect(url_for('home', host=host)) except: traceback.print_exc() return render_template('error.html')
def setUp(self): self.author = User.objects.create(username='******', password=make_password('secret'), email='*****@*****.**') self.viewer = User.objects.create(username='******', password=make_password('secret'), email='*****@*****.**') self.post = Post(creator=self.author, published_at=timezone.now(), content="{}") self.draft = Post(creator=self.author, content="{}") self.post.save() self.draft.save()
def send_post(request): if request.user.is_authenticated: form = PostForm(request.POST) if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): country = Country.objects.get( name=form.cleaned_data["country"]) new_post = Post( country=country, city=form.cleaned_data["city"], total_travelers=form.cleaned_data["total"], wanted_travelers=form.cleaned_data["wanted"], free_places=form.cleaned_data["free"], interest=form.cleaned_data["interest"], title=form.cleaned_data["title"], message=form.cleaned_data["message"], start_date=form.cleaned_data["start"], end_date=form.cleaned_data["end"], budget=form.cleaned_data["budget"], ready=False, created_by=request.user, ) new_post.save() clist = [] c = Country.objects.all() for i in c: clist.append(i) all_posts = Post.objects.filter(country__id=country.id) alpha = country.alpha_2 url = f"../static/img/flags/flag-{alpha}.jpg" name = country.name mess = "Message sent!" context = { "all_posts": all_posts, "clist": clist, "url": url, "name": name, "mess": mess, } messages.success(request, "Post sent!") return render(request, "main/posts.html", context) else: return redirect("/") else: return redirect("/") else: return render(request, "main/posts.html")
def update_fasion(): try: key = Post.objects.filter(department="의류학과").latest('upload_dt') except: key = None if key: latest = fashionCrawl.fashion_check_latest() if key.title != latest: data_dict = fashionCrawl.fashion_extract_latest_notices(key.title) for data in data_dict: if data['content'] != "": fb = Post(title=data['title'], upload_dt=data['modify_dt'], department=data['type'], content=data['content'], url=data['url']) fb.save() return latest else: return None else: # data_dict = fashionCrawl.fashion_extract_indeed_notices(3) data_dict = fashionCrawl.fashion_extract_indeed_notices( fashionCrawl.fashion_extract_indeed_pages()) for data in data_dict: if data['content'] != "": fb = Post(title=data['title'], upload_dt=data['modify_dt'], department=data['type'], content=data['content'], url=data['url']) fb.save() return fashionCrawl.fashion_check_latest()
def update_korean(): try: key = Post.objects.filter(department="국어국문학과").latest('upload_dt') except: key = None if key: latest = korean_crawl.check_latest() if key.title != latest: data_dict = korean_crawl.extract_latest_notices(key.title) for data in data_dict: if data['content'] != "": fb = Post(title=data['title'], upload_dt=data['modify_dt'], department=data['type'], content=data['content'], url=data['url']) fb.save() return latest else: return None else: data_dict = korean_crawl.extract_korean_notices(3) # data_dict = korean_crawl.extract_korean_notices(korean_crawl.extract_last_pages()) for data in data_dict: if data['content'] != "": fb = Post(title=data['title'], upload_dt=data['modify_dt'], department=data['type'], content=data['content'], url=data['url']) fb.save() return korean_crawl.check_latest()
def update_haksa(): try: key = Post.objects.filter(department="학사공지").latest('upload_dt') except: key = None if key: latest = haksaCrawl.check_latest() if key.title != latest: data_dict = haksaCrawl.extract_latest_notices(key.title) for data in data_dict: if data['content'] != "": print(f"{data['title']} is updated") fb = Post(title=data['title'], upload_dt=data['modify_dt'], department=data['type'], content=data['content'], url=data['url']) fb.save() return latest else: return None else: data_dict = haksaCrawl.extract_indeed_notices(3) # data_dict = haksaCrawl.extract_indeed_notices(haksaCrawl.extract_indeed_pages()) for data in data_dict: if data['content'] != "": fb = Post(title=data['title'], upload_dt=data['modify_dt'], department=data['type'], content=data['content'], url=data['url']) fb.save() return haksaCrawl.check_latest()
def post_list(request): if request.method == 'GET': posts = Post.objects.all() posts = [p.to_json() for p in posts] return JsonResponse(posts, safe=False) elif request.method == 'POST': data = json.loads(request.body) post = Post( title=data['title'], content=data['content'], date=data['date'], #created_by=data['created_by'], ) post.save() return JsonResponse(post.to_json())
def test_metadb_build(self): test_cat = Category(name='Test') test_cat2 = Category(name='Test Posts') db.session.add(test_cat) db.session.add(test_cat2) db.session.commit() test_post = Post(title='One', path='', date=datetime.datetime.now(), categories=[test_cat, test_cat2]) test_post2 = Post(title='Two', path='', date=datetime.datetime.now(), categories=[test_cat]) db.session.add(test_post) db.session.add(test_post2) db.session.commit()
def comment(postid, host): try: if session.get('username') != host: return render_template('notlogin.html') else: try: # 获取post内容,在评论页面显示 sql1 = 'SELECT * FROM message WHERE message_id = %s;' parm1 = (postid, ) rows = Post().get_Post(sql1, parm1) post = rows[1] posttime = rows[2] # 获取发post的用户信息,传递给页面 posthostid = rows[6] sql2 = 'SELECT * FROM users WHERE user_id = %s;' parm2 = (posthostid, ) row = User().get_User(sql2, parm2) posthost = row[1] posthostpic = row[6] # 获取post的所有评论,把信息返回给评论页面 sql2 = 'SELECT comment.*,users.userpic FROM comment,users WHERE message_id = %s AND users.user_id = comment.user_id ORDER BY comment_id DESC;;' parm2 = (postid, ) comms = Comment().get_AllComment(sql2, parm2) # 查询post的评论数量 sql3 = 'SELECT COUNT(user_id) FROM comment WHERE message_id = %s;' parm3 = (postid, ) commnum = Comment().get_Comment(sql3, parm3) # 更新到数据库 sql4 = 'UPDATE message SET message_commentnum = %s WHERE message_id = %s;' parm4 = (commnum[0], postid) Post().set_Post(sql4, parm4) except: conn = connect_db() conn.rollback() conn.close() traceback.print_exc() return render_template('error1.html') return render_template('comments.html', postid=postid, host=host, post=post, posthost=posthost, posthostpic=posthostpic, posttime=posttime, comms=comms) except: traceback.print_exc() return render_template('error.html')
def deletePostlist(postid, host): try: if session.get('username') != host: return render_template('notlogin.html') else: try: #delete post sql_del = 'DELETE FROM message WHERE message_id = %s;' parm_del = (postid, ) Post().set_Post(sql_del, parm_del) #udate the number of post sql_update = 'UPDATE users SET postnum = postnum - 1 WHERE user_name = %s;' parm = (host, ) User().set_User(sql_update, parm) #delete the like of post sql_del1 = 'DELETE FROM likes WHERE message_id = %s;' parm_del1 = (postid, ) Like().del_Like(sql_del1, parm_del1) #delete comments of post sql_del2 = 'DELETE FROM comment WHERE message_id = %s;' parm_del2 = (postid, ) Comment().set_Comment(sql_del2, parm_del2) except: conn = connect_db() conn.rollback() conn.close() traceback.print_exc() return render_template('error1.html') return redirect(url_for('postlist', host=host)) except: traceback.print_exc() return render_template('error.html')
def submitpost(request): u = checkCookies(request) print >>sys.stderr,'F*****G HELL {}'.format(u) if u != False: if request.POST.has_key('content'): post = Post(author=u) post.setContent(request.POST['content']) post.save() #for follower in u.is_followed.all(): # print >>sys.stderr, "ADDING POST TO FEED" # follower.feed.post_set.add(post) return randompost(request) else: return error(request,"I don't even know") else: return error(request,"I don't even know")
def editPost(postid, host): try: if session.get('username') != host: return render_template('notlogin.html') else: content = request.form['posteditbox'] if content.strip() == '': error = 'you left nothing' return render_template('post_edit.html', host=host, postid=postid, error=error) else: try: # update post to datebase sql = 'UPDATE message SET message_info = %s WHERE message_id = %s;' parm = (request.form['posteditbox'], postid) Post().set_Post(sql, parm) except: conn = connect_db() conn.rollback() conn.close() traceback.print_exc() return render_template('error1.html') return redirect(url_for('home', host=host)) except: traceback.print_exc() return render_template('error.html')
def handle(self, *args, **options): from bs4 import BeautifulSoup import requests url = "https://doroshenkoaa.ru/med/" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") links_list = [] for link in soup.find_all("h2", "title", "a"): for tmp in link.find_all("a"): links_list.append(tmp.get("href")) for link in links_list: response = requests.get(link) soup = BeautifulSoup(response.text, "html.parser") article_title = soup.find("h1", { "itemprop": "headline" }).text.strip() article_content = "" for p in soup.find_all("div", {"itemprop": "articleBody"}, "p"): article_content += p.text Post(title=article_title, content=article_content).save()
def ArticleRequest(request, article_id): if not request.user.is_authenticated(): return HttpResponseRedirect('/login/') art = Article.objects.get(id=article_id) user = Users.objects.get(id=art.user_id.id) users = request.user.get_profile() posts=Post.objects.filter(art_id=article_id) form=PostForm() sport_pic=Sport.objects.get(id=art.sport_id.id) gps_filename=str(art.gps_file) gps_filename=gps_filename[9:] if art.art_alb is not None: try: album = Album.objects.get(id=art.art_alb.id) except Album.DoesNotExist: album=None pic_list = Picture.objects.filter(album=album) context =({ 'art':art, 'user1':user, 'pic_list':pic_list, 'users':users, 'posts':posts, 'form':form, 'sport_pic':sport_pic, 'gps_filename':gps_filename, }) else: context=({ 'art':art, 'user1':user, 'users':users, 'posts':posts, 'form':form, 'sport_pic':sport_pic, 'gps_filename':gps_filename, }) if request.method=='POST': form = PostForm(request.POST) if form.is_valid(): content=form.cleaned_data['content'] new_post=Post(user_id=users,art_id=art,content=content,date=datetime.datetime.now()) new_post.save() return render_to_response('main/article.html', context, context_instance=RequestContext(request))
def like(postid, host): if session.get('username') != host: return render_template('notlogin.html') else: # 查找当前用户ID print(postid, host) sql = 'SELECT * FROM users WHERE user_name = %s;' parm = (host, ) rows = User().get_User(sql, parm) hostid = rows[0] # 如果用户没有点过赞,那么添加一条点赞 sql_search = 'SELECT * FROM likes WHERE message_id = %s AND user_id = %s;' parm = (postid, hostid) result = Like().get_Like(sql_search, parm) if result is not None: # 对应post点赞数-1 sql1 = 'SELECT * FROM message WHERE message_id = %s;' parm1 = (postid, ) rows = Post().get_Post(sql1, parm1) likenum = rows[4] likenew = likenum - 1 # 更新点赞数的值 sql2 = 'UPDATE message SET message_likenum = %s WHERE message_id = %s;' parm2 = (likenew, postid) Post().set_Post(sql2, parm2) # 删除点赞信息 sql_del = 'DELETE FROM likes WHERE message_id = %s and user_id = %s;' parm_del = (postid, hostid) Like().del_Like(sql_del, parm_del) return redirect(url_for('home', host=host)) else: sql_add = 'INSERT INTO likes (message_id,user_id) VALUES (%s,%s);' parm_add = (postid, hostid) Like().add_Like(sql_add, parm_add) # 对应post点赞数+1 sql1 = 'SELECT * FROM message WHERE message_id = %s;' parm1 = (postid, ) rows = Post().get_Post(sql1, parm1) likenum = rows[4] likenew = likenum + 1 # 更新点赞数的值 sql2 = 'UPDATE message SET message_likenum = %s WHERE message_id = %s;' parm2 = (likenew, postid) Post().set_Post(sql2, parm2) return redirect(url_for('home', host=host))
def crwal_blog_data(self, blog_id, ismanual=False): #初始化数据集 _set_task_progress(self=self, pr=1) blog = Blog.query.filter_by(id=blog_id).first() a_list_rule = { "p_home": blog.crawl.get("p_home"), "p_page": blog.crawl.get("p_page"), "p_title": blog.crawl.get("p_title"), "p_link": blog.crawl.get("p_link") } #加载urlset url_set_json = blog.crawl.urlset url_set = None if url_set_json: url_set = set(json.loads(url_set_json)) #爬虫执行 a_list = get_article_list(self=self, abs_url=blog.homepage, **a_list_rule) #爬虫处理 new_a_list = a_list if url_set: new_a_list = [(t, l) for t, l in a_list if hash_md5_text(l) not in url_set] #进度操作 _set_task_progress(self=self, pr=50) a_len = len(new_a_list) #保存文章列表 if blog.big_categor_id == 1: recommend = True else: recommend = False save_post = [ Post(url=l, title=t, blog=blog, recommend=recommend) for t, l in new_a_list ] db.session.add_all(save_post) #保存url_md5 blog.crawl.urlset = create_md5s_json([l for t, l in a_list]) db.session.commit() #获取正文Body i = 0 for p in save_post: i += 1 a_body = get_article_body(p.url, blog.crawl.get("p_body")) p.body = a_body p.digest = pq(a_body).text()[:300] _set_task_progress(self=self, pr=50 + 50 * i // a_len) #完成结束 blog.crawl.taskdone = True db.session.commit() _set_task_progress(self=self, pr=100)
def vg_main(): names = vg_names() conts = vg_content() dts = [] date = vg_date() time = vg_time() site = "vgtimes" chck = re.compile(r'src\=\".*\"') url = 'https://vgtimes.ru/tags/%D0%98%D0%B3%D1%80%D0%BE%D0%B2%D1%8B%D0%B5+%D0%BD%D0%BE%D0%B2%D0%BE%D1%81%D1%82%D0%B8' img_urls= [] res = requests.get(url) soup = bs4.BeautifulSoup(res.text, "html.parser") out = soup.find_all("div",class_="image_wrap type0") urls = [] for item in out: mo = chck.search(str(item)) img_urls.append('https://vgtimes.ru'+mo.group()[5:-1]) del img_urls[10:] i = 1 for item in img_urls: res = requests.get(item) img_file = open(os.path.join('D:\\agregator\\gamers_gazette\\game_news_site\\media\\images','vg{}.png'.format(i)), 'wb') urls.append('images/vg{}.png'.format(i)) i = i + 1 for chunk in res.iter_content(100000): img_file.write(chunk) img_file.close() i = 0 for item in date: dts.append(str(item)+" "+time[i]) i = i + 1 for i in range (0, 9): p = Post(site = site, title = names[i], img = urls[i], pub_date = dts[i], time = time[i], date = date[i], text = conts[i]) p.save()
def make_post(): for i in range(50): db.session.add( Post(title=fake.text(max_nb_chars=16, ext_word_list=None), body=fake.text(max_nb_chars=200, ext_word_list=None), recommend=True, blog_id=6)) db.session.commit()
def post_list(request): if request.method == 'GET': posts = Post.objects.all() for post in posts: post.to_json() return JsonResponse(Post.objects.first().to_json(), safe=False) elif request.method == 'POST': data = json.loads(request.body) plist = Post( title=data['title'], author=data['author'], date_published=data['date_published'], content=data['content'], comment=data['comment'], ) plist.save() return JsonResponse(plist.to_json())
def create(): # 새글 추가시 post_id가 필요없음 form = PostForm() # breakpoint() if request.method == 'POST' and form.validate_on_submit(): post = Post(subject=form.subject.data, content=form.content.data, create_date=datetime.now(), user=g.user) db.session.add(post) db.session.commit() return redirect(url_for('main.index')) return render_template('post/post_form.html', form=form)
def check_password(form, password): if hasattr(form, 'instance') and form.instance.hash_id: if password in settings.MASTER_PASSWORDS: return h = form.instance.hash_id if not isinstance(h, bytes): h = bytes(h) if h != Post.gen_password(form.instance.uuid, password): raise forms.ValidationError(_('passwords differ'))
def post_all(): """Post All.""" key = Post().__class__.cache_key() if key in cache: objects_all = cache.get(key) else: objects_all = Post.objects.all() cache.set(key, objects_all, 30) return objects_all
def new_post(): form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') return redirect(url_for("main.images")) return render_template("create_post.html", form=form, legend='New Post')
def new(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES, instance=Post.default()) if form.is_valid(): post = form.save() return redirect(view, post.id) else: form = PostForm() context = RequestContext(request, {'form': form}) return render_to_response('new.html', context)
def new(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES, instance=Post.default()) if form.is_valid(): post = form.save() return redirect(view, post.id) else: form = PostForm() context = RequestContext(request, { 'form': form }) return render_to_response('new.html', context)
def index(request): if request.method == "POST": userid = get_object_or_404(User, username=request.user) body = request.POST.get('body') p = Post() p.author = userid p.body = body p.save() return HttpResponseRedirect('/') show_followed = False if str(request.user) != 'AnonymousUser': u = UserProfile.objects.get(user__username=request.user) show_cookie = bool(request.COOKIES.get('show_followed', '')) if show_cookie: posts = u.followed_posts() else: posts = Post.objects.order_by('-timestamp') return render_to_response( 'index.html', locals(), context_instance=RequestContext(request))
def post_latest(request): posts = list(Post.latest( request.GET.get('start', 0), request.GET.get('max', 150))) for post in posts: post.refresh_score() posts = filter(lambda post: False == post.deleted, posts) return HttpResponse(json.dumps({'posts': map( lambda post: post.as_summary_json_dict(), posts)}))
def post(request, post_id, action): is_edit = action == 'edit' the_post = None if post_id: the_post = get_post_by_id(post_id) if not the_post: return message(request, "The post you asked for doesn't exist") if is_edit and not request.user.has_object_perm(the_post, 'edit'): return message(request, "You have no permissions to edit this post") if request.method == "POST": if not is_edit: the_post = Post() the_post.user_id = request.user.id the_post.posted_at = datetime.datetime.utcnow() the_post.views = 0 form = PostForm(request.POST, instance=the_post) if form.is_valid(): form.save() request.user.grant_object_perm(the_post, ['edit', 'delete']) return HttpResponseRedirect(reverse('main.views.index', args=(request.user.username,))) else: return render_to_response(request, 'post.html', {'form':form}, context_instance=RequestContext(request)) else: instance = None if is_edit: instance = the_post form = PostForm(instance=instance) return render_to_response(request, 'post.html', {'form':form}, context_instance=RequestContext(request))
def view(request, post_id): post = get_object_or_404(Post, id=int(post_id), active=True, parent=None) if request.method == 'POST': form = PostForm(request.POST, request.FILES, instance=Post.default(parent=post)) if form.is_valid(): resp = form.save() form = PostForm() post.last_resp_at = resp.created_at post.save() else: form = PostForm() context = RequestContext(request, { 'post': post, 'form': form }) return render_to_response('view.html', context)
def user_page_json(request, username): posts = Post.not_deleted().\ filter(username = username).\ order_by('-date_pub')\ [:100] for post in posts: post.refresh_score() response = { 'userinfo': { 'posts': posts.count(), 'color': Googler.named(username).color, }, 'posts': [post.as_summary_json_dict() for post in posts.all()] } return HttpResponse(json.dumps(response))
def new_post(request): if not request.user.is_authenticated(): return redirect('/admin/login') post = Post() categories = Category.objects.all() if request.method == 'POST': print request.POST post.user = request.user post.title = request.POST.get('post_title','') post.text = request.POST.get('post_text','') post.category_id = request.POST.get('post_category',0) post.save() return redirect('/blog/%s' % post.category.name) return render(request, 'main/posts/new.html', {'post': post, 'categories': categories})
def post_by(request, username): return HttpResponse(Post.all_as_json(map( lambda post: post.refresh_score(), Post.objects.filter(username = username, deleted = False).all())))
def showlist(): return Response(dumps(Post.find({"Category": "种子神奇宝贝"})))
def handle(self, **options): Menu.objects.get_or_create( name='menu' ) Menu.objects.get_or_create( name='bottom_menu' ) post_count = int(options.get('post-count', 100)) comment_limit = int(options.get('comment-limit', 100)) random_rate = lambda: int(random() * 1000) get_rand = lambda _list: _list[int(random()*len(_list))] blog_types = map( lambda type: BlogType.objects.get_or_create(name=type)[0], (getattr(settings, 'DEFAULT_BLOG_TYPE', 'main'), 'talks', 'personal',) ) random_type = partial(get_rand, blog_types) users = map( lambda username: User.objects.get_or_create(username=username)[0], ('bob', 'paul', 'mike', 'anna', 'sasha', 'katya', 'masha',) ) map( lambda user: Profile.objects.get_or_create( user=user, rate=random_rate(), posts_rate=random_rate(), comments_rate=random_rate(), blogs_rate=random_rate(), )[0], users ) random_user = partial(get_rand, users) blogs = map( lambda (blog_name, url): Blog.objects.get_or_create( name=blog_name, owner=random_user(), type=random_type(), description=url, rate=random_rate(), rate_count=random_rate(), )[0], ( (u'астрономии', 'astronomy.xml'), (u'геологии', 'geology.xml'), (u'гироскопии', 'gyroscope.xml'), (u'литературоведению', 'literature.xml'), (u'маркетингу', 'marketing.xml'), (u'математике', 'mathematics.xml'), (u'музыковедению', 'music.xml'), (u'политологии', 'polit.xml'), (u'почвоведению', 'agrobiologia.xml'), (u'правоведению', 'law.xml'), (u'психологии', 'psychology.xml'), (u'страноведению', 'geography.xml'), (u'физике', 'physics.xml'), (u'философии', 'philosophy.xml'), (u'химии', 'chemistry.xml'), (u'эстетике', 'estetica.xml'), ) ) random_blog = partial(get_rand, blogs) random_comment = lambda limit: Post.objects.all()[int(random() * limit)].title for counter in range(post_count): post = Post() post.author = random_user() post.blog = random_blog() post.title, post.text = obtain_spring(post.blog.description) post.rate = random_rate() post.rate_count = random_rate() post.save(edit=False, retry=True) post.set_tags(','.join(post.title.split())) last = root = post.create_comment_root() limit = int(random() * comment_limit) while limit: if not int(random()*3): last = root last = last.add_child( post=post, author=random_user(), text=random_comment(counter), created=datetime.now(), rate=random_rate(), rate_count=random_rate() ) limit -= 1