def feedback(request): data = {'page_class': 'meta'} form = None if askbot_settings.ALLOW_ANONYMOUS_FEEDBACK is False: if request.user.is_anonymous(): message = _('Please sign in or register to send your feedback') request.user.message_set.create(message=message) redirect_url = get_login_url() + '?next=' + request.path return HttpResponseRedirect(redirect_url) if request.method == "POST": form = FeedbackForm( is_auth=request.user.is_authenticated(), data=request.POST ) if form.is_valid(): if not request.user.is_authenticated(): data['email'] = form.cleaned_data.get('email',None) data['message'] = form.cleaned_data['message'] data['name'] = form.cleaned_data.get('name',None) template = get_template('email/feedback_email.txt', request) message = template.render(RequestContext(request, data)) mail_moderators(_('Q&A forum feedback'), message) msg = _('Thanks for the feedback!') request.user.message_set.create(message=msg) return render_into_skin("autoclose.html", data, request) else: form = FeedbackForm(is_auth = request.user.is_authenticated(), initial={'next':get_next_url(request)}) data['form'] = form return render_into_skin('feedback.html', data, request)
def faq(request): if getattr(askbot_settings, 'FORUM_FAQ',''): text = _(getattr(askbot_settings, 'FORUM_FAQ','')) data = { 'gravatar_faq_url': reverse('faq') + '#gravatar', #'send_email_key_url': reverse('send_email_key'), 'ask_question_url': reverse('ask'), 'page_class': 'meta', } forum_faq = render_text_into_skin(text, data, request) data_out = { 'gravatar_faq_url': reverse('faq') + '#gravatar', #'send_email_key_url': reverse('send_email_key'), 'ask_question_url': reverse('ask'), 'page_class': 'meta', 'forum_faq' : forum_faq, } return render_into_skin('faq.html', data_out, request) data = { 'gravatar_faq_url': reverse('faq') + '#gravatar', #'send_email_key_url': reverse('send_email_key'), 'ask_question_url': reverse('ask'), 'page_class': 'meta', } return render_into_skin('faq_static.html', data, request)
def faq(request): if askbot_settings.FORUM_FAQ.strip() != "": data = {"title": _("FAQ"), "content": askbot_settings.FORUM_FAQ, "page_class": "meta"} return render_into_skin("static_page.html", data, request) else: data = { "gravatar_faq_url": reverse("faq") + "#gravatar", "ask_question_url": reverse("ask"), "page_class": "meta", } return render_into_skin("faq_static.html", data, request)
def faq(request): if askbot_settings.FORUM_FAQ.strip() != '': return render_into_skin( 'static_page.html', {'title': _('FAQ'), 'content': askbot_settings.FORUM_FAQ}, request ) else: data = { 'gravatar_faq_url': reverse('faq') + '#gravatar', 'ask_question_url': reverse('ask'), 'page_class': 'meta', } return render_into_skin('faq_static.html', data, request)
def user_tags(request, user, context): """a view showing users subscribed and ignored tags""" subscribed_tags = models.Tag.objects.filter( user_selections__reason__contains = 'S', user_selections__user = user ) ignored_tags = models.Tag.objects.filter( user_selections__reason__contains = 'I', user_selections__user = user ) favorite_tags = models.Tag.objects.filter( user_selections__reason__contains = 'F', user_selections__user = user ) strategy = user.email_tag_filter_strategy tag_subscription_status = dict(const.TAG_EMAIL_FILTER_STRATEGY_CHOICES)[strategy] data = { 'tag_subscription_status': tag_subscription_status, 'subscribed_tags': subscribed_tags, 'subscribed_wildcards': user.get_selected_wildcard_tags('subscribed'), 'ignored_tags': ignored_tags, 'ignored_wildcards': user.get_selected_wildcard_tags('ignored'), 'favorite_tags': favorite_tags, 'favorite_wildcards': user.get_selected_wildcard_tags('followed'), 'use_wildcards': askbot_settings.USE_WILDCARD_TAGS, 'view_user': user } context.update(data) return render_into_skin('user_profile/user_tags.html', data, request)
def confirm(request, amount): """ List of Questions, Tagged questions, and Unanswered questions. matching search query or user selection """ if request.user.is_anonymous(): request.user.message_set.create(message = unicode('您要先登入後才能購買iBon! <a href="/account/signin/?bext=/">立刻登入</a>')) return HttpResponseRedirect(reverse('index')) user=request.user comment = user.username+unicode('產生iBon購買條碼, 金額:')+unicode(amount)+unicode('元') transaction = Transaction( user=user, income=0, outcome=0, comment=comment, #question = fake_question, invoice=False, trans_at=datetime.datetime.now(), transaction_type=twmodeconst.TYPE_TRANSACTION_BUY_IBON_ISSUE, #todo: fix magic number balance=user.balance, question_id=None ) transaction.save() template_data = { 'Roturl': 'http://www.keepwin.com.tw/payment/Roturl/', 'Data_id': transaction.id, 'amount':amount, 'user':user, 'ip':get_client_ip(request), } #return render_into_skin('main_page_twmode.html', template_data, request) return render_into_skin('payment_confirm.html', template_data, request)
def privacy(request): data = { 'title': _('Privacy policy'), 'page_class': 'meta', 'content': askbot_settings.FORUM_PRIVACY } return render_into_skin('static_page.html', data, request)
def add(request, extra_context=None, next_override=None, upload_form=UploadAvatarForm, *args, **kwargs): if extra_context is None: extra_context = {} avatar, avatars = _get_avatars(request.user) upload_avatar_form = upload_form(request.POST or None, request.FILES or None, user=request.user) if request.method == "POST" and 'avatar' in request.FILES: if upload_avatar_form.is_valid(): avatar = Avatar( user = request.user, primary = True, ) image_file = request.FILES['avatar'] avatar.avatar.save(image_file.name, image_file) avatar.save() request.user.message_set.create( message=_("Successfully uploaded a new avatar.")) if notification: _notification_updated(request, avatar) return HttpResponseRedirect(next_override or _get_next(request)) data = { 'avatar': avatar, 'avatars': avatars, 'upload_avatar_form': upload_avatar_form, 'next': next_override or _get_next(request), 'view_user': request.user, 'page_class': 'avatar-page', } if extra_context: data.update(extra_context) return render_into_skin('avatar/add.html', data, request)
def delete(request, extra_context=None, next_override=None, *args, **kwargs): if extra_context is None: extra_context = {} avatar, avatars = _get_avatars(request.user) delete_avatar_form = DeleteAvatarForm(request.POST or None, user=request.user, avatars=avatars) if request.method == 'POST': if delete_avatar_form.is_valid(): ids = delete_avatar_form.cleaned_data['choices'] if unicode(avatar.id) in ids and avatars.count() > len(ids): # Find the next best avatar, and set it as the new primary for a in avatars: if unicode(a.id) not in ids: a.primary = True a.save() if notification: _notification_updated(request, a) break Avatar.objects.filter(id__in=ids).delete() request.user.message_set.create( message=_("Successfully deleted the requested avatars.")) return HttpResponseRedirect(next_override or _get_next(request)) data = { 'avatar': avatar, 'avatars': avatars, 'delete_avatar_form': delete_avatar_form, 'next': next_override or _get_next(request), 'view_user': request.user, 'page_class': 'avatar-page', } if extra_context: data.update(extra_context) return render_into_skin('avatar/confirm_delete.html', data, request)
def import_data(request): """a view allowing the site administrator upload stackexchange data """ #allow to use this view to site admins #or when the forum in completely empty if request.user.is_anonymous() or (not request.user.is_administrator()): if models.Post.objects.get_questions().exists(): raise Http404 if request.method == 'POST': #if not request.is_ajax(): # raise Http404 form = forms.DumpUploadForm(request.POST, request.FILES) if form.is_valid(): dump_file = form.cleaned_data['dump_file'] dump_storage = tempfile.NamedTemporaryFile() #save the temp file for chunk in dump_file.chunks(): dump_storage.write(chunk) dump_storage.flush() return HttpResponse(__import_se_data(dump_storage)) #yield HttpResponse(_('StackExchange import complete.'), mimetype='text/plain') #dump_storage.close() else: form = forms.DumpUploadForm() data = { 'dump_upload_form': form, 'need_configuration': (not stackexchange.is_ready()) } return render_into_skin('import_data.html', data, request)
def widgets(request): data = { 'ask_widgets': models.AskWidget.objects.all().count(), 'question_widgets': models.QuestionWidget.objects.all().count(), 'page_class': 'widgets' } return render_into_skin('embed/widgets.html', data, request)
def question_widget(request, widget_id): """Returns the first x questions based on certain tags. @returns template with those questions listed.""" # make sure this is a GET request with the correct parameters. widget = get_object_or_404(models.QuestionWidget, pk=widget_id) if request.method != 'GET': raise Http404 filter_params = {} if widget.tagnames: filter_params['tags__name__in'] = widget.tagnames.split(' ') if widget.group: filter_params['groups'] = widget.group #simple title search for now if widget.search_query: filter_params['title__icontains'] = widget.search_query if filter_params: threads = models.Thread.objects.filter(**filter_params).order_by( widget.order_by)[:widget.question_number] else: threads = models.Thread.objects.all().order_by( widget.order_by)[:widget.question_number] data = {'threads': threads, 'widget': widget} return render_into_skin('embed/question_widget.html', data, request)
def edit_widget(request, model, widget_id): model_class = _get_model(model) form_class = _get_form(model) widget = get_object_or_404(model_class, pk=widget_id) if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): form_dict = dict.copy(form.cleaned_data) for key in widget.__dict__: if key.endswith('_id'): form_key = key.split('_id')[0] if form_dict[form_key]: form_dict[key] = form_dict[form_key].id del form_dict[form_key] else: continue widget.__dict__.update(form_dict) widget.save() return redirect('list_widgets', model=model) else: initial_dict = dict.copy(widget.__dict__) for key in initial_dict: if key.endswith('_id'): new_key = key.split('_id')[0] initial_dict[new_key] = initial_dict[key] del initial_dict[key] else: continue del initial_dict['_state'] form = form_class(initial=initial_dict) data = {'form': form, 'action': 'edit', 'widget_name': model} return render_into_skin('embed/widget_form.html', data, request)
def new_solution_form(request, mid, pid): exercise_post = models.Post.objects.filter( post_type = 'exercise', id = mid ).select_related('thread')[0] problem_post = models.Post.objects.filter( post_type = 'problem', id = pid ).select_related('thread')[0] thread = exercise_post.thread initial = { 'wiki': exercise_post.wiki and askbot_settings.WIKI_ON, 'email_notify': thread.is_followed_by(request.user) } solution_form = SolutionForm(initial) # if exercise doesn't exist, redirect to main page data = { 'pid': pid, 'mid': mid, 'exercise': exercise_post, 'problem': problem_post, 'thread': thread, 'solution_form': solution_form } return render_into_skin('exercise/solution_form.html', data, request)
def user_reputation(request, user, context): reputes = models.Repute.objects.filter(user=user).select_related( 'question', 'question__thread', 'user').order_by('-reputed_at') # prepare data for the graph - last values go in first rep_list = [ '[%s,%s]' % (calendar.timegm(datetime.datetime.now().timetuple()) * 1000, user.reputation) ] for rep in reputes: rep_list.append('[%s,%s]' % (calendar.timegm(rep.reputed_at.timetuple()) * 1000, rep.reputation)) reps = ','.join(rep_list) reps = '[%s]' % reps data = { 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_name': 'reputation', 'tab_description': _('user karma'), 'page_title': _("Profile - User's Karma"), 'reputation': reputes, 'reps': reps } context.update(data) return render_into_skin('user_profile/user_reputation.html', context, request)
def validation_email_sent(request): """this function is called only if EMAIL_VALIDATION setting is set to True bolean value, basically dead now""" assert askbot_settings.EMAIL_VALIDATION == True logging.debug("") data = {"email": request.user.email, "change_email_url": reverse("user_changeemail"), "action_type": "validate"} return render_into_skin("authopenid/changeemail.html", data, request)
def send_email_key(request): """ url = /email/sendkey/ view that is shown right after sending email key email sending is called internally raises 404 if email validation is off if current email is valid shows 'key_not_sent' view of authopenid/changeemail.html template """ if askbot_settings.EMAIL_VALIDATION == True: if request.user.email_isvalid: data = { 'email': request.user.email, 'action_type': 'key_not_sent', 'change_link': reverse('user_changeemail') } return render_into_skin( 'authopenid/changeemail.html', data, request ) else: send_new_email_key(request.user) return validation_email_sent(request) else: raise Http404
def send_email_key(request): """ url = /email/sendkey/ view that is shown right after sending email key email sending is called internally raises 404 if email validation is off if current email is valid shows 'key_not_sent' view of authopenid/changeemail.html template """ if askbot_settings.EMAIL_VALIDATION == True: if request.user.email_isvalid: data = { 'email': request.user.email, 'action_type': 'key_not_sent', 'change_link': reverse('user_changeemail') } return render_into_skin('authopenid/changeemail.html', data, request) else: send_new_email_key(request.user) return validation_email_sent(request) else: raise Http404
def retag_question(request, id): """retag question view """ question = get_object_or_404(models.Question, id=id) try: request.user.assert_can_retag_question(question) if request.method == "POST": form = forms.RetagQuestionForm(question, request.POST) if form.is_valid(): if form.has_changed(): request.user.retag_question(question=question, tags=form.cleaned_data["tags"]) if request.is_ajax(): response_data = {"success": True, "new_tags": question.tagnames} data = simplejson.dumps(response_data) return HttpResponse(data, mimetype="application/json") else: return HttpResponseRedirect(question.get_absolute_url()) elif request.is_ajax(): response_data = {"message": unicode(form.errors["tags"]), "success": False} data = simplejson.dumps(response_data) return HttpResponse(data, mimetype="application/json") else: form = forms.RetagQuestionForm(question) data = {"active_tab": "questions", "question": question, "form": form} return render_into_skin("question_retag.html", data, request) except exceptions.PermissionDenied, e: if request.is_ajax(): response_data = {"message": unicode(e), "success": False} data = simplejson.dumps(response_data) return HttpResponse(data, mimetype="application/json") else: request.user.message_set.create(message=unicode(e)) return HttpResponseRedirect(question.get_absolute_url())
def reopen(request, id):#re-open question """view to initiate and process question close this is not an ajax view """ question = get_object_or_404(models.Post, post_type='question', id=id) # open question try: if request.method == 'POST' : request.user.reopen_question(question) return HttpResponseRedirect(question.get_absolute_url()) else: request.user.assert_can_reopen_question(question) closed_by_profile_url = question.thread.closed_by.get_profile_url() closed_by_username = question.thread.closed_by.username data = { 'question' : question, 'closed_by_profile_url': closed_by_profile_url, 'closed_by_username': closed_by_username, } return render_into_skin('reopen.html', data, request) except exceptions.PermissionDenied, e: request.user.message_set.create(message = unicode(e)) return HttpResponseRedirect(question.get_absolute_url())
def close(request, id):#close question """view to initiate and process question close """ question = get_object_or_404(models.Post, post_type='question', id=id) try: if request.method == 'POST': form = forms.CloseForm(request.POST) if form.is_valid(): reason = form.cleaned_data['reason'] request.user.close_question( question = question, reason = reason ) return HttpResponseRedirect(question.get_absolute_url()) else: request.user.assert_can_close_question(question) form = forms.CloseForm() data = { 'question': question, 'form': form, } return render_into_skin('close.html', data, request) except exceptions.PermissionDenied, e: request.user.message_set.create(message = unicode(e)) return HttpResponseRedirect(question.get_absolute_url())
def about(request, template='about.html'): title = _('About %(site)s') % {'site': askbot_settings.APP_SHORT_NAME} data = { 'title': title, 'content': askbot_settings.FORUM_ABOUT } return render_into_skin('static_page.html', data, request)
def user_reputation(request, user): reputes = models.Repute.objects.filter(user=user).order_by("-reputed_at") # select_related() adds stuff needed for the query reputes = reputes.select_related("question__title", "question__id", "user__username") # prepare data for the graph rep_list = [] # last values go in first rep_list.append("[%s,%s]" % (calendar.timegm(datetime.datetime.now().timetuple()) * 1000, user.reputation)) # ret remaining values in for rep in reputes: dic = "[%s,%s]" % (calendar.timegm(rep.reputed_at.timetuple()) * 1000, rep.reputation) rep_list.append(dic) reps = ",".join(rep_list) reps = "[%s]" % reps data = { "active_tab": "users", "page_class": "user-profile-page", "tab_name": "reputation", "tab_description": _("user reputation in the community"), "page_title": _("profile - user reputation"), "view_user": user, "reputation": reputes, "reps": reps, } return render_into_skin("user_profile/user_reputation.html", data, request)
def user_votes(request, user, context): all_votes = list(models.Vote.objects.filter(user=user)) votes = [] for vote in all_votes: post = vote.voted_post if post.is_question(): vote.title = post.thread.title vote.question_id = post.id vote.answer_id = 0 votes.append(vote) elif post.is_answer(): vote.title = post.thread.title vote.question_id = post.thread._question_post().id vote.answer_id = post.id votes.append(vote) votes.sort(key=operator.attrgetter("id"), reverse=True) data = { "active_tab": "users", "page_class": "user-profile-page", "tab_name": "votes", "tab_description": _("user vote record"), "page_title": _("profile - votes"), "votes": votes[: const.USER_VIEW_DATA_SIZE], } context.update(data) return render_into_skin("user_profile/user_votes.html", context, request)
def user_favorites(request, user, context): favorited_q_id_list = models.FavoriteQuestion.objects.filter(user=user).values_list("question__id", flat=True) questions = ( models.Question.objects.filter(id__in=favorited_q_id_list) .order_by("-score", "-last_activity_at") .select_related( "last_activity_by__id", "last_activity_by__username", "last_activity_by__reputation", "last_activity_by__gold", "last_activity_by__silver", "last_activity_by__bronze", )[: const.USER_VIEW_DATA_SIZE] ) data = { "active_tab": "users", "page_class": "user-profile-page", "tab_name": "favorites", "tab_description": _("users favorite questions"), "page_title": _("profile - favorite questions"), "questions": questions, "favorited_myself": favorited_q_id_list, } context.update(data) return render_into_skin("user_profile/user_favorites.html", context, request)
def subscribe_for_tags(request): """process subscription of users by tags""" #todo - use special separator to split tags tag_names = request.REQUEST.get('tags','').strip().split() pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names) if request.user.is_authenticated(): if request.method == 'POST': if 'ok' in request.POST: request.user.mark_tags( pure_tag_names, wildcards, reason = 'good', action = 'add' ) request.user.message_set.create( message = _('Your tag subscription was saved, thanks!') ) else: message = _( 'Tag subscription was canceled (<a href="%(url)s">undo</a>).' ) % {'url': request.path + '?tags=' + request.REQUEST['tags']} request.user.message_set.create(message = message) return HttpResponseRedirect(reverse('index')) else: data = {'tags': tag_names} return render_into_skin('subscribe_for_tags.html', data, request) else: all_tag_names = pure_tag_names + wildcards message = _('Please sign in to subscribe for: %(tags)s') \ % {'tags': ', '.join(all_tag_names)} request.user.message_set.create(message = message) request.session['subscribe_for_tags'] = (pure_tag_names, wildcards) return HttpResponseRedirect(url_utils.get_login_url())
def user_votes(request, user, context): all_votes = list(models.Vote.objects.filter(user=user)) votes = [] for vote in all_votes: post = vote.voted_post if post.is_question(): vote.title = post.thread.title vote.question_id = post.id vote.answer_id = 0 votes.append(vote) elif post.is_answer(): vote.title = post.thread.title vote.question_id = post.thread._question_post().id vote.answer_id = post.id votes.append(vote) votes.sort(key=operator.attrgetter('id'), reverse=True) data = { 'active_tab':'users', 'page_class': 'user-profile-page', 'tab_name' : 'votes', 'tab_description' : _('user vote record'), 'page_title' : _('profile - votes'), 'votes' : votes[:const.USER_VIEW_DATA_SIZE] } context.update(data) return render_into_skin('user_profile/user_votes.html', context, request)
def exercise_widget(request, widget_id): """Returns the first x exercises based on certain tags. @returns template with those exercises listed.""" # make sure this is a GET request with the correct parameters. widget = get_object_or_404(models.ExerciseWidget, pk=widget_id) if request.method != 'GET': raise Http404 filter_params = {} if widget.tagnames: filter_params['tags__name__in'] = widget.tagnames.split(' ') if widget.group: filter_params['groups'] = widget.group #simple title search for now if widget.search_query: filter_params['title__icontains'] = widget.search_query if filter_params: threads = models.Thread.objects.filter(**filter_params).order_by(widget.order_by)[:widget.exercise_number] else: threads = models.Thread.objects.all().order_by(widget.order_by)[:widget.exercise_number] data = { 'threads': threads, 'widget': widget } return render_into_skin('embed/exercise_widget.html', data, request)
def widgets(request): data = { 'ask_widgets': models.AskWidget.objects.all().count(), 'exercise_widgets': models.ExerciseWidget.objects.all().count(), 'page_class': 'widgets' } return render_into_skin('embed/widgets.html', data, request)
def user_votes(request, user, context): all_votes = list(models.Vote.objects.filter(user=user)) votes = [] for vote in all_votes: post = vote.voted_post if post.is_question(): vote.title = post.thread.title vote.question_id = post.id vote.answer_id = 0 votes.append(vote) elif post.is_answer(): vote.title = post.thread.title vote.question_id = post.thread._question_post().id vote.answer_id = post.id votes.append(vote) votes.sort(key=operator.attrgetter('id'), reverse=True) data = { 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_name': 'votes', 'tab_description': _('user vote record'), 'page_title': _('profile - votes'), 'votes': votes[:const.USER_VIEW_DATA_SIZE] } context.update(data) return render_into_skin('user_profile/user_votes.html', context, request)
def subscribe_for_tags(request): """process subscription of users by tags""" # todo - use special separator to split tags tag_names = request.REQUEST.get("tags", "").strip().split() pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names) if request.user.is_authenticated(): if request.method == "POST": if "ok" in request.POST: request.user.mark_tags(pure_tag_names, wildcards, reason="good", action="add") request.user.message_set.create(message=_("Your tag subscription was saved, thanks!")) else: message = _('Tag subscription was canceled (<a href="%(url)s">undo</a>).') % { "url": request.path + "?tags=" + request.REQUEST["tags"] } request.user.message_set.create(message=message) return HttpResponseRedirect(reverse("index")) else: data = {"tags": tag_names} return render_into_skin("subscribe_for_tags.html", data, request) else: all_tag_names = pure_tag_names + wildcards message = _("Please sign in to subscribe for: %(tags)s") % {"tags": ", ".join(all_tag_names)} request.user.message_set.create(message=message) request.session["subscribe_for_tags"] = (pure_tag_names, wildcards) return HttpResponseRedirect(url_utils.get_login_url())
def show_group_join_requests(request, user, context): """show group join requests to admins who belong to the group""" if request.user.is_administrator_or_moderator() is False: raise Http404 #get group to which user belongs groups = request.user.get_groups() #construct a dictionary group id --> group object #to avoid loading group via activity content object groups_dict = dict([(group.id, group) for group in groups]) #get join requests for those groups group_content_type = ContentType.objects.get_for_model(models.Group) join_requests = models.Activity.objects.filter( activity_type=const.TYPE_ACTIVITY_ASK_TO_JOIN_GROUP, content_type=group_content_type, object_id__in=groups_dict.keys() ).order_by('-active_at') data = { 'active_tab':'users', 'page_class': 'user-profile-page', 'tab_name' : 'join_requests', 'tab_description' : _('group joining requests'), 'page_title' : _('profile - moderation'), 'groups_dict': groups_dict, 'join_requests': join_requests } context.update(data) return render_into_skin('user_inbox/group_join_requests.html', context, request)
def user_favorites(request, user, context): favorited_q_id_list= models.FavoriteQuestion.objects.filter( user = user ).values_list('question__id', flat=True) questions = models.Question.objects.filter( id__in=favorited_q_id_list ).order_by( '-score', '-last_activity_at' ).select_related( 'last_activity_by__id', 'last_activity_by__username', 'last_activity_by__reputation', 'last_activity_by__gold', 'last_activity_by__silver', 'last_activity_by__bronze' )[:const.USER_VIEW_DATA_SIZE] data = { 'active_tab':'users', 'page_class': 'user-profile-page', 'tab_name' : 'favorites', 'tab_description' : _('users favorite questions'), 'page_title' : _('profile - favorite questions'), 'questions' : questions, 'favorited_myself': favorited_q_id_list, } context.update(data) return render_into_skin('user_profile/user_favorites.html', context, request)
def user_reputation(request, user, context): reputes = ( models.Repute.objects.filter(user=user) .select_related("question", "question__thread", "user") .order_by("-reputed_at") ) # prepare data for the graph - last values go in first rep_list = ["[%s,%s]" % (calendar.timegm(datetime.datetime.now().timetuple()) * 1000, user.reputation)] for rep in reputes: rep_list.append("[%s,%s]" % (calendar.timegm(rep.reputed_at.timetuple()) * 1000, rep.reputation)) reps = ",".join(rep_list) reps = "[%s]" % reps data = { "active_tab": "users", "page_class": "user-profile-page", "tab_name": "reputation", "tab_description": _("user reputation in the community"), "page_title": _("profile - user reputation"), "reputation": reputes, "reps": reps, } context.update(data) return render_into_skin("user_profile/user_reputation.html", context, request)
def list_widgets(request, model): model_class = _get_model(model) widgets = model_class.objects.all() data = { 'widgets': widgets, 'widget_name': model } return render_into_skin('embed/list_widgets.html', data, request)
def about(request, template='about.html'): title = _('About %(site)s') % {'site': askbot_settings.APP_SHORT_NAME} data = { 'title': title, 'page_class': 'meta', 'content': askbot_settings.FORUM_ABOUT } return render_into_skin('static_page.html', data, request)
def faq(request): data = { 'gravatar_faq_url': reverse('faq') + '#gravatar', #'send_email_key_url': reverse('send_email_key'), 'ask_question_url': reverse('ask'), 'page_class': 'meta', } return render_into_skin('faq.html', data, request)
def users(request): is_paginated = True sortby = request.GET.get('sort', 'reputation') suser = request.REQUEST.get('query', "") try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 if suser == "": if sortby == "newest": order_by_parameter = '-date_joined' elif sortby == "last": order_by_parameter = 'date_joined' elif sortby == "user": order_by_parameter = 'username' else: # default order_by_parameter = '-reputation' objects_list = Paginator( models.User.objects.all().order_by(order_by_parameter), const.USERS_PAGE_SIZE) base_url = reverse('users') + '?sort=%s&' % sortby else: sortby = "reputation" objects_list = Paginator( models.User.objects.filter( username__icontains=suser).order_by('-reputation'), const.USERS_PAGE_SIZE) base_url = reverse('users') + '?name=%s&sort=%s&' % (suser, sortby) try: users_page = objects_list.page(page) except (EmptyPage, InvalidPage): users_page = objects_list.page(objects_list.num_pages) paginator_data = { 'is_paginated': is_paginated, 'pages': objects_list.num_pages, 'page': page, 'has_previous': users_page.has_previous(), 'has_next': users_page.has_next(), 'previous': users_page.previous_page_number(), 'next': users_page.next_page_number(), 'base_url': base_url } paginator_context = extra_tags.cnprog_paginator(paginator_data) data = { 'active_tab': 'users', 'page_class': 'users-page', 'users': users_page, 'suser': suser, 'keywords': suser, 'tab_id': sortby, 'paginator_context': paginator_context } return render_into_skin('users.html', data, request)
def delete_widget(request, model, widget_id): model_class = _get_model(model) widget = get_object_or_404(model_class, pk=widget_id) if request.method == "POST": widget.delete() return redirect('list_widgets', model=model) else: return render_into_skin('embed/delete_widget.html', {'widget': widget, 'widget_name': model}, request)
def faq(request): if askbot_settings.FORUM_FAQ.strip() != '': data = { 'title': _('FAQ'), 'content': askbot_settings.FORUM_FAQ, 'page_class': 'meta', } return render_into_skin( 'static_page.html', data, request ) else: data = { 'gravatar_faq_url': reverse('faq') + '#gravatar', 'ask_question_url': reverse('ask'), 'page_class': 'meta', } return render_into_skin('faq_static.html', data, request)
def user_network(request, user, context): if 'followit' not in django_settings.INSTALLED_APPS: raise Http404 data = { 'tab_name': 'network', 'followed_users': user.get_followed_users(), 'followers': user.get_followers(), } context.update(data) return render_into_skin('user_profile/user_network.html', context, request)
def groups(request, id=None, slug=None): """output groups page """ if askbot_settings.GROUPS_ENABLED == False: raise Http404 groups = models.Tag.group_tags.get_all() can_edit = request.user.is_authenticated() and \ request.user.is_administrator_or_moderator() data = {'groups': groups, 'can_edit': can_edit, 'active_tab': 'users'} return render_into_skin('groups.html', data, request)
def edit_answer(request, id): answer = get_object_or_404(models.Answer, id=id) try: request.user.assert_can_edit_answer(answer) latest_revision = answer.get_latest_revision() if request.method == "POST": if 'select_revision' in request.POST: # user has changed revistion number revision_form = forms.RevisionForm( answer, latest_revision, request.POST ) if revision_form.is_valid(): # Replace with those from the selected revision rev = revision_form.cleaned_data['revision'] selected_revision = models.AnswerRevision.objects.get( answer = answer, revision = rev ) form = forms.EditAnswerForm(answer, selected_revision) else: form = forms.EditAnswerForm( answer, latest_revision, request.POST ) else: form = forms.EditAnswerForm(answer, latest_revision, request.POST) revision_form = forms.RevisionForm(answer, latest_revision) if form.is_valid(): if form.has_changed(): request.user.edit_answer( answer = answer, body_text = form.cleaned_data['text'], revision_comment = form.cleaned_data['summary'], wiki = form.cleaned_data.get('wiki', answer.wiki), #todo: add wiki field to form ) return HttpResponseRedirect(answer.get_absolute_url()) else: revision_form = forms.RevisionForm(answer, latest_revision) form = forms.EditAnswerForm(answer, latest_revision) data = { 'active_tab': 'questions', 'answer': answer, 'revision_form': revision_form, 'form': form, } return render_into_skin('answer_edit.html', data, request) except exceptions.PermissionDenied, e: request.user.message_set.create(message = unicode(e)) return HttpResponseRedirect(answer.get_absolute_url())
def validation_email_sent(request): """this function is called only if EMAIL_VALIDATION setting is set to True bolean value, basically dead now""" assert (askbot_settings.EMAIL_VALIDATION == True) logging.debug('') data = { 'email': request.user.email, 'change_email_url': reverse('user_changeemail'), 'action_type': 'validate' } return render_into_skin('authopenid/changeemail.html', data, request)
def tags(request): #view showing a listing of available tags - plain list stag = "" is_paginated = True sortby = request.GET.get('sort', 'used') try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 if request.method == "GET": stag = request.GET.get("query", "").strip() if stag != '': objects_list = Paginator( models.Tag.objects.filter( deleted=False, name__icontains=stag).exclude(used_count=0), DEFAULT_PAGE_SIZE) else: if sortby == "name": objects_list = Paginator( models.Tag.objects.all().filter(deleted=False).exclude( used_count=0).order_by("name"), DEFAULT_PAGE_SIZE) else: objects_list = Paginator( models.Tag.objects.all().filter(deleted=False).exclude( used_count=0).order_by("-used_count"), DEFAULT_PAGE_SIZE) try: tags = objects_list.page(page) except (EmptyPage, InvalidPage): tags = objects_list.page(objects_list.num_pages) paginator_data = { 'is_paginated': is_paginated, 'pages': objects_list.num_pages, 'page': page, 'has_previous': tags.has_previous(), 'has_next': tags.has_next(), 'previous': tags.previous_page_number(), 'next': tags.next_page_number(), 'base_url': reverse('tags') + '?sort=%s&' % sortby } paginator_context = extra_tags.cnprog_paginator(paginator_data) data = { 'active_tab': 'tags', 'page_class': 'tags-page', 'tags': tags, 'stag': stag, 'tab_id': sortby, 'keywords': stag, 'paginator_context': paginator_context } return render_into_skin('tags.html', data, request)
def retag_question(request, id): """retag question view """ question = get_object_or_404(models.Post, id=id) try: request.user.assert_can_retag_question(question) if request.method == 'POST': form = forms.RetagQuestionForm(question, request.POST) if form.is_valid(): if form.has_changed(): request.user.retag_question(question=question, tags=form.cleaned_data['tags']) if request.is_ajax(): response_data = { 'success': True, 'new_tags': question.thread.tagnames } if request.user.message_set.count() > 0: #todo: here we will possibly junk messages message = request.user.get_and_delete_messages()[-1] response_data['message'] = message data = simplejson.dumps(response_data) return HttpResponse(data, mimetype="application/json") else: return HttpResponseRedirect(question.get_absolute_url()) elif request.is_ajax(): response_data = { 'message': format_errors(form.errors['tags']), 'success': False } data = simplejson.dumps(response_data) return HttpResponse(data, mimetype="application/json") else: form = forms.RetagQuestionForm(question) data = { 'active_tab': 'questions', 'question': question, 'form': form, } return render_into_skin('question_retag.html', data, request) except exceptions.PermissionDenied, e: if request.is_ajax(): response_data = {'message': unicode(e), 'success': False} data = simplejson.dumps(response_data) return HttpResponse(data, mimetype="application/json") else: request.user.message_set.create(message=unicode(e)) return HttpResponseRedirect(question.get_absolute_url())
def edit_solution(request, id): solution = get_object_or_404(models.Post, id=id) revision = solution.get_latest_revision() try: request.user.assert_can_edit_solution(solution) if request.method == "POST": if request.POST['select_revision'] == 'true': # user has changed revistion number revision_form = forms.RevisionForm(solution, revision, request.POST) if revision_form.is_valid(): # Replace with those from the selected revision rev = revision_form.cleaned_data['revision'] revision = solution.revisions.get(revision=rev) form = forms.EditProblemForm(solution, revision) else: form = forms.EditProblemForm(solution, revision, request.POST) else: form = forms.EditProblemForm(solution, revision, request.POST) revision_form = forms.RevisionForm(solution, revision) if form.is_valid(): if form.has_changed(): user = form.get_post_user(request.user) user.edit_solution( solution=solution, body_text=form.cleaned_data['text'], revision_comment=form.cleaned_data['summary'], wiki=form.cleaned_data.get('wiki', solution.wiki), is_private=form.cleaned_data.get( 'is_private', False) #todo: add wiki field to form ) return HttpResponseRedirect(solution.get_absolute_url()) else: revision_form = forms.RevisionForm(solution, revision) form = forms.EditProblemForm(solution, revision) if request.user.can_make_group_private_posts(): form.initial['post_privately'] = solution.is_private() data = { 'page_class': 'edit-problem-page', 'active_tab': 'exercises', 'solution': solution, 'revision': revision, 'revision_form': revision_form, 'form': form, } return render_into_skin('solution_edit.html', data, request) except exceptions.PermissionDenied, e: request.user.message_set.create(message=unicode(e)) return HttpResponseRedirect(solution.get_absolute_url())
def ask_widget_complete(request): exercise_url = request.session.get('widget_exercise_url') custom_css = request.session.get('widget_css') if exercise_url: del request.session['widget_exercise_url'] else: exercise_url = '#' if custom_css: del request.session['widget_css'] data = {'exercise_url': exercise_url, 'custom_css': custom_css} return render_into_skin('embed/ask_widget_complete.html', data, request)
def cats(request): """ View that renders a simple page showing the categories tree widget. It uses JSON to send tree data in the context to the client. """ if askbot_settings.ENABLE_CATEGORIES: return render_into_skin( 'categories.html', {'cats_tree':simplejson.dumps(generate_tree())}, request ) else: raise Http404
def logout(request): #refactor/change behavior? #currently you click logout and you get #to this view which actually asks you again - do you really want to log out? #I guess rationale was to tell the user that s/he may be still logged in #through their external login sytem and we'd want to remind them about it #however it might be a little annoying #why not just show a message: you are logged out of forum, but #if you really want to log out -> go to your openid provider data = { 'next': get_next_url(request), 'page_class': 'meta', } return render_into_skin('logout.html', data, request)
def user_email_subscriptions(request, user, context): logging.debug(get_request_info(request)) if request.method == 'POST': email_feeds_form = forms.EditUserEmailFeedsForm(request.POST) tag_filter_form = forms.TagFilterSelectionForm(request.POST, instance=user) if email_feeds_form.is_valid() and tag_filter_form.is_valid(): action_status = None tag_filter_saved = tag_filter_form.save() if tag_filter_saved: action_status = _('changes saved') if 'save' in request.POST: feeds_saved = email_feeds_form.save(user) if feeds_saved: action_status = _('changes saved') elif 'stop_email' in request.POST: email_stopped = email_feeds_form.reset().save(user) initial_values = forms.EditUserEmailFeedsForm.NO_EMAIL_INITIAL email_feeds_form = forms.EditUserEmailFeedsForm(initial=initial_values) if email_stopped: action_status = _('email updates canceled') else: #user may have been created by some app that does not know #about the email subscriptions, in that case the call below #will add any subscription settings that are missing #using the default frequencies user.add_missing_askbot_subscriptions() #initialize the form email_feeds_form = forms.EditUserEmailFeedsForm() email_feeds_form.set_initial_values(user) tag_filter_form = forms.TagFilterSelectionForm(instance=user) action_status = None data = { 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_name': 'email_subscriptions', 'tab_description': _('email subscription settings'), 'page_title': _('profile - email subscriptions'), 'email_feeds_form': email_feeds_form, 'tag_filter_selection_form': tag_filter_form, 'action_status': action_status, } context.update(data) return render_into_skin( 'user_profile/user_email_subscriptions.html', context, request )
def edit_user(request, id): """View that allows to edit user profile. This view is accessible to profile owners or site administrators """ user = get_object_or_404(models.User, id=id) if not(request.user == user or request.user.is_superuser): raise Http404 if request.method == "POST": form = forms.EditUserForm(user, request.POST) if form.is_valid(): new_email = sanitize_html(form.cleaned_data['email']) set_new_email(user, new_email) if askbot_settings.EDITABLE_SCREEN_NAME: new_username = sanitize_html(form.cleaned_data['username']) if user.username != new_username: group = user.get_personal_group() user.username = new_username group.name = format_personal_group_name(user) group.save() user.real_name = sanitize_html(form.cleaned_data['realname']) user.website = sanitize_html(form.cleaned_data['website']) user.location = sanitize_html(form.cleaned_data['city']) user.date_of_birth = form.cleaned_data.get('birthday', None) user.about = sanitize_html(form.cleaned_data['about']) user.country = form.cleaned_data['country'] user.show_country = form.cleaned_data['show_country'] user.show_marked_tags = form.cleaned_data['show_marked_tags'] user.save() # send user updated signal if full fields have been updated award_badges_signal.send(None, event = 'update_user_profile', actor = user, context_object = user ) return HttpResponseRedirect(user.get_profile_url()) else: form = forms.EditUserForm(user) data = { 'active_tab': 'users', 'page_class': 'user-profile-edit-page', 'form' : form, 'marked_tags_setting': askbot_settings.MARKED_TAGS_ARE_PUBLIC_WHEN, 'support_custom_avatars': ('avatar' in django_settings.INSTALLED_APPS), 'view_user': user, } return render_into_skin('user_profile/user_edit.html', data, request)
def badge(request, id): #todo: supplement database data with the stuff from badges.py badge = get_object_or_404(BadgeData, id=id) badge_recipients = User.objects.filter(award_user__badge=badge).annotate( last_awarded_at=Max('award_user__awarded_at'), award_count=Count('award_user')).order_by('-last_awarded_at') data = { 'active_tab': 'badges', 'badge_recipients': badge_recipients, 'badge': badge, 'page_class': 'meta', } return render_into_skin('badge.html', data, request)