def user_edit(request, uid): "User's profile page" user = models.User.objects.select_related('profile').get(id=uid) if not user.profile.editable(request.user): messages.error(request, "unable to edit this user") return html.redirect("/user/show/%s/" % uid) if request.method == 'GET': initial = dict( display_name = user.profile.display_name, email = user.email or '', location = user.profile.location or '', website = user.profile.website or '', about_me = user.profile.about_me or '' ) form = UserForm(initial) return html.template(request, name='user.edit.html', user=user, form=form) elif request.method == 'POST': form = UserForm(request.POST) if not form.is_valid(): return html.template(request, name='user.edit.html', user=user, form=form) else: for field in "display_name about_me website location".split(): setattr(user.profile, field, form.cleaned_data[field]) user.email = form.cleaned_data['email'] user.profile.save() user.save() return html.redirect("/user/show/%s/" % user.id)
def new_post(request, pid=0, post_type=POST_QUESTION): "Handles the creation of a new post" user = request.user name = "post.edit.html" parent = models.Post.objects.get(pk=pid) if pid else None root = parent.root if parent else None toplevel = (pid == 0) factory = formdef.ChildContent if pid else formdef.TopLevelContent params = html.Params(tab='new', title="New post", toplevel=toplevel) if request.method == 'GET': # no incoming data, render form form = factory() return html.template(request, name=name, form=form, params=params) # process the incoming data assert request.method == 'POST', "Method=%s" % request.method form = factory(request.POST) if not form.is_valid(): # returns with an error message return html.template(request, name=name, form=form, params=params) # form is valid at this point, create the post params = dict(author=user, type=post_type, parent=parent, root=root) params.update(form.cleaned_data) with transaction.commit_on_success(): post = models.Post.objects.create(**params) post.set_tags() post.save() return redirect(post)
def new_post(request, pid=0, post_type=POST_QUESTION): "Handles the creation of a new post" user = request.user name = "post.edit.html" parent = models.Post.objects.get(pk=pid) if pid else None root = parent.root if parent else None toplevel = (pid == 0) factory = formdef.ChildContent if pid else formdef.TopLevelContent params = html.Params(tab='new', title="New post", toplevel=toplevel) if request.method == 'GET': # no incoming data, render form form = factory() return html.template(request, name=name, form=form, params=params) # process the incoming data assert request.method == 'POST', "Method=%s" % request.method form = factory(request.POST) # throttle new users to no more than 3 posts per 2 hours MIN_AGE, MIN_COUNT = 6, 2 brand_new = (datetime.now() - user.date_joined) < timedelta(hours=MIN_AGE) too_many = models.Post.objects.filter(author=user).count() >= MIN_COUNT if brand_new and too_many: messages.error(request, "Brand new users (accounts less than 6 hours old) may not create more than 2 posts. Apologies \ if that interferes with your usage, it is an anti-spam measure. Gives us a chance to ban the spamming bots") return html.template(request, name=name, form=form, params=params) if not form.is_valid(): # returns with an error message return html.template(request, name=name, form=form, params=params) # form is valid at this point, create the post params = dict(author=user, type=post_type, parent=parent, root=root) # form may contain a variable number of elements for attr in "title content tag_val type".split(): if attr in form.cleaned_data: params[attr] = form.cleaned_data[attr] with transaction.commit_on_success(): post = models.Post.objects.create(**params) post.set_tags() #post.save() return redirect(post)
def badge_show(request, bid): "Shows users that have earned a certain badge" page = None badge = models.Badge.objects.get(id=bid) awards = models.Award.objects.filter(badge=badge).select_related('user', 'user_profile').order_by("-date") page = get_page(request, awards, per_page=24) return html.template(request, name='badge.show.html', page=page, badge=badge)
def more(request, pid): counts = request.session.get(SESSION_POST_COUNT, {}) form = SearchForm() params = html.Params(tab='search', q="", sort='') res = more_like_this(request=request, pid=pid) page = get_page(request, res, per_page=10) return html.template(request, name='search.html', page=page, params=params, counts=counts, form=form)
def post_show(request, pid): "Returns a question with all answers" qs = models.Post.objects question = qs.select_related('children', 'votes').get(id=pid) #qs = models.Post.all_objects if 'view_deleted' in request.permissions else models.Post.objects answers = models.Post.objects.filter(parent=question, post_type=POST_ANSWER).select_related('author', 'author__profile') answers = answers.order_by('-answer_accepted','-score') if request.user.is_authenticated(): notes = models.Note.objects.filter(target=request.user, post=question).all().delete() votes = models.Vote.objects.filter(author=request.user, post__id__in=[ question.id ] + [a.id for a in answers] ) # updates the viewcounter once within a session, Alex says to move to IP based counting TODO viewed = request.session.get(VIEWED_KEY, set()) if question.id not in viewed: viewed.add(question.id) question.views += 1 question.save() request.session[VIEWED_KEY] = viewed else: notes, votes = [], [] up_votes = set(vote.post.id for vote in votes if vote.type == const.VOTE_UP) down_votes = set(vote.post.id for vote in votes if vote.type == const.VOTE_DOWN) return html.template( request, name='post.show.html', question=question, answers=answers, up_votes=up_votes, down_votes=down_votes )
def question_unanswered(request, uid=0, post_type=None): "Lists all the questions" params = html.Params() params.setr('Filter: unanswered') qs = get_posts(request).filter(answer_count=0) page = get_page(request, qs) return html.template(request, name='post.list.html', page=page, params=params)
def show_tag(request, tag_name=None): "Display posts by a certain tag" user = request.user # populate the session data sess = middleware.Session(request) # get the sort order sort_type = sess.sort_order() # select based on history tab, pill = "posts", sess.get_tab() params = html.Params(nav='', tab=tab, sort='' ) # the params object will carry layout = settings.USER_PILL_BAR if auth else settings.ANON_PILL_BAR # wether to show the type of the post params = html.Params(tab=tab, pill=pill, sort=sort_type, sort_choices=SORT_CHOICES, layout=layout, title="Tagged as %s" % tag_name) msg = 'Filtering by tag: <b>%s</b>. Subscribe to an <a href="/feeds/tag/%s/">RSS feed</a> to this tag.' % (tag_name,tag_name) messages.info(request, msg) posts = models.query_by_tags(user=user, text=tag_name) posts = apply_sort(request=request, posts=posts, order=sort_type) page = get_page(request, posts, per_page=20) return html.template( request, name='index.html', page=page, params=params)
def main(request): "Main search" counts = request.session.get(SESSION_POST_COUNT, {}) q = request.GET.get('q', '') # query t = request.GET.get('t', 'all') # type params = html.Params(tab='search', q=q, sort='', t=t) subset = get_subset(t) if params.q: form = SearchForm(request.GET) results = search_results(request=request, text=params.q, subset=subset) posts = Post.objects.filter(id__in=[row['pid'] for row in results]).exclude( status=POST_DELETED) for post, row in zip(posts, results): post.context = row['content'] #size = len(results) #messages.info(request, 'Searched results for: %s found %d results' % (params.q, size)) else: form = SearchForm() res = [] objects = [] page = get_page(request, posts, per_page=25) return html.template(request, name='search.html', page=page, params=params, counts=counts, form=form)
def request_info(request, pid): "Requests information from a source" user = request.user post = models.Post.objects.get(id=pid) params = html.Params(site_domain = settings.SITE_DOMAIN, user=user, post=post) params.subject = "Your expert advice is needed at Biostar" if user.is_authenticated(): params.display_name, score = user.profile.display_name, user.profile.score else: params.display_name, score = "Anonymous", 0 params.body = html.fill(name='pages/request-info.txt', params=params) LIMIT = 5 disabled = score < LIMIT if disabled: messages.error(request, "Note: users with fewer than %s reputation points may not send messages via Biostar. You have %s points" % (LIMIT, score)) elif 'submit' in request.POST: form = formdef.RequestInfo(request.POST) if form.is_valid(): send_mail(subject=params.subject, from_email=settings.DEFAULT_FROM_EMAIL, message=params.body, recipient_list=[settings.DEFAULT_FROM_EMAIL, form.cleaned_data['email']], fail_silently=False) messages.info(request, "Your message has been sent.") return html.redirect( post.get_absolute_url() ) else: messages.error(request, "%s" % form.errors) return html.template(request, name='pages/request-info.html', params=params)
def main(request): "Main search" counts = request.session.get(SESSION_POST_COUNT, {}) q = request.GET.get('q','') # query t = request.GET.get('t','all') # type params = html.Params(tab='search', q=q, sort='', t=t) subset = get_subset(t) if params.q: form = SearchForm(request.GET) results = search_results(request=request, text=params.q, subset=subset) posts = Post.objects.filter(id__in=[row['pid'] for row in results]).exclude(status=POST_DELETED) for post, row in zip(posts, results): post.context = row['content'] #size = len(results) #messages.info(request, 'Searched results for: %s found %d results' % (params.q, size)) else: form = SearchForm() res = [] objects = [] page = get_page(request, posts, per_page=25) return html.template(request, name='search.html', page=page, params=params, counts=counts, form=form)
def user_profile(request, uid): "User's profile page" user = request.user target = models.User.objects.get(id=uid) if target == user: notes = models.Note.objects.filter(target=target).select_related('author', 'author__profile', 'root').order_by('-date') page = get_page(request, notes, per_page=10) # we evalute it here so that subsequent status updates won't interfere page.object_list = list(page.object_list) models.Note.objects.filter(target=target).update(unread=False) else: page = None # we need to collate and count the awards awards = models.Award.objects.filter(user=target).select_related('badge').order_by('-date') answer_count = models.Post.objects.filter(author=target, post_type=POST_ANSWER).count() question_count = models.Post.objects.filter(author=target, post_type=POST_QUESTION).count() comment_count = models.Post.objects.filter(author=target, post_type=POST_COMMENT).count() post_count = models.Post.objects.filter(author=target).count() vote_count = models.Vote.objects.filter(author=target).count() award_count = models.Award.objects.filter(user=target).count() params = html.Params(question_count=question_count, answer_count=answer_count, comment_count=comment_count, post_count=post_count, vote_count=vote_count, award_count=award_count) # it the target personal information writable target.editable = target.profile.editable(user) target.authorized = target.profile.authorize(user) return html.template(request, name='user.profile.html', awards=awards, user=request.user,target=target, params=params, page=page)
def main(request): "Main search" counts = request.session.get(SESSION_POST_COUNT, {}) q = request.GET.get('q', '') # query t = request.GET.get('t', 'all') # type params = html.Params(tab='search', q=q, sort='') subset = get_subset(t) if params.q: form = SearchForm(request.GET) res = search_results(request=request, text=params.q, subset=subset) size = len(res) messages.info( request, 'Searched results for: %s found %d results' % (params.q, size)) else: form = SearchForm() res = [] page = get_page(request, res, per_page=10) return html.template(request, name='search.html', page=page, params=params, counts=counts, form=form)
def about(request): "Renders the about page" post_count = models.Post.objects.filter(status=POST_OPEN).count() question_count = models.Post.objects.filter(status=POST_OPEN, type=POST_QUESTION).count() answer_count = models.Post.objects.filter(status=POST_OPEN, type=POST_ANSWER).count() comment_count = models.Post.objects.filter(status=POST_OPEN, type=POST_COMMENT).count() user_count = models.User.objects.filter( profile__status=USER_ACTIVE).count() mods = models.User.objects.filter( profile__type=USER_MODERATOR).select_related("profile").order_by( '-profile__score').all() admins = models.User.objects.filter( profile__type=USER_ADMIN).select_related("profile").order_by( '-profile__score').all() managers = models.User.objects.filter( email=settings.ADMINS[0][1]).select_related("profile").order_by( '-profile__score').all() navloc = dict(about="active") params = html.Params(nav='about', post_count=post_count, user_count=user_count, question_count=question_count, answer_count=answer_count, comment_count=comment_count, admins=admins, mods=mods, navloc=navloc, managers=managers) return html.template(request, name='pages/about.html', params=params)
def show_user(request, uid, post_type=''): "Displays posts by a user" user = models.User.objects.filter( id=uid).select_related('profile').all()[0] params = html.Params(nav='', tab='user', sort='', title="Activity for user %s" % user.profile.display_name) # notification messages.info(request, 'Filtering by user: %s' % user.profile.display_name) post_type = POST_REV_MAP.get(post_type.lower()) if post_type: posts = get_post_manager(request).filter( type=post_type, author=user).order_by('-creation_date') else: posts = get_post_manager(request).filter( type__in=POST_TOPLEVEL, author=user).order_by('-creation_date') posts = posts.select_related('author', 'author__profile', 'root') page = get_page(request, posts, per_page=20) return html.template(request, name='index.html', page=page, params=params)
def show_tag(request, tag_name=None): "Display posts by a certain tag" user = request.user # populate the session data sess = middleware.Session(request) # get the sort order sort_type = sess.sort_order() # select based on history tab, pill = "posts", sess.get_tab() params = html.Params(nav='', tab=tab, sort='') # the params object will carry layout = settings.USER_PILL_BAR if auth else settings.ANON_PILL_BAR # wether to show the type of the post params = html.Params(tab=tab, pill=pill, sort=sort_type, sort_choices=SORT_CHOICES, layout=layout, title="Tagged as %s" % tag_name) msg = 'Filtering by tag: <b>%s</b>. Subscribe to an <a href="/feeds/tag/%s/">RSS feed</a> to this tag.' % ( tag_name, tag_name) messages.info(request, msg) posts = models.query_by_tags(user=user, text=tag_name) posts = apply_sort(request=request, posts=posts, order=sort_type) page = get_page(request, posts, per_page=20) return html.template(request, name='index.html', page=page, params=params)
def user_profile(request, uid, tab='activity'): "User's profile page" if not models.User.objects.filter(id=uid): messages.error(request, "This user does not exist. It has perhaps been deleted.") return html.redirect("/") user = request.user target = models.User.objects.get(id=uid) awards = [] page = None # some information is only visible to the user target.writeable = auth.authorize_user_edit(target=target, user=user, strict=False) target.showall = (target == user) params = html.Params(tab=tab, sort='', title="User %s" % target.profile.display_name) # these do not actually get executed unless explicitly rendered in the page bookmarks = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).select_related('post', 'post__author__profile').order_by('id') awards = models.Award.objects.filter(user=target).select_related('badge').order_by('-date') # we need to collate and count the awards answer_count = models.Post.objects.filter(author=target, type=POST_ANSWER).count() question_count = models.Post.objects.filter(author=target, type=POST_QUESTION).count() comment_count = models.Post.objects.filter(author=target, type=POST_COMMENT).count() post_count = models.Post.objects.filter(author=target).count() vote_count = models.Vote.objects.filter(author=target).count() award_count = models.Award.objects.filter(user=target).count() note_count = models.Note.objects.filter(target=target, unread=True).count() bookmarks_count = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).count() if tab in [ 'activity', 'created' ]: if tab == 'created': notes = models.Note.objects.filter(sender=target, target=target, type=NOTE_USER).select_related('author', 'author__profile', 'root').order_by('-date') else: notes = models.Note.objects.filter(target=target, type=NOTE_USER).exclude(sender=target).select_related('author', 'author__profile', 'root').order_by('-date') page = get_page(request, notes, per_page=15) # we evalute it here so that subsequent status updates won't interfere page.object_list = list(page.object_list) if user == target: models.Note.objects.filter(target=target, unread=True).update(unread=False) models.UserProfile.objects.filter(user=target).update(new_messages=0) note_count = 0 elif tab == 'bookmarks': bookmarks = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).select_related('post', 'post__author__profile').order_by('-date') page = get_page(request, bookmarks, per_page=15) elif tab =="moderator": notes = models.Note.objects.filter(target=target, type=NOTE_MODERATOR).select_related('author', 'author__profile').order_by('-date') page = get_page(request, notes, per_page=15) params.update(dict(question_count=question_count, answer_count=answer_count, note_count=note_count, bookmarks_count=bookmarks_count, comment_count=comment_count, post_count=post_count, vote_count=vote_count, award_count=award_count)) return html.template(request, name='user.profile.html', awards=awards, user=request.user,target=target, params=params, page=page)
def revision_show(request, pid): post = models.Post.objects.get(pk=pid) revs = post.revisions.order_by('-date').select_related( 'author', 'lastedit_author') return html.template(request, name='revision.show.html', revs=revs, post=post)
def show_tag(request, tag_name=None): "Display posts by a certain tag" user = request.user params = html.Params(nav='', tab='tags') messages.warning(request, 'Filtering by tag: %s' % tag_name) posts = models.query_by_tags(user=user, text=tag_name).order_by('-rank') page = get_page(request, posts, per_page=20) return html.template( request, name='index.html', page=page, params=params)
def rss(request): "Renders the rss feed page" user = request.user params = html.Params(nav='rss') return html.template(request, name='pages/rss.html', params=params, user=user)
def google(request): "Renders the rss feed page" user = request.user params = html.Params(nav='google') return html.template(request, name='pages/google.html', params=params, user=user)
def user_edit(request, uid): "User's profile page" target = models.User.objects.select_related('profile').get(id=uid) allow = auth.authorize_user_edit(target=target, user=request.user, strict=False) if not allow: messages.error(request, "unable to edit this user") return html.redirect(target.profile.get_absolute_url() ) # valid incoming fields fields = "display_name about_me website location my_tags scholar hide_ads".split() if request.method == 'GET': initial = dict(email=target.email) for field in fields: initial[field] = getattr(target.profile, field) or '' form = UserForm(initial) return html.template(request, name='user.edit.html', target=target, form=form) elif request.method == 'POST': form = UserForm(request.POST) if not form.is_valid(): return html.template(request, name='user.edit.html', target=target, form=form) else: for field in fields: setattr(target.profile, field, form.cleaned_data[field]) # hiding ads requires a minimum reputation if target.profile.hide_ads and target.profile.score < settings.AD_MIN_REP: target.profile.hide_ads = False messages.warning(request, "The reputation needed to hide ads is %s" % (settings.AD_MIN_REP * 10)) # check the new email new_email = form.cleaned_data['email'].strip() if new_email != target.email and models.User.objects.filter(email=new_email): # cannot set your email to an existing other user 'semail messages.error(request, "This email is aready taken - please merge the accounts!") else: target.email = new_email target.profile.save() target.save() url = reverse('main.server.views.user_profile', kwargs=dict(uid=target.id)) return html.redirect(url)
def post_edit(request, pid=0): "Handles the editing of an existing post" user = request.user name = "post.edit.html" post = models.Post.objects.get(pk=pid) if not post.open and not user.can_moderate: messages.error(request, 'Post is closed. It may not be edited.') return redirect(post.root) # verify that this user may indeed modify the post if not auth.authorize_post_edit(post=post, user=request.user, strict=False): messages.error(request, 'User may not edit the post.') return redirect(post.root) toplevel = post.top_level factory = formdef.TopLevelContent if toplevel else formdef.ChildContent params = html.Params(tab='edit', title="Edit post", toplevel=toplevel) if request.method == 'GET': # no incoming data, render prefilled form form = factory(initial=dict(title=post.title, content=post.content, tag_val=post.tag_val, type=post.type, context=post.context)) return html.template(request, name=name, form=form, params=params) # process the incoming data assert request.method == 'POST', "Method=%s" % request.method form = factory(request.POST) if not form.is_valid(): # returns with an error message return html.template(request, name=name, form=form, params=params) # form is valid now set the attributes for key, value in form.cleaned_data.items(): setattr(post, key, value) post.lastedit_user = user post.lastedit_date = datetime.now() post.set_tags() # this saves the post return redirect(post)
def url500(request): "Custom error handler" type, value, tb = sys.exc_info() trace = traceback.format_exc() trace = "\n<trace>\n%s</trace>" % trace logger.error(trace) return html.template(request, name='500.html', path=request.path, value=value)
def show_tag(request, tag_name=None): "Display posts by a certain tag" user = request.user params = html.Params(nav='', tab='tags', sort='') msg = 'Filtering by tag: <b>%s</b>. Subscribe to an <a href="/feeds/tag/%s/">RSS feed</a> to this tag.' % (tag_name,tag_name) messages.info(request, msg) posts = models.query_by_tags(user=user, text=tag_name).order_by('-rank') page = get_page(request, posts, per_page=20) return html.template( request, name='index.html', page=page, params=params)
def user_list(request): search = request.GET.get('m','')[:80] # trim for sanity if search: query = Q(profile__display_name__icontains=search) users = models.User.objects.filter(query).select_related('profile').order_by("-profile__score") else: users = models.User.objects.select_related('profile').order_by("-profile__score") page = get_page(request, users, per_page=24) return html.template(request, name='user.list.html', page=page)
def more(request, pid): counts = request.session.get(SESSION_POST_COUNT, {}) form = SearchForm() params = html.Params(tab='search', q="", sort='') results = more_like_this(request=request, pid=pid) posts = Post.objects.filter(id__in=[row['pid'] for row in results]).exclude(status=POST_DELETED) for post, row in zip(posts, results): post.context = row['content'] page = get_page(request, posts, per_page=10) return html.template(request, name='search.html', page=page, params=params, counts=counts, form=form)
def user_profile(request, uid, tab='activity'): "User's profile page" if not models.User.objects.filter(id=uid): messages.error(request, "This user does not exist. It has perhaps been deleted.") return html.redirect("/") user = request.user target = models.User.objects.get(id=uid) awards = [] page = None # some information is only visible to the user target.writeable = auth.authorize_user_edit(target=target, user=user, strict=False) target.showall = (target == user) params = html.Params(tab=tab, sort='') # these do not actually get executed unless explicitly rendered in the page bookmarks = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).select_related('post', 'post__author__profile').order_by('id') awards = models.Award.objects.filter(user=target).select_related('badge').order_by('-date') # we need to collate and count the awards answer_count = models.Post.objects.filter(author=target, type=POST_ANSWER).count() question_count = models.Post.objects.filter(author=target, type=POST_QUESTION).count() comment_count = models.Post.objects.filter(author=target, type=POST_COMMENT).count() post_count = models.Post.objects.filter(author=target).count() vote_count = models.Vote.objects.filter(author=target).count() award_count = models.Award.objects.filter(user=target).count() note_count = models.Note.objects.filter(target=target, unread=True).count() bookmarks_count = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).count() if tab == 'activity': notes = models.Note.objects.filter(target=target, type=NOTE_USER).select_related('author', 'author__profile', 'root').order_by('-date') page = get_page(request, notes, per_page=15) # we evalute it here so that subsequent status updates won't interfere page.object_list = list(page.object_list) if user==target: models.Note.objects.filter(target=target).update(unread=False) models.UserProfile.objects.filter(user=target).update(new_messages=0) note_count = 0 elif tab == 'bookmarks': bookmarks = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).select_related('post', 'post__author__profile').order_by('-date') page = get_page(request, bookmarks, per_page=15) elif tab =="moderator": notes = models.Note.objects.filter(target=target, type=NOTE_MODERATOR).select_related('author', 'author__profile').order_by('-date') page = get_page(request, notes, per_page=15) params.update(dict(question_count=question_count, answer_count=answer_count, note_count=note_count, bookmarks_count=bookmarks_count, comment_count=comment_count, post_count=post_count, vote_count=vote_count, award_count=award_count)) return html.template(request, name='user.profile.html', awards=awards, user=request.user,target=target, params=params, page=page)
def post_list(request, uid=0, post_type=None): params = html.Params() posts = get_posts(request, post_type=post_type) if uid: user = models.User.objects.filter(id=uid).select_related('profile').all()[0] posts = posts.filter(author=user) params.setr('Filter: %s' % user.profile.display_name) posts = posts.order_by('-lastedit_date') page = get_page(request, posts, per_page=20) return html.template( request, name='post.list.html', page=page, params=params)
def user_list(request): search = request.GET.get('m','')[:80] # trim for sanity params = html.Params(nav='users', sort='') if search: query = Q(profile__display_name__icontains=search) else: query = Q(id__gt=0) users = models.User.objects.filter(query).select_related('profile').order_by("-profile__score", "id") page = get_page(request, users, per_page=24) return html.template(request, name='user.list.html', page=page, params=params)
def user_list(request): search = request.GET.get('m','')[:80] # trim for sanity params = html.Params(nav='users', sort='') if search: query = Q(profile__display_name__icontains=search) else: query = Q(id__gt=0) users = models.User.objects.filter(query).select_related('profile').order_by("-profile__score") page = get_page(request, users, per_page=24) return html.template(request, name='user.list.html', page=page, params=params)
def post_edit(request, pid=0): "Handles the editing of an existing post" user = request.user name = "post.edit.html" post = models.Post.objects.get(pk=pid) if not post.open and not user.can_moderate: messages.error(request, 'Post is closed. It may not be edited.') return redirect(post.root) # verify that this user may indeed modify the post if not auth.authorize_post_edit(post=post, user=request.user, strict=False): messages.error(request, 'User may not edit the post.') return redirect(post.root) toplevel = post.top_level factory = formdef.TopLevelContent if toplevel else formdef.ChildContent params = html.Params(tab='edit', title="Edit post", toplevel=toplevel) if request.method == 'GET': # no incoming data, render prefilled form form = factory(initial=dict(title=post.title, content=post.content, tag_val=post.tag_val, type=post.type)) return html.template(request, name=name, form=form, params=params) # process the incoming data assert request.method == 'POST', "Method=%s" % request.method form = factory(request.POST) if not form.is_valid(): # returns with an error message return html.template(request, name=name, form=form, params=params) # form is valid now set the attributes for key, value in form.cleaned_data.items(): setattr(post, key, value) post.lastedit_user = user post.lastedit_date = datetime.now() post.set_tags() # this saves the post return redirect(post)
def testpage(request): "Renders a test page" user = request.user params = html.Params(nav='rss') posts = models.Post.objects posts = posts.exclude(type=POST_BLOG).select_related('author', 'author__profile') posts = posts.order_by('-rank')[:10] posts = list(posts) rows = connection.queries return html.template(request, name='pages/testpage.html', params=params, user=user, rows=rows)
def badge_list(request): user = request.user badges = models.Badge.objects.filter(secret=False).order_by('-count', '-type') # set a flag for badges that a user has if user.is_authenticated(): earned = set( models.Award.objects.filter(user=user).values_list('badge__name', flat=True).distinct() ) else: earned = [] for badge in badges: badge.earned = badge.name in earned params = html.Params(nav='badges', sort='') return html.template(request, name='badge.list.html', badges=badges, params=params)
def revision_list(request, pid): post = models.Post.objects.get(pk=pid) root = post.get_root() def full_view(rev): line = '-' * 10 title = "Title: %s" % rev.title content = "%s" % rev.content tag_string = "Tags: %s" % rev.tag_string text = "\n".join( (title, line, content, line, tag_string) ) return text revisions = map(full_view, post.revisions.order_by('date')) revisions.reverse() return html.template(request, name='revision.list.html', revisions=revisions, post=post, root=root)
def more(request, pid): counts = request.session.get(SESSION_POST_COUNT, {}) form = SearchForm() params = html.Params(tab='search', q="", sort='') results = more_like_this(request=request, pid=pid) posts = Post.objects.filter( id__in=[row['pid'] for row in results]).exclude(status=POST_DELETED) for post, row in zip(posts, results): post.context = row['content'] page = get_page(request, posts, per_page=10) return html.template(request, name='search.html', page=page, params=params, counts=counts, form=form)
def about(request): "Renders the about page" post_count = models.Post.objects.filter(deleted=False).count() question_count = models.Post.objects.filter(deleted=False, post_type=const.POST_QUESTION).count() answer_count = models.Post.objects.filter(deleted=False, post_type=const.POST_ANSWER).count() comment_count = models.Post.objects.filter(deleted=False, post_type=const.POST_COMMENT).count() user_count = models.User.objects.filter(profile__suspended=False).count() mods = models.User.objects.filter(profile__type=const.USER_MODERATOR).select_related("profile").all()[:100] admins = models.User.objects.filter(profile__type=const.USER_ADMIN).select_related("profile").all()[:100] params = html.Params(post_count=post_count, user_count=user_count, question_count=question_count, answer_count=answer_count, comment_count=comment_count, admins=admins, mods=mods) return html.template(request, name='about.html', params=params)
def show_user(request, uid, post_type=''): "Displays posts by a user" user = models.User.objects.filter(id=uid).select_related('profile').all()[0] params = html.Params(nav='', tab='user', sort='') # notification messages.info(request, 'Filtering by user: %s' % user.profile.display_name) post_type = POST_REV_MAP.get(post_type.lower()) if post_type: posts = get_post_manager(request).filter(type=post_type, author=user).order_by('-creation_date') else: posts = get_post_manager(request).filter(type__in=POST_TOPLEVEL, author=user).order_by('-creation_date') page = get_page(request, posts, per_page=20) return html.template( request, name='index.html', page=page, params=params)
def tag_list(request): # remove null tags models.Tag.objects.all().filter(count=0).delete() search = request.GET.get('m','')[:80] # trim for sanity if search: query = Q(name__icontains=search) else: query = Q(id__gt=0) tags = models.Tag.objects.filter(query).order_by('name') page = get_page(request, tags, per_page=152) params = html.Params(nav='tags', sort='') return html.template(request, name='tag.list.html', page=page, params=params)
def tag_list(request): # remove null tags models.Tag.objects.all().filter(count=0).delete() search = request.GET.get('m','')[:80] # trim for sanity if search: query = Q(name__icontains=search) else: query = Q(id__gt=0) tags = models.Tag.objects.filter(query).order_by('-count') page = get_page(request, tags, per_page=152) params = html.Params(nav='tags', sort='') return html.template(request, name='tag.list.html', page=page, params=params)
def help_external(request, word='main'): "Renders a test page" user = request.user # create a test key/value pair name = "GALAXY" pair = settings.EXTERNAL_AUTHENICATION.get(name) if pair: messages.info(request, "The <b>%s</b> key is active!" % name) key, patt = pair else: key, patt = "abcd", "" # prepare the data data = dict(display_name="Jane Doe", username="******", email="*****@*****.**", tags="galaxy bwa", title="How do I run bwa?", tool_name="Uber Convert", tool_id=1, tool_version="0.0.1.alpha", ) # encode the data and get the digest enc, digest = formdef.encode(data, key=key) # encode into url parameters store = dict(name=name, data=enc, digest=digest) # encoding the parameters into the url to be loaded params = urllib.urlencode(store.items()) login_url = "/x/?%s" % params store['action'] = 'new' params = urllib.urlencode(store.items()) post_url = "/x/?%s" % params # override login_url = "http://test.biostars.org" + login_url post_url = "http://test.biostars.org" + post_url # this is used inside the templates params = html.Params(post_url=post_url, login_url=login_url, key=key, data=data, enc=enc, digest=digest) return html.template(request, name='help/help.external.html', params=params, user=user)
def help_external(request, word='main'): "Renders a test page" user = request.user # create a test key/value pair name = settings.EXTERNAL_AUTHENICATION_TEST_KEY pair = settings.EXTERNAL_AUTHENICATION.get(name) if pair: messages.info(request, "The <b>%s</b> key is active!" % name) key, patt = pair else: key, patt = "abcd", "" # prepare the data data = dict(display_name="Jane Doe", username="******", email="*****@*****.**", tags="galaxy bwa", title="How do I run bwa?", tool_name="Uber Convert", tool_id=1, tool_version="0.0.1.alpha", ) # encode the data and get the digest enc, digest = formdef.encode(data, key=key) # encode into url parameters store = dict(name=name, data=enc, digest=digest) # encoding the parameters into the url to be loaded params = urllib.urlencode(store.items()) login_url = "/x/?%s" % params store['action'] = 'new' params = urllib.urlencode(store.items()) post_url = "/x/?%s" % params # override login_url = settings.EXTERNAL_AUTHENICATION_TEST_URL + login_url post_url = settings.EXTERNAL_AUTHENICATION_TEST_URL + post_url # this is used inside the templates params = html.Params(post_url=post_url, login_url=login_url, key=key, data=data, enc=enc, digest=digest) return html.template(request, name='help/help.external.html', params=params, user=user)
def index(request): "Main page" # this will contain the query if it was sent query = request.REQUEST.get('q','') pids = action.search(query) params = html.Params() if query: params.remind = 'Searching for: %s' % query qs = get_posts(request, post_type=None) qs = qs.filter(id__in=pids) else: qs = get_posts(request) qs = qs.order_by('-touch_date') page = get_page(request, qs, per_page=20) return html.template( request, name='index.html', page=page, params=params)
def about(request): "Renders the about page" post_count = models.Post.objects.filter(status=POST_OPEN).count() question_count = models.Post.objects.filter(status=POST_OPEN, type=POST_QUESTION).count() answer_count = models.Post.objects.filter(status=POST_OPEN, type=POST_ANSWER).count() comment_count = models.Post.objects.filter(status=POST_OPEN, type=POST_COMMENT).count() user_count = models.User.objects.filter(profile__status=USER_ACTIVE).count() mods = models.User.objects.filter(profile__type=USER_MODERATOR).select_related("profile").order_by('-profile__score').all() admins = models.User.objects.filter(profile__type=USER_ADMIN).select_related("profile").order_by('-profile__score').all() managers = models.User.objects.filter(email=settings.ADMINS[0][1]).select_related("profile").order_by('-profile__score').all() navloc = dict(about="active") params = html.Params(nav='about', post_count=post_count, user_count=user_count, question_count=question_count, answer_count=answer_count, comment_count=comment_count, admins=admins, mods=mods, navloc=navloc, managers=managers) return html.template(request, name='pages/about.html', params=params)
def testpage(request): "Renders a test page" user = request.user params = html.Params(nav='rss') posts = models.Post.objects posts = posts.exclude(type=POST_BLOG).select_related( 'author', 'author__profile') posts = posts.order_by('-rank')[:10] posts = list(posts) rows = connection.queries return html.template(request, name='pages/testpage.html', params=params, user=user, rows=rows)
def post_reparent(request, pid, rid=0): "Reparent a post" post = models.Post.objects.get(id=pid) root = post.root parent = post.parent allow = auth.authorize_post_edit(post=post, user=request.user, strict=False) if not allow: messages.error(request, "Reparent access denied") return html.redirect(post.get_absolute_url()) if post.type in POST_TOPLEVEL or post == post.root: messages.error(request, "Cannot reparent a toplevel post") return html.redirect(post.get_absolute_url()) # these are the valid targets targets = models.Post.objects.filter(root=root).select_related('author', 'author__profile').exclude(id__in=(post.id, parent.id)) target = request.REQUEST.get('target') if target: target = models.Post.objects.get(id=target) if target not in targets: messages.error(request, "Invalid reparent %s -> %s" % (post.id, target.id) ) return html.redirect(post.get_absolute_url()) # comment to comment reparent is not yet supported if target.type == POST_COMMENT and post.type == POST_COMMENT: messages.error(request, "Comment to comment reparent %s -> %s not implemented" % (post.id, target.id) ) return html.redirect(post.get_absolute_url()) # perfomr the reparent post.parent = target question = (target.type == POST_QUESTION) post.type = POST_ANSWER if question else POST_COMMENT post.save() # valid target to be applied messages.info(request, "Reparenting %s to %s" % (post.id, target.id)) return html.redirect(post.get_absolute_url()) return html.template(request, name='post.reparent.html', post=post, targets=targets)
def index(request, tab=""): "Main page" user = request.user if not tab: # if the user has a mytags then switch to that if user.is_authenticated() and user.profile.my_tags: tab = 'mytags' else: tab = 'questions' if tab not in VALID_TABS: messages.error(request, 'Unknown content type requested') params = html.Params(tab=tab) # this will fill in the query (q) and the match (m)parameters params.parse(request) # update with counts counts = request.session.get(SESSION_POST_COUNT, {}) # returns the object manager that contains all or only visible posts posts = get_post_manager(request) # filter posts by type posts = filter_by_type(posts=posts, value=tab) # sort selected in the dropdown. by default lists cannot be sorted sort = request.GET.get('sort', '').lower() # attempts to remeber the last sorting sort = get_last_sort(request, sort) # override sort in the recent tab if tab == 'recent': sort = 'creation' posts = posts.order_by('-creation_date') else: posts = apply_sort(posts, value=sort, request=request) if tab == 'planet': models.decorate_posts(posts, user) if tab == 'mytags': if user.is_authenticated(): text = user.profile.my_tags if not text: messages.warning(request, "This Tab will show posts matching the My Tags fields in your user profile.") else: messages.info(request, "Filtering by %s" % text) posts = models.query_by_tags(user,text=text) posts = apply_sort(posts, value=sort, request=request) else: messages.warning(request, "This Tab is populated only for registered users based on the My Tags field in their user profile") posts = [] sort_choices = "rank,views,votes,answers,bookmarks,creation,edit".split(',') # put sort options in params so they can be displayed params.update(dict(sort=sort, sort_choices=sort_choices)) # reset the counts update_counts(request, tab, 0) page = get_page(request, posts, per_page=POSTS_PER_PAGE) return html.template(request, name='index.html', page=page, params=params, counts=counts)
def modlog_list(request): "Lists of all moderator actions" mods = models.Note.objects.filter(type=NOTE_MODERATOR).select_related('sender', 'target', 'post', 'sender_profile').order_by('-date') page = get_page(request, mods) return html.template(request, name='modlog.list.html', page=page)
domain=settings.SITE_DOMAIN, master_id=master.id, remove_id=remove.id, master_name = master.profile.display_name, remove_name=remove.profile.display_name, master_email = master.email, remove_email=remove.email, request_id = request.user.id, request_name = user.profile.display_name, ) body = ACCOUNT_MERGE_EMAIL % fill logger.info('sending email to %s' % settings.SERVER_EMAIL) send_mail(subject='BioStar: account merge request', message=body, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[ settings.DEFAULT_FROM_EMAIL ], fail_silently=False) messages.info(request, "Your request for account merge has been submitted for review.") return html.redirect( user.profile.get_absolute_url() ) except Exception, exc: messages.error(request, 'Submission error %s' % exc) else: form = MergeForm() params = html.Params(nav='') return html.template(request, name='pages/merge.html', params=params, form=form) def migrate(master, remove): "Migrates user data" UserOpenID.objects.filter(user=remove).update(user=master) models.Vote.objects.filter(author=remove).update(author=master) models.Note.objects.filter(sender=remove).update(sender=master) models.Note.objects.filter(target=remove).update(target=master) models.Post.objects.filter(author=remove).update(author=master) models.Post.objects.filter(lastedit_user=remove).update(lastedit_user=master) models.PostRevision.objects.filter(author=remove).update(author=master) models.Award.objects.filter(user=remove).update(user=master) master.profile.score += remove.profile.score master.profile.save()
email=settings.ADMINS[0][1]).select_related("profile").order_by( '-profile__score').all() navloc = dict(about="active") params = html.Params(nav='about', post_count=post_count, user_count=user_count, question_count=question_count, answer_count=answer_count, comment_count=comment_count, admins=admins, mods=mods, navloc=navloc, managers=managers, visitors=visitors) return html.template(request, name='pages/about.html', params=params) def rss(request): "Renders the rss feed page" user = request.user params = html.Params(nav='rss') return html.template(request, name='pages/rss.html', params=params, user=user) def request_info(request, pid): "Requests information from a source" user = request.user
def faq(request): "Renders the faq page" best = models.User.objects.all().select_related("profile").order_by( '-profile__score')[:3] params = html.Params(nav='faq', best=best) return html.template(request, name='pages/faq.html', params=params)
def beta(request): "Renders the beta test information page" params = html.Params(nav='') return html.template(request, name='pages/beta.html', params=params)