class Fragment(models.Model): """ Configurable HTML fragments that can be inserted in pages. """ ref = models.CharField( _("Identifier"), max_length=100, unique=True, db_index=True, help_text=_("Unique identifier for fragment name"), ) title = models.CharField( max_length=100, blank=True, help_text=_( "Optional description that helps humans identify the content and " "role of the fragment."), ) format = EnumField(Format, _("Format"), help_text=_("Defines how content is interpreted.")) content = models.TextField( _("content"), blank=True, help_text=_("Raw fragment content in HTML or Markdown"), ) editable = models.BooleanField(default=True, editable=False) def __str__(self): return self.ref def __html__(self): return str(self.render()) def save(self, *args, **kwargs): super().save(*args, **kwargs) invalidate_cache(self.ref) def delete(self, using=None, keep_parents=False): super().delete(using, keep_parents) invalidate_cache(self.ref) def lock(self): """ Prevents fragment from being deleted on the admin. """ FragmentLock.objects.update_or_create(fragment=self) def unlock(self): """ Allows fragment being deleted. """ FragmentLock.objects.filter(fragment=self).delete() def render(self, request=None, **kwargs): """Render element to HTML""" return self.format.render(self.content, request, kwargs)
class Discipline(DescriptiveModel): """ An academic discipline. """ organization = models.ForeignKey( 'Organization', blank=True, on_delete=models.CASCADE, ) school_id = models.CharField( max_length=50, blank=True ) since = models.DateField(blank=True, null=True) # These were modeled as in https://matriculaweb.unb.br/, which is not # particularly good. In the future we may want more structured data types. syllabus = models.TextField(blank=True) program = models.TextField(blank=True) bibliography = models.TextField(blank=True)
class AbstractTimelineItem(models.TimeStampedModel): # status = models.StatusField() Posted, Draft, Scheduled classroom = models.ForeignKey( 'classrooms.Classroom', on_delete=models.CASCADE, ) topic = models.ForeignKey( 'classrooms.Topic', on_delete=models.CASCADE, ) text = models.TextField() hyperlink = models.URLField(blank=True) attachment = models.FileField( blank=True, null=True, upload_to='classrooms/timeline/notice', ) class Meta: abstract = True
class NumericQuestion(Question): """ A very simple question with a simple numeric answer. """ correct_answer = models.FloatField( _('Correct answer'), help_text=_( 'The expected numeric answer for question.' ) ) tolerance = models.FloatField( _('Tolerance'), default=0, help_text=_( 'If tolerance is zero, the responses must be exact.' ), ) label = models.CharField( _('Label'), max_length=100, default=_('Answer'), help_text=_( 'The label text that is displayed in the submission form.' ), ) help_text = models.TextField( _('Help text'), blank=True, help_text=_( 'Additional explanation that is displayed bellow the response field ' 'in the input form.' ) ) class Meta: verbose_name = _('Numeric question') verbose_name_plural = _('Numeric questions')
class Question(models.Model): """ Base abstract class for all question types. """ name = models.NameField() short_description = models.ShortDescriptionField() description = models.LongDescriptionField(help_text=_( 'Describe what the question is asking and how should the students ' 'answer it as clearly as possible. Good questions should not be ' 'ambiguous.'), ) comments = models.TextField( _('Comments'), blank=True, help_text=_( 'Arbitrary private information that you want to associate to the ' 'question page. This data is only available to the question ' 'author and staff members.')) class Meta: abstract = True permissions = [ ("download_question", "Can download question files"), ]
class Comment(StatusModel, TimeStampedModel): """ A comment on a conversation. """ STATUS = Choices(("pending", _("awaiting moderation")), ("approved", _("approved")), ("rejected", _("rejected"))) STATUS_MAP = { "pending": STATUS.pending, "approved": STATUS.approved, "rejected": STATUS.rejected } conversation = models.ForeignKey("Conversation", related_name="comments", on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) content = models.TextField( _("Content"), max_length=252, validators=[MinLengthValidator(2), is_not_empty], help_text=_("Body of text for the comment"), ) rejection_reason = models.EnumField(RejectionReason, _("Rejection reason"), default=RejectionReason.USER_PROVIDED) rejection_reason_text = models.TextField( _("Rejection reason (free-form)"), blank=True, help_text=_( "You must provide a reason to reject a comment. Users will receive " "this feedback."), ) moderator = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="moderated_comments", on_delete=models.SET_NULL, blank=True, null=True, ) is_approved = property(lambda self: self.status == self.STATUS.approved) is_pending = property(lambda self: self.status == self.STATUS.pending) is_rejected = property(lambda self: self.status == self.STATUS.rejected) @property def has_rejection_explanation(self): return self.rejection_reason != RejectionReason.USER_PROVIDED or ( self.rejection_reason.USER_PROVIDED and self.rejection_reason_text) # # Annotations # author_name = lazy(lambda self: self.author.name, name="author_name") missing_votes = lazy( lambda self: self.conversation.users.count() - self.n_votes, name="missing_votes") agree_count = lazy(lambda self: votes_counter(self, choice=Choice.AGREE), name="agree_count") skip_count = lazy(lambda self: votes_counter(self, choice=Choice.SKIP), name="skip_count") disagree_count = lazy( lambda self: votes_counter(self, choice=Choice.DISAGREE), name="disagree_count") n_votes = lazy(lambda self: votes_counter(self), name="n_votes") @property def rejection_reason_display(self): if self.status == self.STATUS.approved: return _("Comment is approved") elif self.status == self.STATUS.pending: return _("Comment is pending moderation") elif self.rejection_reason_text: return self.rejection_reason_text elif self.rejection_reason is not None: return self.rejection_reason.description else: raise AssertionError objects = CommentQuerySet.as_manager() class Meta: unique_together = ("conversation", "content") def __str__(self): return self.content def clean(self): super().clean() if self.status == self.STATUS.rejected and not self.has_rejection_explanation: raise ValidationError({ "rejection_reason": _("Must give a reason to reject a comment") }) def vote(self, author, choice, commit=True): """ Cast a vote for the current comment. Vote must be one of 'agree', 'skip' or 'disagree'. >>> comment.vote(user, 'agree') # doctest: +SKIP """ choice = normalize_choice(choice) # We do not full_clean since the uniqueness constraint will only be # enforced when strictly necessary. vote = Vote(author=author, comment=self, choice=choice) vote.clean_fields() # Check if vote exists and if its existence represents an error is_changed = False try: saved_vote = Vote.objects.get(author=author, comment=self) except Vote.DoesNotExist: pass else: if saved_vote.choice == choice: commit = False elif saved_vote.choice == Choice.SKIP: vote.id = saved_vote.id vote.created = now() is_changed = True else: raise ValidationError("Cannot change user vote") # Send possibly saved vote if commit: vote.save() log.debug(f"Registered vote: {author} - {choice}") vote_cast.send( Comment, vote=vote, comment=self, choice=choice, is_update=is_changed, is_final=choice != Choice.SKIP, ) return vote def statistics(self, ratios=False): """ Return full voting statistics for comment. Args: ratios (bool): If True, also include 'agree_ratio', 'disagree_ratio', etc fields each original value. Ratios count the percentage of votes in each category. >>> comment.statistics() # doctest: +SKIP { 'agree': 42, 'disagree': 10, 'skip': 25, 'total': 67, 'missing': 102, } """ stats = { "agree": self.agree_count, "disagree": self.disagree_count, "skip": self.skip_count, "total": self.n_votes, "missing": self.missing_votes, } if ratios: e = 1e-50 # prevents ZeroDivisionErrors stats.update( agree_ratio=self.agree_count / (self.n_votes + e), disagree_ratio=self.disagree_count / (self.n_votes + e), skip_ratio=self.skip_count / (self.n_votes + e), missing_ratio=self.missing_votes / (self.missing_votes + self.n_votes + e), ) return stats
class Stereotype(models.Model): """ A "fake" user created to help with classification. """ name = models.CharField( _("Name"), max_length=64, help_text=_("Public identification of persona.") ) owner = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="stereotypes", on_delete=models.CASCADE ) description = models.TextField( _("Description"), blank=True, help_text=_( "Specify a background history, or give hints about the profile this persona wants to " "capture. This information is optional and is not made public." ), ) objects = StereotypeQuerySet.as_manager() class Meta: unique_together = [("name", "owner")] __str__ = lambda self: f'{self.name} ({self.owner})' def vote(self, comment, choice, commit=True): """ Cast a single vote for the stereotype. """ choice = Choice.normalize(choice) log.debug(f"Vote: {self.name} (stereotype) - {choice}") vote = StereotypeVote(author=self, comment=comment, choice=choice) vote.full_clean() if commit: vote.save() return vote def cast_votes(self, choices): """ Create votes from dictionary of comments to choices. """ votes = [] for comment, choice in choices.items(): votes.append(self.vote(comment, choice, commit=False)) StereotypeVote.objects.bulk_update(votes) return votes def non_voted_comments(self, conversation): """ Return a queryset with all comments that did not receive votes. """ voted = StereotypeVote.objects.filter( author=self, comment__conversation=conversation ) comment_ids = voted.values_list("comment", flat=True) return conversation.comments.exclude(id__in=comment_ids) def voted_comments(self, conversation): """ Return a queryset with all comments that the stereotype has cast votes. The resulting queryset is annotated with the vote value using the choice attribute. """ voted = StereotypeVote.objects.filter( author=self, comment__conversation=conversation ) voted_subquery = voted.filter(comment=OuterRef("id")).values("choice") comment_ids = voted.values_list("comment", flat=True) return conversation.comments.filter(id__in=comment_ids).annotate( choice=Subquery(voted_subquery) )
class Conversation(TimeStampedModel): """ A topic of conversation. """ title = models.CharField( _("Title"), max_length=255, help_text=_( "Short description used to create URL slugs (e.g. School system)." ), ) text = models.TextField(_("Question"), help_text=_("What do you want to ask?")) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="conversations", help_text= _("Only the author and administrative staff can edit this conversation." ), ) moderators = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name="moderated_conversations", help_text=_("Moderators can accept and reject comments."), ) slug = AutoSlugField(unique=False, populate_from="title") is_promoted = models.BooleanField( _("Promote conversation?"), default=False, help_text=_( "Promoted conversations appears in the main /conversations/ " "endpoint."), ) is_hidden = models.BooleanField( _("Hide conversation?"), default=False, help_text=_( "Hidden conversations does not appears in boards or in the main /conversations/ " "endpoint."), ) objects = ConversationQuerySet.as_manager() tags = TaggableManager(through="ConversationTag", blank=True) votes = property( lambda self: Vote.objects.filter(comment__conversation=self)) @property def users(self): return (get_user_model().objects.filter( votes__comment__conversation=self).distinct()) @property def approved_comments(self): return self.comments.filter(status=Comment.STATUS.approved) class Meta: ordering = ["created"] permissions = ( ("can_publish_promoted", _("Can publish promoted conversations")), ("is_moderator", _("Can moderate comments in any conversation")), ) # # Statistics and annotated values # author_name = lazy(this.author.name) first_tag = lazy(this.tags.values_list("name", flat=True).first()) tag_names = lazy(this.tags.values_list("name", flat=True)) # Statistics n_comments = lazy( this.comments.filter(status=Comment.STATUS.approved).count()) n_pending_comments = lazy( this.comments.filter(status=Comment.STATUS.pending).count()) n_rejected_comments = lazy( this.comments.filter(status=Comment.STATUS.rejected).count()) n_favorites = lazy(this.favorites.count()) n_tags = lazy(this.tags.count()) n_votes = lazy(this.votes.count()) n_participants = lazy(this.users.count()) # Statistics for the request user user_comments = property(this.comments.filter(author=this.for_user)) user_votes = property(this.votes.filter(author=this.for_user)) n_user_comments = lazy( this.user_comments.filter(status=Comment.STATUS.approved).count()) n_user_rejected_comments = lazy( this.user_comments.filter(status=Comment.STATUS.rejected).count()) n_user_pending_comments = lazy( this.user_comments.filter(status=Comment.STATUS.pending).count()) n_user_votes = lazy(this.user_votes.count()) is_user_favorite = lazy(this.is_favorite(this.for_user)) @lazy def for_user(self): return self.request.user @lazy def request(self): msg = "Set the request object by calling the .set_request(request) method first" raise RuntimeError(msg) # TODO: move as patches from other apps @lazy def n_clusters(self): try: return self.clusterization.n_clusters except AttributeError: return 0 @lazy def n_stereotypes(self): try: return self.clusterization.n_clusters except AttributeError: return 0 n_endorsements = 0 def __str__(self): return self.title def set_request(self, request_or_user): """ Saves optional user and request attributes in model. Those attributes are used to compute and cache many other attributes and statistics in the conversation model instance. """ request = None user = request_or_user if not isinstance(request_or_user, get_user_model()): user = request_or_user.user request = request_or_user if (self.__dict__.get("for_user", user) != user or self.__dict__.get("request", request) != request): raise ValueError("user/request already set in conversation!") self.for_user = user self.request = request def save(self, *args, **kwargs): if self.id is None: pass super().save(*args, **kwargs) def clean(self): can_edit = "ej.can_edit_conversation" if (self.is_promoted and self.author_id is not None and not self.author.has_perm(can_edit, self)): raise ValidationError( _("User does not have permission to create a promoted " "conversation.")) def get_absolute_url(self, board=None): kwargs = {"conversation": self, "slug": self.slug} if board is None: board = getattr(self, "board", None) if board: kwargs["board"] = board return SafeUrl("boards:conversation-detail", **kwargs) else: return SafeUrl("conversation:detail", **kwargs) def url(self, which, board=None, **kwargs): """ Return a url pertaining to the current conversation. """ if board is None: board = getattr(self, "board", None) kwargs["conversation"] = self kwargs["slug"] = self.slug if board: kwargs["board"] = board which = "boards:" + which.replace(":", "-") return SafeUrl(which, **kwargs) return SafeUrl(which, **kwargs) def votes_for_user(self, user): """ Get all votes in conversation for the given user. """ if user.id is None: return Vote.objects.none() return self.votes.filter(author=user) def create_comment(self, author, content, commit=True, *, status=None, check_limits=True, **kwargs): """ Create a new comment object for the given user. If commit=True (default), comment is persisted on the database. By default, this method check if the user can post according to the limits imposed by the conversation. It also normalizes duplicate comments and reuse duplicates from the database. """ # Convert status, if necessary if status is None and (author.id == self.author.id or author.has_perm( "ej.can_edit_conversation", self)): kwargs["status"] = Comment.STATUS.approved else: kwargs["status"] = normalize_status(status) # Check limits if check_limits and not author.has_perm("ej.can_comment", self): log.info("failed attempt to create comment by %s" % author) raise PermissionError("user cannot comment on conversation.") # Check if comment is created with rejected status if status == Comment.STATUS.rejected: msg = _("automatically rejected") kwargs.setdefault("rejection_reason", msg) kwargs.update(author=author, content=content.strip()) comment = make_clean(Comment, commit, conversation=self, **kwargs) log.info("new comment: %s" % comment) return comment def vote_count(self, which=None): """ Return the number of votes of a given type. """ kwargs = {"comment__conversation_id": self.id} if which is not None: kwargs["choice"] = which return Vote.objects.filter(**kwargs).count() def statistics(self, cache=True): """ Return a dictionary with basic statistics about conversation. """ if cache: try: return self._cached_statistics except AttributeError: self._cached_statistics = self.statistics(False) return self._cached_statistics return { # Vote counts "votes": self.votes.aggregate( agree=Count("choice", filter=Q(choice=Choice.AGREE)), disagree=Count("choice", filter=Q(choice=Choice.DISAGREE)), skip=Count("choice", filter=Q(choice=Choice.SKIP)), total=Count("choice"), ), # Comment counts "comments": self.comments.aggregate( approved=Count("status", filter=Q(status=Comment.STATUS.approved)), rejected=Count("status", filter=Q(status=Comment.STATUS.rejected)), pending=Count("status", filter=Q(status=Comment.STATUS.pending)), total=Count("status"), ), # Participants count "participants": { "voters": (get_user_model().objects.filter( votes__comment__conversation_id=self.id).distinct().count( )), "commenters": (get_user_model().objects.filter( comments__conversation_id=self.id, comments__status=Comment.STATUS.approved, ).distinct().count()), }, } def statistics_for_user(self, user): """ Get information about user. """ max_votes = (self.comments.filter( status=Comment.STATUS.approved).exclude(author_id=user.id).count()) given_votes = (0 if user.id is None else (Vote.objects.filter(comment__conversation_id=self.id, author=user).count())) e = 1e-50 # for numerical stability return { "votes": given_votes, "missing_votes": max_votes - given_votes, "participation_ratio": given_votes / (max_votes + e), } def next_comment(self, user, default=NOT_GIVEN): """ Returns a random comment that user didn't vote yet. If default value is not given, raises a Comment.DoesNotExit exception if no comments are available for user. """ comment = rules.compute("ej.next_comment", self, user) if comment: return comment elif default is NOT_GIVEN: msg = _("No comments available for this user") raise Comment.DoesNotExist(msg) else: return default def is_favorite(self, user): """ Checks if conversation is favorite for the given user. """ return bool(self.favorites.filter(user=user).exists()) def make_favorite(self, user): """ Make conversation favorite for user. """ self.favorites.update_or_create(user=user) def remove_favorite(self, user): """ Remove favorite status for conversation """ if self.is_favorite(user): self.favorites.filter(user=user).delete() def toggle_favorite(self, user): """ Toggles favorite status of conversation. Return the final favorite status. """ try: self.favorites.get(user=user).delete() return False except ObjectDoesNotExist: self.make_favorite(user) return True
class Conversation(HasFavoriteMixin, TimeStampedModel): """ A topic of conversation. """ title = models.CharField( _("Title"), max_length=255, help_text=_( "Short description used to create URL slugs (e.g. School system)." ), ) text = models.TextField(_("Question"), help_text=_("What do you want to ask?")) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="conversations", help_text= _("Only the author and administrative staff can edit this conversation." ), ) moderators = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name="moderated_conversations", help_text=_("Moderators can accept and reject comments."), ) slug = AutoSlugField(unique=False, populate_from="title") is_promoted = models.BooleanField( _("Promote conversation?"), default=False, help_text=_( "Promoted conversations appears in the main /conversations/ " "endpoint."), ) is_hidden = models.BooleanField( _("Hide conversation?"), default=False, help_text=_( "Hidden conversations does not appears in boards or in the main /conversations/ " "endpoint."), ) objects = ConversationQuerySet.as_manager() tags = TaggableManager(through="ConversationTag", blank=True) votes = property( lambda self: Vote.objects.filter(comment__conversation=self)) @property def users(self): return get_user_model().objects.filter( votes__comment__conversation=self).distinct() # Comment managers def _filter_comments(*args): *_, which = args status = getattr(Comment.STATUS, which) return property(lambda self: self.comments.filter(status=status)) approved_comments = _filter_comments("approved") rejected_comments = _filter_comments("rejected") pending_comments = _filter_comments("pending") del _filter_comments class Meta: ordering = ["created"] verbose_name = _("Conversation") verbose_name_plural = _("Conversations") permissions = ( ("can_publish_promoted", _("Can publish promoted conversations")), ("is_moderator", _("Can moderate comments in any conversation")), ) # # Statistics and annotated values # author_name = lazy(this.author.name) first_tag = lazy(this.tags.values_list("name", flat=True).first()) tag_names = lazy(this.tags.values_list("name", flat=True)) # Statistics n_comments = deprecate_lazy( this.n_approved_comments, "Conversation.n_comments was deprecated in favor of .n_approved_comments." ) n_approved_comments = lazy(this.approved_comments.count()) n_pending_comments = lazy(this.pending_comments.count()) n_rejected_comments = lazy(this.rejected_comments.count()) n_total_comments = lazy(this.comments.count().count()) n_favorites = lazy(this.favorites.count()) n_tags = lazy(this.tags.count()) n_votes = lazy(this.votes.count()) n_final_votes = lazy(this.votes.exclude(choice=Choice.SKIP).count()) n_participants = lazy(this.users.count()) # Statistics for the request user user_comments = property(this.comments.filter(author=this.for_user)) user_votes = property(this.votes.filter(author=this.for_user)) n_user_total_comments = lazy(this.user_comments.count()) n_user_comments = lazy( this.user_comments.filter(status=Comment.STATUS.approved).count()) n_user_rejected_comments = lazy( this.user_comments.filter(status=Comment.STATUS.rejected).count()) n_user_pending_comments = lazy( this.user_comments.filter(status=Comment.STATUS.pending).count()) n_user_votes = lazy(this.user_votes.count()) n_user_final_votes = lazy( this.user_votes.exclude(choice=Choice.SKIP).count()) is_user_favorite = lazy(this.is_favorite(this.for_user)) # Statistical methods vote_count = vote_count statistics = statistics statistics_for_user = statistics_for_user @lazy def for_user(self): return self.request.user @lazy def request(self): msg = "Set the request object by calling the .set_request(request) method first" raise RuntimeError(msg) # TODO: move as patches from other apps @lazy def n_clusters(self): try: return self.clusterization.n_clusters except AttributeError: return 0 @lazy def n_stereotypes(self): try: return self.clusterization.n_clusters except AttributeError: return 0 n_endorsements = 0 # FIXME: endorsements def __str__(self): return self.title def set_request(self, request_or_user): """ Saves optional user and request attributes in model. Those attributes are used to compute and cache many other attributes and statistics in the conversation model instance. """ request = None user = request_or_user if not isinstance(request_or_user, get_user_model()): user = request_or_user.user request = request_or_user if self.__dict__.get("for_user", user) != user or self.__dict__.get( "request", request) != request: raise ValueError("user/request already set in conversation!") self.for_user = user self.request = request def save(self, *args, **kwargs): if self.id is None: pass super().save(*args, **kwargs) def clean(self): can_edit = "ej.can_edit_conversation" if self.is_promoted and self.author_id is not None and not self.author.has_perm( can_edit, self): raise ValidationError( _("User does not have permission to create a promoted " "conversation.")) def get_absolute_url(self, board=None): kwargs = {"conversation": self, "slug": self.slug} if board is None: board = getattr(self, "board", None) if board: kwargs["board"] = board return SafeUrl("boards:conversation-detail", **kwargs) else: return SafeUrl("conversation:detail", **kwargs) def url(self, which="conversation:detail", board=None, **kwargs): """ Return a url pertaining to the current conversation. """ if board is None: board = getattr(self, "board", None) kwargs["conversation"] = self kwargs["slug"] = self.slug if board: kwargs["board"] = board which = "boards:" + which.replace(":", "-") return SafeUrl(which, **kwargs) return SafeUrl(which, **kwargs) def votes_for_user(self, user): """ Get all votes in conversation for the given user. """ if user.id is None: return Vote.objects.none() return self.votes.filter(author=user) def create_comment(self, author, content, commit=True, *, status=None, check_limits=True, **kwargs): """ Create a new comment object for the given user. If commit=True (default), comment is persisted on the database. By default, this method check if the user can post according to the limits imposed by the conversation. It also normalizes duplicate comments and reuse duplicates from the database. """ # Convert status, if necessary if status is None and (author.id == self.author.id or author.has_perm( "ej.can_edit_conversation", self)): kwargs["status"] = Comment.STATUS.approved else: kwargs["status"] = normalize_status(status) # Check limits if check_limits and not author.has_perm("ej.can_comment", self): log.info("failed attempt to create comment by %s" % author) raise PermissionError("user cannot comment on conversation.") # Check if comment is created with rejected status if status == Comment.STATUS.rejected: msg = _("automatically rejected") kwargs.setdefault("rejection_reason", msg) kwargs.update(author=author, content=content.strip()) comment = make_clean(Comment, commit, conversation=self, **kwargs) if comment.status == comment.STATUS.approved and author != self.author: comment_moderated.send( Comment, comment=comment, moderator=comment.moderator, is_approved=True, author=comment.author, ) log.info("new comment: %s" % comment) return comment def next_comment(self, user, default=NOT_GIVEN): """ Returns a random comment that user didn't vote yet. If default value is not given, raises a Comment.DoesNotExit exception if no comments are available for user. """ comment = rules.compute("ej.next_comment", self, user) if comment: return comment return None def next_comment_with_id(self, user, comment_id=None): """ Returns a comment with id if user didn't vote yet, otherwhise return a random comment. """ if comment_id: try: return self.approved_comments.exclude(votes__author=user).get( id=comment_id) except Exception as e: pass return self.next_comment(user)
class Cluster(TimeStampedModel): """ Represents an opinion group. """ clusterization = models.ForeignKey("Clusterization", on_delete=models.CASCADE, related_name="clusters") name = models.CharField(_("Name"), max_length=64) description = models.TextField( _("Description"), blank=True, help_text=_("How was this cluster conceived?")) users = models.ManyToManyField(get_user_model(), related_name="clusters", blank=True) stereotypes = models.ManyToManyField("Stereotype", related_name="clusters") conversation = delegate_to("clusterization") comments = delegate_to("clusterization") objects = ClusterManager() @property def votes(self): return self.clusterization.votes.filter(author__in=self.users.all()) @property def stereotype_votes(self): return self.clusterization.stereotype_votes.filter( author__in=self.stereotypes.all()) n_votes = lazy(this.votes.count()) n_users = lazy(this.users.count()) n_stereotypes = lazy(this.stereotypes.count()) n_stereotype_votes = lazy(this.n_stereotype_votes.count()) def __str__(self): msg = _('{name} ("{conversation}" conversation, {n} users)') return msg.format(name=self.name, conversation=self.conversation, n=self.users.count()) def get_absolute_url(self): args = {"conversation": self.conversation, "cluster": self} return reverse("cluster:detail", kwargs=args) def mean_stereotype(self): """ Return the mean stereotype for cluster. """ stereotypes = self.stereotypes.all() votes = StereotypeVote.objects.filter( author__in=Subquery(stereotypes.values("id"))).values_list( "comment", "choice") df = pd.DataFrame(list(votes), columns=["comment", "choice"]) if len(df) == 0: return pd.DataFrame([], columns=["choice"]) else: return df.pivot_table("choice", index="comment", aggfunc="mean") def comments_statistics_summary_dataframe(self, normalization=1.0): """ Like comments.statistics_summary_dataframe(), but restricts votes to users in the current clusters. """ kwargs = dict(normalization=normalization, votes=self.votes) return self.comments.statistics_summary_dataframe(**kwargs) def separate_comments(self, sort=True): """ Separate comments into a pair for comments that cluster agrees to and comments that cluster disagree. """ tol = 1e-6 table = self.votes.votes_table() n_agree = (table > 0).sum() n_disagree = (table < 0).sum() total = n_agree + n_disagree + (table == 0).sum() + tol d_agree = dict( ((n_agree[n_agree >= n_disagree] + tol) / total).dropna().items()) d_disagree = dict(((n_disagree[n_disagree > n_agree] + tol) / total).dropna().items()) agree = [] disagree = [] for comment in Comment.objects.filter(id__in=d_agree): # It would accept 0% agreement since we test sfor n_agree >= n_disagree # We must prevent cases with 0 agrees (>= 0 disagrees) to enter in # the calculation n_agree = d_agree[comment.id] if n_agree: comment.agree = n_agree agree.append(comment) for comment in Comment.objects.filter(id__in=d_disagree): comment.disagree = d_disagree[comment.id] disagree.append(comment) if sort: agree.sort(key=lambda c: c.agree, reverse=True) disagree.sort(key=lambda c: c.disagree, reverse=True) return agree, disagree
class Task(AbstractTask): instructions = models.TextField()