Reputation: 3611
In my app, a user can send message in a thread by creating a new thread or can message to an existing thread. Suppose a user want's to delete a message from a particular thread, I can probably delete the message. But I just want to delete the message for that user, and not for the other users of that thread. So that the message will only be seen to the other users other that the user who deleted it. How do I do that?
models.py:
class Thread(models.Model):
user = models.ManyToManyField(User)
class Message(models.Model):
thread = models.ForeignKey(Thread)
sent_date = models.DateTimeField(default=datetime.now)
body = models.TextField()
user = models.ForeignKey(User)
Edit:
message.html:
<div id="conversation">
{% for message in messages %}
{% if message|is_visible:request.user %}
<div class="messages">
<p>{{message.body}}</p>
<p>{{message.sent_date}}</p>
<p>-{{message.user}}</p>
<hr>
</div>
{% else %}
<div class="messages">
<p>You have deleted this message.</p>
</div>
{% endif %}
{% endfor %}
</div>
Edit:
templatetag:
from django import template
register = template.Library()
@register.filter
def is_visible(message, user):
"""Check the user's visibility of the message."""
return not HideMessage.objects.filter(message=message, user=user).exists()
Upvotes: 2
Views: 313
Reputation: 3384
You don't actually want to delete the message, but rather hide it from a specific user. The way to do this could be to have your threads/messages visible by all by default, but when the user "deletes" the message, create an instance of a HideMessage
model or similar that links the message to the user that "deleted" it. Then you could create a simple template filter that checks the currently logged in user ({{ request.user }}
in the template) against the message to see if they have visibility of it, e.g.
{% for message in messages %}
{% if message|is_visible:user %} {# your custom filter #}
<div class="msg visible">
Message stuff here
</div>
{% else %}
<div class="msg hidden">
You have hidden this message!
</div>
{% endif %}
{% endfor %}
The HideMessage
model for example might only need:
class HideMessage(models.Model):
message = models.ForeignKey(Message)
user = models.ForeignKey(User)
You create an instance of this whenever your user hides a specific message, and you check for the existence of this in your filter to determine if the user can see a message.
The django documentation is very good on template tags and filters, and is worth a read. A very quick implementation though would be along the lines of:
from django import template
register = template.Library()
@register.filter
def is_visible(message, user):
"""Check the user's visibility of the message."""
return not HideMessage.objects.filter(message=message, user=user).exists()
Upvotes: 3