So I’m trying to add messaging functionality to my e-commerce website, where buyers can message sellers and sellers can message buyers once the buyer has purchased something from them (haven’t written the code for that yet, just want basic messaging functionality out of the way). So this is what I’ve tried.
So about my views, I have two views. Through the message_seller
view I can directly message that specific seller, it takes me to the inbox of that seller, and the user_messages_view
is like an inbox of that user’s messages, sent and received, and the user can click on a selected message to open up the conversation.
I can send message to other users, but there is one problem with this. That is when a user receives a message initiated by another user, the inbox shows an incorrect self-conversation rather than the actual message. Even though the unread message counter correctly shows the unread messages for that user.
Can anyone please help me solve the issue? Thanks in advance!
My models.py:
class Business(models.Model):
BUSINESS_TYPE_CHOICES = [
('product', 'Product Business'),
('service', 'Service Business'),
]
seller = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='business')
business_name = models.CharField(max_length=100)
description = models.TextField()
business_slug = models.SlugField(unique=True, blank=True)
business_type = models.CharField(max_length=20, choices=BUSINESS_TYPE_CHOICES)
countries = models.ManyToManyField(Country)
states = models.ManyToManyField(State)
address = models.CharField(max_length=200)
phone = models.CharField(max_length=20)
website = models.URLField(blank=True, null=True)
email = models.EmailField(blank=True, null=True)
profile_picture = models.ImageField(upload_to='business_profiles/', blank=True, null=True)
banner_image = models.ImageField(upload_to='business_banners/', blank=True, null=True)
is_featured = models.BooleanField(default=False)
def __str__(self):
return self.business_name
def save(self, *args, **kwargs):
if not self.business_slug:
self.business_slug = slugify(self.business_name)
super().save(*args, **kwargs)
class Message(models.Model):
sender = models.ForeignKey(CustomUser, related_name='sent_messages', on_delete=models.CASCADE)
recipient = models.ForeignKey(CustomUser, related_name='received_messages', on_delete=models.CASCADE)
business = models.ForeignKey(Business, related_name='messages', on_delete=models.CASCADE, null=True)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
is_read = models.BooleanField(default=False)
def __str__(self):
return f'Message from {self.sender} to {self.recipient} in {self.business}'
My views.py:
@login_required
def message_seller(request, business_slug):
business = get_object_or_404(Business, business_slug=business_slug)
if request.method == 'POST':
content = request.POST.get('content')
if content:
Message.objects.create(
sender=request.user,
recipient=business.seller,
business=business,
content=content
)
return redirect('message_seller', business_slug=business.business_slug)
# Mark messages as read for the current user and business
Message.objects.filter(recipient=request.user, business=business).update(is_read=True)
messages = Message.objects.filter(
Q(sender=request.user, recipient=business.seller) |
Q(sender=business.seller, recipient=request.user)
).filter(business=business).order_by('timestamp')
individual_business_message_counter = Message.objects.filter(recipient=request.user, business=business, is_read=False).count()
context = {
'business': business,
'messages': messages,
'individual_business_message_counter': individual_business_message_counter,
}
return render(request, 'business/message.html', context)
@login_required
def user_messages_view(request, business_slug=None):
# Fetch all businesses the user has interacted with
businesses = Business.objects.filter(
Q(messages__sender=request.user) | Q(messages__recipient=request.user)
).distinct()
user_messages = []
unread_businesses = set()
for business in businesses:
last_message = Message.objects.filter(
Q(sender=request.user, recipient=business.seller) |
Q(sender=business.seller, recipient=request.user)
).filter(business=business).order_by('-timestamp').first()
unread_count = Message.objects.filter(recipient=request.user, business=business, is_read=False).count()
if unread_count > 0:
unread_businesses.add(business)
user_messages.append({
'business': business,
'last_message': last_message,
'unread_count': unread_count,
})
unread_message_counter = len(unread_businesses)
if request.method == 'POST':
business_slug = request.POST.get('business_slug')
business = get_object_or_404(Business, business_slug=business_slug)
content = request.POST.get('content')
if content:
Message.objects.create(
sender=request.user,
recipient=business.seller,
business=business,
content=content
)
return redirect(f'{request.path}?business_slug={business.business_slug}')
selected_business = None
messages = []
business_slug = request.GET.get('business_slug')
if business_slug:
selected_business = get_object_or_404(Business, business_slug=business_slug)
messages = Message.objects.filter(
Q(sender=request.user, recipient=selected_business.seller, business=selected_business) |
Q(sender=selected_business.seller, recipient=request.user, business=selected_business)
).order_by('timestamp')
Message.objects.filter(recipient=request.user, business=selected_business).update(is_read=True)
context = {
'user_messages': user_messages,
'selected_business': selected_business,
'messages': messages,
'unread_message_counter': unread_message_counter,
}
return render(request, 'business/user_messages.html', context)
My urls.py:
urlpatterns = [
path('message/<slug:business_slug>/', views.message_seller, name='message_seller'),
path('messages/', views.user_messages_view, name='user_messages'),
path('messages/<slug:business_slug>/', views.user_messages_view, name='user_messages_with_slug'),
]
My message.html:
<main class="content">
<div class="container p-0">
<h1 class="h3 mb-3 mt-3">Messages</h1>
<div class="card">
<div class="row g-0">
<div class="col-12 col-lg-5 col-xl-3 border-right">
{% for message in user_messages %}
<a href="#" class="list-group-item list-group-item-action border-0">
<div class="badge bg-success float-right">{{ individual_business_message_counter }}</div>
<div class="d-flex align-items-start">
<img src="{{ message.business.profile_picture.url }}" class="rounded-circle mr-1" width="40px" height="40px">
<div class="flex-grow-1 ml-3">
{{ message.business.business_name }}
{% if message.last_message %}
{% if not message.last_message.is_read %}
<div class="small">{{ message.last_message.content }}</div>
{% else %}
<div class="small"><b>{{ message.last_message.content }}</b></div>
{% endif %}
{% else %}
<p>No messages yet.</p>
{% endif %}
</div>
</div>
</a>
{% endfor %}
<hr class="d-block d-lg-none mt-1 mb-0">
</div>
<div class="col-12 col-lg-7 col-xl-9">
<div class="py-2 px-4 border-bottom d-none d-lg-block">
<div class="d-flex align-items-center py-1">
<div class="position-relative">
<img src="{{ business.profile_picture.url }}" class="rounded-circle mr-1" alt="Sharon Lessman" width="40" height="40">
</div>
<div class="flex-grow-1 pl-3">
<strong>{{ business.business_name }}</strong>
</div>
</div>
</div>
<div class="position-relative">
<div class="chat-messages p-4">
{% for message in messages %}
{% if message.sender == request.user %}
<div class="chat-message-right pb-4">
<div>
<img src="https://bootdey.com/img/Content/avatar/avatar1.png" class="rounded-circle mr-1" alt="Chris Wood" width="40" height="40">
<div class="text-muted small text-nowrap mt-2">{{ message.timestamp }}</div>
</div>
<div class="flex-shrink-1 bg-light rounded py-2 px-3 mr-3">
<div class="font-weight-bold mb-1">You</div>
{{ message.content }}
</div>
</div>
{% else %}
<div class="chat-message-left pb-4">
<div>
<img src="{{ business.banner_image.url }}" class="rounded-circle mr-1" alt="{{ business.business_name }}" width="40" height="40">
<div class="text-muted small text-nowrap mt-2">{{ message.timestamp }}</div>
</div>
<div class="flex-shrink-1 bg-light rounded py-2 px-3 ml-3">
<div class="font-weight-bold mb-1">{{ business.business_name }}</div>
{{ message.content }}
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% if request.user.is_authenticated %}
<form method="post">
{% csrf_token %}
<div class="flex-grow-0 py-3 px-4 border-top">
<div class="input-group">
<input name="content" type="text" class="form-control" placeholder="Type your message">
<button class="btn btn-primary">Send</button>
</div>
</div>
</form>
{% endif %}
</div>
</div>
</div>
</div>
</main>
My user_messages.html:
<main class="content mt-5 mb-5">
<div class="container p-0">
<h1 class="h3 mb-3">Your Messages</h1>
<div class="card">
<div class="row g-0">
<div class="col-12 col-lg-5 col-xl-3 border-right">
{% for user_message in user_messages %}
<a href="{% url 'user_messages' %}?business_slug={{ user_message.business.business_slug }}" class="list-group-item list-group-item-action border-0">
<div class="badge bg-success float-right">{{ user_message.unread_count }}</div>
<div class="d-flex align-items-start">
<img src="{{ user_message.business.profile_picture.url }}" class="rounded-circle mr-1" width="40px" height="40px">
<div class="flex-grow-1 ml-3">
{{ user_message.business.business_name }}
{% if user_message.last_message %}
<div class="small">{{ user_message.last_message.content }}</div>
{% else %}
<p>No messages yet.</p>
{% endif %}
</div>
</div>
</a>
{% endfor %}
<hr class="d-block d-lg-none mt-1 mb-0">
</div>
<div class="col-12 col-lg-7 col-xl-9">
{% if selected_business %}
<div class="py-2 px-4 border-bottom d-none d-lg-block">
<div class="d-flex align-items-center py-1">
<div class="position-relative">
<img src="{{ selected_business.profile_picture.url }}" class="rounded-circle mr-1" alt="{{ selected_business.business_name }}" width="40" height="40">
</div>
<div class="flex-grow-1 pl-3">
<strong>{{ selected_business.business_name }}</strong>
</div>
</div>
</div>
{% endif %}
<div class="position-relative">
<div class="chat-messages p-4">
{% for message in messages %}
{% if message.sender == request.user %}
<div class="chat-message-right pb-4">
<div>
<img src="https://bootdey.com/img/Content/avatar/avatar1.png" class="rounded-circle mr-1" alt="User Avatar" width="40" height="40">
<div class="text-muted small text-nowrap mt-2">{{ message.timestamp }}</div>
</div>
<div class="flex-shrink-1 bg-light rounded py-2 px-3 mr-3">
<div class="font-weight-bold mb-1">You</div>
{{ message.content }}
</div>
</div>
{% else %}
<div class="chat-message-left pb-4">
<div>
<img src="{{ selected_business.profile_picture.url }}" class="rounded-circle mr-1" alt="{{ selected_business.business_name }}" width="40" height="40">
<div class="text-muted small text-nowrap mt-2">{{ message.timestamp }}</div>
</div>
<div class="flex-shrink-1 bg-light rounded py-2 px-3 ml-3">
<div class="font-weight-bold mb-1">{{ selected_business.business_name }}</div>
{{ message.content }}
</div>
</div>
{% endif %}
{% empty %}
<p>No messages yet.</p>
{% endfor %}
</div>
</div>
{% if request.user.is_authenticated and selected_business %}
<form method="post" action="{% url 'user_messages' %}?business_slug={{ selected_business.business_slug }}">
{% csrf_token %}
<input type="hidden" name="business_slug" value="{{ selected_business.business_slug }}">
<div class="flex-grow-0 py-3 px-4 border-top">
<div class="input-group">
<input name="content" type="text" class="form-control" placeholder="Type your message">
<button class="btn btn-primary">Send</button>
</div>
</div>
</form>
{% endif %}
</div>
</div>
</div>
</div>
</main>