def feedback(request): data = {'page_class': 'meta'} form = None if openode_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 HttpResponseRedirect(get_next_url(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 category_edit(request, node_id, node_slug, category_id): """ edit ThreadCategory recently used only for structuring Document Threads, so is called Directory """ node = get_object_or_404(Node, pk=node_id) try: category = node.thread_categories.get(pk=category_id) except ObjectDoesNotExist: raise Http404 if not category.has_update_perm(request.user): return render_forbidden(request) if request.method == "POST": form = EditThreadCategoryForm(request.POST, instance=category) if form.is_valid(): form.save() request.user.log(category, const.LOG_ACTION_THREAD_CATEGORY_EDIT) return HttpResponseRedirect( reverse("node_module", args=[node.pk, node.slug, "library"])) else: form = EditThreadCategoryForm(instance=category) to_tmpl = { "node": node, "form": form, "directory": category, } return render_into_skin('node/document/edit_directory.html', to_tmpl, request)
def question_flow_new(request, profile_owner, context): if not request.user.has_perm('can_solve_question_flow', None): return render_forbidden(request) if request.method == "POST": # raw_node = request.GET.get(node) # if raw_node and str(raw_node).isdigit(): question_pk = request.POST.get("question") if question_pk and question_pk.isdigit(): question = get_object_or_404(Thread, pk=int(question_pk)) form = QuestionFlowNodeResponsibleUsersForm(request.POST, question=question) if form.is_valid(): question.question_flow_interviewee_user = form.cleaned_data[form.get_responsible_users_field_name()] question.question_flow_responsible_user = request.user question.question_flow_state = const.QUESTION_FLOW_STATE_SUBMITTED question.save() return HttpResponseRedirect(request.path) context.update({ 'view_user': request.user, "get_qf_form": lambda question: QuestionFlowNodeResponsibleUsersForm(question=question), "page_title": _("question flow new"), }) return render_into_skin('user_profile/question_flow_new.html', context, request)
def feedback(request): data = {'page_class': 'meta'} form = None if openode_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 HttpResponseRedirect(get_next_url(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 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 category_add(request, node_id, node_slug): """ add ThreadCategory recently used only for structuring Document Threads, so is called Directory """ node = get_object_or_404(Node, pk=node_id) if not request.user.has_openode_perm("document_directory_create", node): return render_forbidden(request) if request.method == "POST": form = AddThreadCategoryForm(request.POST, node=node) if form.is_valid(): thread_category = form.save() request.user.log(thread_category, const.LOG_ACTION_ADD_THREAD_CATEGORY) return HttpResponseRedirect(reverse("node_module", args=[node.pk, node.slug, "library"])) else: form = AddThreadCategoryForm(node=node, initial={"node": node}) to_tmpl = { "node": node, "form": form, "directory": None, } return render_into_skin('node/document/edit_directory.html', to_tmpl, 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 category_edit(request, node_id, node_slug, category_id): """ edit ThreadCategory recently used only for structuring Document Threads, so is called Directory """ node = get_object_or_404(Node, pk=node_id) try: category = node.thread_categories.get(pk=category_id) except ObjectDoesNotExist: raise Http404 if not category.has_update_perm(request.user): return render_forbidden(request) if request.method == "POST": form = EditThreadCategoryForm(request.POST, instance=category) if form.is_valid(): form.save() request.user.log(category, const.LOG_ACTION_THREAD_CATEGORY_EDIT) return HttpResponseRedirect(reverse("node_module", args=[node.pk, node.slug, "library"])) else: form = EditThreadCategoryForm(instance=category) to_tmpl = { "node": node, "form": form, "directory": category, } return render_into_skin('node/document/edit_directory.html', to_tmpl, request)
def user_followed_questions(request, user, context): if not request.user.has_user_perm('can_see_followed_threads', user): return render_forbidden(request) user.user_followed_threads.values_list('thread', flat=True) questions = models.Post.objects.filter( post_type='question', thread__in=user.user_followed_threads.values_list('thread', flat=True) # followed_threads ).select_related( 'thread', 'thread__last_activity_by' ).order_by( '-points', '-thread__last_activity_at' )[:const.USER_VIEW_DATA_SIZE] context.update({ 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_description': _('users followed questions'), 'page_title': _('profile - followed questions'), 'questions': questions, 'view_user': user }) return render_into_skin('user_profile/user_followed_questions.html', context, request)
def category_move(request, node_id, node_slug, category_id): node = get_object_or_404(Node, pk=node_id) try: category = node.thread_categories.get(pk=category_id) except ThreadCategory.DoesNotExist: raise Http404 if request.method == "POST": form = CategoryMoveForm(request.POST, instance=category) if form.is_valid(): form.save() request.user.log(category, const.LOG_ACTION_THREAD_CATEGORY_MOVE) return HttpResponseRedirect( reverse("category_reorg", args=[node.pk, node.slug])) else: form = CategoryMoveForm(instance=category) to_tmpl = { "categories": node.thread_categories.filter(level=0), "category": category, 'form': form, } return render_into_skin('node/document/move_directory.html', to_tmpl, request)
def category_add(request, node_id, node_slug): """ add ThreadCategory recently used only for structuring Document Threads, so is called Directory """ node = get_object_or_404(Node, pk=node_id) if not request.user.has_openode_perm("document_directory_create", node): return render_forbidden(request) if request.method == "POST": form = AddThreadCategoryForm(request.POST, node=node) if form.is_valid(): thread_category = form.save() request.user.log(thread_category, const.LOG_ACTION_ADD_THREAD_CATEGORY) return HttpResponseRedirect( reverse("node_module", args=[node.pk, node.slug, "library"])) else: form = AddThreadCategoryForm(node=node, initial={"node": node}) to_tmpl = { "node": node, "form": form, "directory": None, } return render_into_skin('node/document/edit_directory.html', to_tmpl, request)
def create_response(self): """ Generates the actual HttpResponse to send back to the user. """ def tags_reduce_fx(all_pks, pk): """ clean function to template """ ret = list(all_pks) ret.remove(pk) return "+".join([str(i) for i in ret]) (paginator, page) = self.build_page() ############################### others_tags_ids = set() for res in page.object_list: if not res.tags_data: continue for tag_data in res.tags_data: others_tags_ids.add(tag_data[0]) tags_pks = set([tag.pk for tag in self.selected_tags]) if tags_pks: other_tags = Tag.objects.valid_tags().filter( pk__in=set(others_tags_ids - tags_pks)) else: other_tags = Tag.objects.valid_tags().order_by("-used_count") ############################### search_in_query = "" if self.form["search_in"].data: search_in_query = "&".join( ["search_in=%s" % i for i in self.form["search_in"].data]) context = { "search_in_query": search_in_query, 'query': self.query, 'form': self.form, 'page': page, 'paginator': paginator, 'suggestion': None, "other_tags": other_tags, "selected_tags": self.selected_tags, "tags_query": "+".join([str(tag.pk) for tag in self.selected_tags]), "tags_pks": tags_pks, "tags_reduce_fx": tags_reduce_fx, "show_results": bool(self.selected_tags or self.query) } if self.results and hasattr( self.results, 'query') and self.results.query.backend.include_spelling: context['suggestion'] = self.form.get_suggestion() context.update(self.extra_context()) return render_into_skin(self.template, context, self.request)
def tag_detail(request, tag_id): tag = get_object_or_404(Tag, pk=tag_id) threads = Thread.objects.filter(tags__in=[tag]) data = {'tag': tag, 'threads': threads} return render_into_skin('tag_detail.html', data, request)
def node_annotation_edit(request, node_id, node_slug): """ Node Annotation Edit """ node = get_object_or_404(Node, pk=node_id) if node.slug != node_slug: return HttpResponseRedirect( reverse('node_annotation_edit', kwargs={ 'node_id': node_id, 'node_slug': node.slug })) if not request.user.has_openode_perm('node_edit_annotation', node): return render_forbidden(request) text = getattr(node.description, "text", u"") data = {"text": text} if text else None if request.method == "POST": data = MergeDict(request.POST, data) form = NodeAnnotationEditForm(data=data, node=node) if form.is_valid(): text = form.cleaned_data["text"] # edit if node.description: node.description.apply_edit(edited_by=request.user, text=text) # create new one else: post = Post.objects.create_new( thread=None, author=request.user, added_at=datetime.now(), text=text, post_type="node_description", ) post.save() node.description = post node.save() request.user.message_set.create( message=_('Node annotation has been succesfully saved.')) return HttpResponseRedirect( reverse('node_annotation_edit', args=[node.pk, node.slug])) else: form = NodeAnnotationEditForm(data=data, node=node) template_data = { 'node': node, 'form': form, 'page_class': 'node-edit', } return render_into_skin('node/annotation/edit.html', template_data, request)
def user_logs(request, user, context): if request.user != user and not request.user.has_perm('openode.view_other_user_log'): return render_forbidden(request) data = { 'logs': user.logs.all().order_by('-action_time')[:50] } context.update(data) return render_into_skin('user_profile/user_logs.html', context, request)
def question_flow_to_publish(request, profile_owner, context): if not request.user.has_perm('can_solve_question_flow', None): return render_forbidden(request) context.update({ 'view_user': request.user, "page_title": _("question flow new"), }) return render_into_skin('user_profile/question_flow_to_check.html', context, request)
def create_response(self): """ Generates the actual HttpResponse to send back to the user. """ def tags_reduce_fx(all_pks, pk): """ clean function to template """ ret = list(all_pks) ret.remove(pk) return "+".join([str(i) for i in ret]) (paginator, page) = self.build_page() ############################### others_tags_ids = set() for res in page.object_list: if not res.tags_data: continue for tag_data in res.tags_data: others_tags_ids.add(tag_data[0]) tags_pks = set([tag.pk for tag in self.selected_tags]) if tags_pks: other_tags = Tag.objects.valid_tags().filter(pk__in=set(others_tags_ids - tags_pks)) else: other_tags = Tag.objects.valid_tags().order_by("-used_count") ############################### search_in_query = "" if self.form["search_in"].data: search_in_query = "&".join(["search_in=%s" % i for i in self.form["search_in"].data]) context = { "search_in_query": search_in_query, 'query': self.query, 'form': self.form, 'page': page, 'paginator': paginator, 'suggestion': None, "other_tags": other_tags, "selected_tags": self.selected_tags, "tags_query": "+".join([str(tag.pk) for tag in self.selected_tags]), "tags_pks": tags_pks, "tags_reduce_fx": tags_reduce_fx, "show_results": bool(self.selected_tags or self.query) } if self.results and hasattr(self.results, 'query') and self.results.query.backend.include_spelling: context['suggestion'] = self.form.get_suggestion() context.update(self.extra_context()) return render_into_skin(self.template, context, self.request)
def node_settings(request, node_id, node_slug): """ Node Settings """ node = get_object_or_404(Node, pk=node_id) if node.slug != node_slug: return HttpResponseRedirect( reverse('node_settings', kwargs={ 'node_id': node_id, 'node_slug': node.slug })) if not (request.user.is_admin('openode.change_node') or request.user.has_openode_perm('node_settings', node)): return render_forbidden(request) NodeUserInlineFormSet = inlineformset_factory(Node, NodeUser, form=NodeUserForm, extra=1) node_users = NodeUser.objects.filter(node=node).order_by( 'role', 'user__last_name', 'user__first_name') if request.method == "POST": form = NodeSettingsForm(instance=node, data=request.POST) formset = NodeUserInlineFormSet(request.POST, instance=node, queryset=node_users) form_is_valid = form.is_valid() formset_is_valid = formset.is_valid() if form_is_valid and formset_is_valid: form.save(user=request.user) formset.save() request.user.message_set.create( message=_('Node settings has been succesfully saved.')) return HttpResponseRedirect( reverse('node_settings', args=[node.pk, node.slug])) else: form = NodeSettingsForm(instance=node) formset = NodeUserInlineFormSet(instance=node, queryset=node_users) user_emails_by_role = SortedDict() for node_user in node_users: user_emails_by_role.setdefault(node_user.get_role_display(), []).append(node_user.user.email) template_data = { 'node': node, 'form': form, 'formset': formset, 'user_emails_by_role': user_emails_by_role, 'page_class': 'node-edit', } return render_into_skin('node/edit_settings.html', template_data, request)
def node_annotation_edit(request, node_id, node_slug): """ Node Annotation Edit """ node = get_object_or_404(Node, pk=node_id) if node.slug != node_slug: return HttpResponseRedirect(reverse('node_annotation_edit', kwargs={ 'node_id': node_id, 'node_slug': node.slug })) if not request.user.has_openode_perm('node_edit_annotation', node): return render_forbidden(request) text = getattr(node.description, "text", u"") data = {"text": text} if text else None if request.method == "POST": data = MergeDict(request.POST, data) form = NodeAnnotationEditForm(data=data, node=node) if form.is_valid(): text = form.cleaned_data["text"] # edit if node.description: node.description.apply_edit( edited_by=request.user, text=text ) # create new one else: post = Post.objects.create_new( thread=None, author=request.user, added_at=datetime.now(), text=text, post_type="node_description", ) post.save() node.description = post node.save() request.user.message_set.create(message=_('Node annotation has been succesfully saved.')) return HttpResponseRedirect(reverse('node_annotation_edit', args=[node.pk, node.slug])) else: form = NodeAnnotationEditForm(data=data, node=node) template_data = { 'node': node, 'form': form, 'page_class': 'node-edit', } return render_into_skin('node/annotation/edit.html', template_data, request)
def category_reorg(request, node_id, node_slug): node = get_object_or_404(Node, pk=node_id) if not request.user.has_openode_perm("document_directory_create", node): return render_forbidden(request) to_tmpl = { "categories": node.thread_categories.filter(level=0), "node": node } return render_into_skin('node/document/reorg_directory.html', to_tmpl, request)
def edit_answer(request, id): # TODO rename answer to post answer = get_object_or_404(models.Post, id=id) if not answer.has_edit_perm(request.user): return render_forbidden(request) revision = answer.get_latest_revision() try: request.user.assert_can_edit_answer(answer) if request.method == "POST": if request.POST['select_revision'] == 'true': # user has changed revistion number revision_form = forms.RevisionForm(answer, revision, request.POST) if revision_form.is_valid(): # Replace with those from the selected revision rev = revision_form.cleaned_data['revision'] revision = answer.revisions.get(revision=rev) form = forms.EditAnswerForm(answer, revision) else: form = forms.EditAnswerForm(answer, revision, request.POST) else: form = forms.EditAnswerForm(answer, revision, request.POST) revision_form = forms.RevisionForm(answer, revision) if form.is_valid(): if form.has_changed(): user = request.user user.edit_answer( answer=answer, body_text=form.cleaned_data['text'], revision_comment=form.cleaned_data['summary'], ) return HttpResponseRedirect(answer.get_absolute_url()) else: revision_form = forms.RevisionForm(answer, revision) form = forms.EditAnswerForm(answer, revision) data = { 'page_class': 'edit-answer-page', 'active_tab': 'questions', 'answer': answer, 'revision': revision, 'revision_form': revision_form, 'form': form, } return render_into_skin('node/%s/edit_post.html' % answer.thread.thread_type, data, request) except exceptions.PermissionDenied, e: request.user.message_set.create(message=unicode(e)) return HttpResponseRedirect(answer.get_absolute_url())
def tag_detail(request, tag_id): tag = get_object_or_404(Tag, pk=tag_id) threads = Thread.objects.filter(tags__in=[tag]) data = { 'tag': tag, 'threads': threads } return render_into_skin('tag_detail.html', data, request)
def user_email_subscriptions(request, user, context): logging.debug(get_request_info(request)) if request.method == 'POST': action_status = None 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(): 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_openode_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 if action_status: request.user.message_set.create(message=action_status) data = { 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_description': _('email subscription settings'), 'page_title': _('profile - email subscriptions'), 'email_feeds_form': email_feeds_form, 'tag_filter_selection_form': tag_filter_form, } context.update(data) return render_into_skin( 'user_profile/user_email_subscriptions.html', context, request )
def static_page(request, slug): """ static page detail page """ static_page = get_object_or_404( StaticPage, slug=slug, language=request.LANGUAGE_CODE ) to_tmpl = { "static_page": static_page } return render_into_skin('cms/static_page.html', to_tmpl, request)
def node_followers(request, node_id, node_slug): node = get_object_or_404(Node, pk=node_id) if node.slug != node_slug: return HttpResponseRedirect(reverse('node_followers', kwargs={ 'node_id': node_id, 'node_slug': node.slug })) data = { 'follows': node.node_following_users.order_by("-added_at"), 'node': node } return render_into_skin('node/followers.html', data, request)
def organization_requests(request, user, context): """show Unresolved Node join requests""" if not request.user.is_admin('openode.add_organization'): raise Http404 data = { 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_description': _('Organization requests'), 'page_title': _('profile - organization requests') } context.update(data) return render_into_skin('user_profile/organization_requests.html', context, request)
def user_node_join_requests(request, user, context): """show Unresolved Node join requests""" if not context['user_has_perm_resolve_node_joining']: raise Http404 data = { 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_description': _('node joining requests'), 'page_title': _('profile - node joins') } context.update(data) return render_into_skin('user_profile/node_join_requests.html', context, request)
def user_organization_join_requests(request, user, context): """show Unresolved Organization join requests""" if request.user.is_admin('openode.resolve_organization_joining') is False: raise Http404 data = { 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_description': _('organization joining requests'), 'page_title': _('profile - organization joins') } context.update(data) return render_into_skin('user_profile/organization_pending_memberships.html', context, request)
def node_module(request, node_id, node_slug, module, **kwargs): """ node detail modulu thread_type -> setup Thread.thread_type or summary """ # bypass for forum module if module == const.NODE_MODULE_FORUM: return node_module_forum(request, node_id, node_slug, module, **kwargs) node = get_object_or_404(Node, pk=node_id) if module in node.get_modules() and module not in [m[0] for m in node.get_modules()]: raise Http404() if node.slug != node_slug: return HttpResponseRedirect(reverse('node_module', kwargs={'node_id': node.pk, 'node_slug': node.slug, 'module': module})) if not request.user.has_openode_perm('node_read', node): if node.visibility == const.NODE_VISIBILITY_SEMIPRIVATE: return node_ask_to_join(request, node.pk, node.slug) return render_forbidden(request) if request.method != 'GET': return HttpResponseNotAllowed(['GET']) if module in const.THREAD_TYPE_BY_NODE_MODULE: return node_module_thread(request, node, module, **kwargs) template_file = NODE_MODULE_TEMPLATE_FILE[module] template_data = { 'node': node, 'module': module } if module == const.NODE_MODULE_ANNOTATION: try: page_no = int(request.GET.get("page", 1)) except ValueError: page_no = 1 end = LIVE_PER_PAGE * page_no start = end - LIVE_PER_PAGE template_data.update({ "live_threads": get_live_data(request.user, start, end, node), "page": page_no, "check_perm": check_perm }) return render_into_skin(template_file, template_data, request)
def node_ask_to_create(request): """ ask to create node There is no cancel option as user may create more than one request and there is no way to tell what request he wants to cancel. """ sent = False # was form successful, sent and without errors? if request.POST: form = AskToCreateNodeForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] note = form.cleaned_data['note'] summary = ugettext_noop( u'''%(user)s wants to create a new node %(node_name)s. Here is a note regarding the request: %(note)s''') % { 'user': request.user, 'node_name': name, 'note': note } data = simplejson.dumps({ 'user_name': request.user.screen_name, 'user_email': request.user.email, 'node_name': name, 'note': note }) # ugettext_noop(summary) # this will translate it after its pulled from db, not before. create_request, created = Activity.objects.get_or_create( user=request.user, activity_type=const.TYPE_ACTIVITY_ASK_TO_CREATE_NODE, # summary=summary, data=data) request.user.log(create_request, const.LOG_ACTION_ASK_TO_CREATE_NODE) sent = True else: form = AskToCreateNodeForm() to_tmpl = { 'sent': sent, 'form': form, } return render_into_skin("node/ask_to_create.html", to_tmpl, request)
def user_followed_nodes(request, user, context): if not request.user.has_user_perm('can_see_followed_nodes', user): return render_forbidden(request) followed_nodes = user.user_followed_nodes.all() data = { 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_description': _('users followed nodes'), 'page_title': _('profile - followed nodes'), 'followed_nodes': followed_nodes, 'view_user': user } context.update(data) return render_into_skin('user_profile/user_followed_nodes.html', context, request)
def user_node_create_requests(request, user, context): """show Unresolved Node create requests""" # user has perm resolve node creating if not (user.is_staff and user.has_perm('openode.add_node')): raise Http404 data = { 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_description': _('requests to create nodes'), 'page_title': _('profile - node requests') } context.update(data) return render_into_skin('user_profile/node_create_requests.html', context, request)
def node_followers(request, node_id, node_slug): node = get_object_or_404(Node, pk=node_id) if node.slug != node_slug: return HttpResponseRedirect( reverse('node_followers', kwargs={ 'node_id': node_id, 'node_slug': node.slug })) data = { 'follows': node.node_following_users.order_by("-added_at"), 'node': node } return render_into_skin('node/followers.html', data, request)
def document_detail_view(request, node, thread): """ Detail of library Document """ document = thread.get_document() main_post = thread._main_post() to_tmpl = { "node": thread.node, "document": document, "file_size": None, "main_post": main_post, "module": const.NODE_MODULE_LIBRARY, 'similar_threads': thread.get_similar_threads(), "thread": thread, } if document and document.latest_revision: to_tmpl.update({"file_size": document.latest_revision.get_size()}) # count visit for thread count_visit(request, thread, main_post) # at the end we call thread.visit, we dont need celery for this # operate with ThreadView thread.visit(request.user) if document and document.latest_revision: try: page_no = int(request.GET.get("page", 1)) except ValueError: page_no = 1 page_qs = document.get_pages(page_no) if page_qs.exists(): page = page_qs[0] else: page = None to_tmpl.update({ "page": page, "pages_numbers": document.latest_revision.pages.values_list("number", flat=True) }) return render_into_skin("node/document/detail.html", to_tmpl, request)
def document_detail_view(request, node, thread): """ Detail of library Document """ document = thread.get_document() main_post = thread._main_post() to_tmpl = { "node": thread.node, "document": document, "file_size": None, "main_post": main_post, "module": const.NODE_MODULE_LIBRARY, 'similar_threads': thread.get_similar_threads(), "thread": thread, } if document and document.latest_revision: to_tmpl.update({ "file_size": document.latest_revision.get_size() }) # count visit for thread count_visit(request, thread, main_post) # at the end we call thread.visit, we dont need celery for this # operate with ThreadView thread.visit(request.user) if document and document.latest_revision: try: page_no = int(request.GET.get("page", 1)) except ValueError: page_no = 1 page_qs = document.get_pages(page_no) if page_qs.exists(): page = page_qs[0] else: page = None to_tmpl.update({ "page": page, "pages_numbers": document.latest_revision.pages.values_list("number", flat=True) }) return render_into_skin("node/document/detail.html", to_tmpl, request)
def node_ask_to_create(request): """ ask to create node There is no cancel option as user may create more than one request and there is no way to tell what request he wants to cancel. """ sent = False # was form successful, sent and without errors? if request.POST: form = AskToCreateNodeForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] note = form.cleaned_data['note'] summary = ugettext_noop(u'''%(user)s wants to create a new node %(node_name)s. Here is a note regarding the request: %(note)s''') % { 'user': request.user, 'node_name': name, 'note': note } data = simplejson.dumps({ 'user_name': request.user.screen_name, 'user_email': request.user.email, 'node_name': name, 'note': note }) # ugettext_noop(summary) # this will translate it after its pulled from db, not before. create_request, created = Activity.objects.get_or_create( user=request.user, activity_type=const.TYPE_ACTIVITY_ASK_TO_CREATE_NODE, # summary=summary, data=data ) request.user.log(create_request, const.LOG_ACTION_ASK_TO_CREATE_NODE) sent = True else: form = AskToCreateNodeForm() to_tmpl = { 'sent': sent, 'form': form, } return render_into_skin("node/ask_to_create.html", to_tmpl, request)
def discussion_answer(request, pk): try: post = Post.objects.get(pk=pk) thread = post.thread node = thread.node except ObjectDoesNotExist: raise Http404 if not request.user.has_openode_perm('discussion_read', node): return render_forbidden(request) to_tmpl = { "answer": post, "posts_per_pages": {} } return render_into_skin('node/discussion/discussion_answer.html', to_tmpl, request)
def user_managed_nodes(request, user, context): if not request.user.has_user_perm('can_see_followed_nodes', user): return render_forbidden(request) managed_nodes = user.nodes.filter(node_users__role=const.NODE_USER_ROLE_MANAGER) data = { 'active_tab': 'users', 'page_class': 'user-profile-page', 'tab_description': _('users managed nodes'), 'page_title': _('profile - managed nodes'), 'managed_nodes': managed_nodes, } context.update(data) return render_into_skin('user_profile/user_managed_nodes.html', context, request)
def node_ask_to_join(request, node_id, node_slug): """ ask to join (create/cancel) node view """ node = get_object_or_404(Node, pk=node_id) if node.slug != node_slug: return HttpResponseRedirect(reverse('node_ask_to_join', kwargs={ 'node_id': node_id, 'node_slug': node.slug })) action = request.GET.get('request') if not request.user.is_anonymous() and node.node_users.filter(user=request.user).exists(): return HttpResponseRedirect(node.get_absolute_url()) join_request = None if request.user.is_authenticated(): node_content_type = ContentType.objects.get_for_model(Node) if action == 'join': join_request, created = Activity.objects.get_or_create( object_id=node.pk, content_type=node_content_type, user=request.user, activity_type=const.TYPE_ACTIVITY_ASK_TO_JOIN_NODE ) request.user.log(node, const.LOG_ACTION_ASK_TO_JOIN_NODE) elif action == 'cancel': try: join_request = Activity.objects.get( object_id=node.pk, content_type=node_content_type, user=request.user, activity_type=const.TYPE_ACTIVITY_ASK_TO_JOIN_NODE ) join_request.delete() except Activity.DoesNotExist: pass finally: join_request = None to_tmpl = { 'node': node, 'join_request': join_request } return render_into_skin("node/ask_to_join.html", to_tmpl, request)
def list_suggested_tags(request): """moderators and administrators can list tags that are in the moderation queue, apply suggested tag to questions or cancel the moderation reuest.""" if openode_settings.ENABLE_TAG_MODERATION == False: raise Http404 tags = Tag.objects.filter(status=Tag.STATUS_SUGGESTED) tags = tags.order_by('-used_count', 'name') #paginate moderated tags paginator = Paginator(tags, 20) page_no = request.GET.get('page', '1') try: page = paginator.page(page_no) except (EmptyPage, InvalidPage): page = paginator.page(paginator.num_pages) paginator_context = functions.setup_paginator({ 'is_paginated': True, 'pages': paginator.num_pages, 'page': page_no, 'has_previous': page.has_previous(), 'has_next': page.has_next(), 'previous': page.previous_page_number(), 'next': page.next_page_number(), 'base_url': request.path }) data = { 'tags': page.object_list, 'active_tab': 'tags', 'tab_id': 'suggested', 'page_class': 'moderate-tags-page', 'page_title': _('Suggested tags'), 'paginator_context': paginator_context, } return render_into_skin('list_suggested_tags.html', data, request)
def live(request): """ live stream view """ try: page_no = int(request.GET.get("page", 1)) except ValueError: page_no = 1 end = PER_PAGE * page_no start = end - PER_PAGE threads = get_live_data(request.user, start, end) context_dict = {"threads": threads, "check_perm": check_perm, "page": page_no} return render_into_skin("live/live.html", context_dict, request)
def ask_to_create_org(request): """ ask to create organization """ if request.method == "POST": form = OrganizationForm(request.POST, request.FILES) if form.is_valid(): org = form.save(request) summary = _( u'''%(user)s wants to create a new organization %(organization_name)s. Description of the organization: %(description)s''') % { 'user': request.user, 'organization_name': org.title, 'description': org.description.summary } # send mail: users_to_notify = get_users_with_perm('add_organization') subject = _( u'''%(user)s wants to create a new organization %(organization_name)s''' ) % { 'user': request.user, 'organization_name': org.title } notify_about_requests(users_to_notify, subject, summary) org_request, created = Activity.objects.get_or_create( object_id=org.pk, content_type=ContentType.objects.get_for_model(Organization), user=request.user, activity_type=const.TYPE_ACTIVITY_ASK_TO_CREATE_ORG, summary=summary, ) request.user.log(org, const.LOG_ACTION_ASK_TO_CREATE_ORG) else: form = OrganizationForm() to_tmpl = { 'form': form, } return render_into_skin("ask_to_create_organization.html", to_tmpl, request)
def node_ask_to_join(request, node_id, node_slug): """ ask to join (create/cancel) node view """ node = get_object_or_404(Node, pk=node_id) if node.slug != node_slug: return HttpResponseRedirect( reverse('node_ask_to_join', kwargs={ 'node_id': node_id, 'node_slug': node.slug })) action = request.GET.get('request') if not request.user.is_anonymous() and node.node_users.filter( user=request.user).exists(): return HttpResponseRedirect(node.get_absolute_url()) join_request = None if request.user.is_authenticated(): node_content_type = ContentType.objects.get_for_model(Node) if action == 'join': join_request, created = Activity.objects.get_or_create( object_id=node.pk, content_type=node_content_type, user=request.user, activity_type=const.TYPE_ACTIVITY_ASK_TO_JOIN_NODE) request.user.log(node, const.LOG_ACTION_ASK_TO_JOIN_NODE) elif action == 'cancel': try: join_request = Activity.objects.get( object_id=node.pk, content_type=node_content_type, user=request.user, activity_type=const.TYPE_ACTIVITY_ASK_TO_JOIN_NODE) join_request.delete() except Activity.DoesNotExist: pass finally: join_request = None to_tmpl = {'node': node, 'join_request': join_request} return render_into_skin("node/ask_to_join.html", to_tmpl, request)
def node_settings(request, node_id, node_slug): """ Node Settings """ node = get_object_or_404(Node, pk=node_id) if node.slug != node_slug: return HttpResponseRedirect(reverse('node_settings', kwargs={ 'node_id': node_id, 'node_slug': node.slug })) if not (request.user.is_admin('openode.change_node') or request.user.has_openode_perm('node_settings', node)): return render_forbidden(request) NodeUserInlineFormSet = inlineformset_factory(Node, NodeUser, form=NodeUserForm, extra=1) node_users = NodeUser.objects.filter(node=node).order_by('role', 'user__last_name', 'user__first_name') if request.method == "POST": form = NodeSettingsForm(instance=node, data=request.POST) formset = NodeUserInlineFormSet(request.POST, instance=node, queryset=node_users) form_is_valid = form.is_valid() formset_is_valid = formset.is_valid() if form_is_valid and formset_is_valid: form.save(user=request.user) formset.save() request.user.message_set.create(message=_('Node settings has been succesfully saved.')) return HttpResponseRedirect(reverse('node_settings', args=[node.pk, node.slug])) else: form = NodeSettingsForm(instance=node) formset = NodeUserInlineFormSet(instance=node, queryset=node_users) user_emails_by_role = SortedDict() for node_user in node_users: user_emails_by_role.setdefault(node_user.get_role_display(), []).append(node_user.user.email) template_data = { 'node': node, 'form': form, 'formset': formset, 'user_emails_by_role': user_emails_by_role, 'page_class': 'node-edit', } return render_into_skin('node/edit_settings.html', template_data, request)
def change(request, extra_context=None, next_override=None, upload_form=UploadAvatarForm, primary_form=PrimaryAvatarForm, *args, **kwargs): if extra_context is None: extra_context = {} avatar, avatars = _get_avatars(request.user) if avatar: kwargs = {'initial': {'choice': avatar.id}} else: kwargs = {} upload_avatar_form = upload_form(user=request.user, **kwargs) primary_avatar_form = primary_form(request.POST or None, user=request.user, avatars=avatars, **kwargs) if request.method == "POST": updated = False if 'choice' in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get( id=primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() updated = True request.user.message_set.create( message=_("Successfully updated your avatar.")) if updated and notification: _notification_updated(request, avatar) return HttpResponseRedirect(next_override or _get_next(request)) data = { 'avatar': avatar, 'avatars': avatars, 'upload_avatar_form': upload_avatar_form, 'primary_avatar_form': primary_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/change.html', data, 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 = EditUserForm(user, request.POST) if form.is_valid(): # new_email = bleach_html(form.cleaned_data['email']) # set_new_email(user, new_email) user.first_name = bleach_html(form.cleaned_data['first_name']) user.last_name = bleach_html(form.cleaned_data['last_name']) user.display_name = bleach_html(form.cleaned_data['display_name']) user.privacy_email_form = form.cleaned_data['privacy_email_form'] user.privacy_show_followed = form.cleaned_data['privacy_show_followed'] user.save() description = form.cleaned_data['user_description'] if user.description: request.user.edit_post(user.description, body_text=description) else: request.user.post_object_description(user, body_text=description) # send user updated signal if full fields have been updated request.user.message_set.create(message=_('Profile has been succesfully saved.')) return HttpResponseRedirect(user.get_profile_url()) else: form = EditUserForm(user) data = { 'active_tab': 'users', 'page_class': 'user-profile-edit-page', 'form': form, 'marked_tags_setting': openode_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 change( request, extra_context=None, next_override=None, upload_form=UploadAvatarForm, primary_form=PrimaryAvatarForm, *args, **kwargs ): if extra_context is None: extra_context = {} avatar, avatars = _get_avatars(request.user) if avatar: kwargs = {"initial": {"choice": avatar.id}} else: kwargs = {} upload_avatar_form = upload_form(user=request.user, **kwargs) primary_avatar_form = primary_form(request.POST or None, user=request.user, avatars=avatars, **kwargs) if request.method == "POST": updated = False if "choice" in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get(id=primary_avatar_form.cleaned_data["choice"]) avatar.primary = True avatar.save() updated = True request.user.message_set.create(message=_("Successfully updated your avatar.")) if updated and notification: _notification_updated(request, avatar) return HttpResponseRedirect(next_override or _get_next(request)) data = { "avatar": avatar, "avatars": avatars, "upload_avatar_form": upload_avatar_form, "primary_avatar_form": primary_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/change.html", data, request)
def thread_followers(request, node_id, node_slug, module, thread_id, thread_slug): node = get_object_or_404(Node, pk=node_id) thread = get_object_or_404(Thread, pk=thread_id, node=node) if node.slug != node_slug or thread.slug != thread_slug: return HttpResponseRedirect(reverse('thread_followers', kwargs={ 'node_id': node_id, 'node_slug': node.slug, 'module': module, 'thread_id': thread_id, 'thread_slug': thread.slug, })) data = { 'follows': thread.thread_following_users.order_by("-added_at"), 'thread': thread, 'node': node, "can_make_remove_from_followers": node.node_users.filter(user=request.user, role=const.NODE_USER_ROLE_MANAGER).exists() } return render_into_skin('node/%s/followers.html' % thread.thread_type, data, request)