models py class Thread models Model id models IntegerField max_length

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# models.py
class Thread(models.Model):
id = models.IntegerField(max_length=16, primary_key=True)
read = models.ForeignKey(User, blank=True, null=True)
date = models.DateTimeField()
class Message(models.Model):
sender = models.ForeignKey(User, related_name='sender')
recipient = models.ForeignKey(User, related_name='recipient')
content = models.TextField()
date = models.DateTimeField()
read = models.BooleanField()
thread = models.ForeignKey(Thread)
# создание тредов и сообщений
def comment_user(request, id):
sender = request.user
recipient = get_object_or_404(User, id=id)
thread_id = "%s%s" % (min(sender.id, recipient.id), max(sender.id, recipient.id))
content = request.POST['message']
thread = get_object_or_None(Thread, id=thread_id)
if thread:
thread.read = ''
thread.date = datetime.datetime.now()
thread.save()
else:
thread = Thread(id=thread_id, read=sender, date=datetime.datetime.now())
thread.save()
Message.objects.create(sender=sender, recipient=recipient, content=content, date=datetime.datetime.now(), read=False, thread=thread)
# вывод тредов
correspondence_users = []
for message in Message.objects.filter(Q(sender=request.user) | Q(recipient=request.user)):
correspondence_users.append(message.sender)
correspondence_users.append(message.recipient)
correspondence_users.remove(request.user)
thread_numbers = []
for user in correspondence_users:
thread_numbers.append("%s%s" % (min(request.user.id, user.id), max(request.user.id, user.id)))
threads = Thread.objects.filter(id__in=thread_numbers)
# template.html
<div>
<br /><br />
<b>Messages</b>:<br />
{% for thread in threads %}
{% for message in thread.message_set.all %}
{{ message.sender.first_name }} {{ message.sender.last_name }}:<br />
{{ message.content }}<br />
{% endfor %}
<br /><br />
{% endfor %}
</div>