Django messaging functionality not working

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.

Now there are three problems with this. One is that when I am in my user_message.html, if I type in a message and I hit send, I get the error:

Page not found (404) No Business matches the given query.

When clearly I have a url for that.

Secondly when I send a message, through the message_seller view, a message instance is created, it works but the recipient does not receive the message in his/her user_messages_view page, so kind of defeats the purpose.

Thirdly I have tried to make counters work, but both counters do not work. The unread_message_counter is supposed to show the number of unread messages from different businesses/users, while the individual_business_message_counter is supposed to show the number of unread messages from that specific business. When I click on a message to go to detail view of the conversation, that is when the messages are supposed to be is_read = True.

Three issues, can anyone please help me solve them? 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)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    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, on_delete=models.CASCADE, related_name='sent_messages')
    recipient = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='received_messages')
    business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='messages', 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.username} to {self.recipient.username}"

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):
    businesses = Business.objects.filter(
        Q(messages__sender=request.user) | Q(messages__recipient=request.user)
    ).distinct()
    user_messages = []

    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_businesses = set()
        if Message.objects.filter(recipient=request.user, business=business, is_read=False).exists():
            unread_businesses.add(business)
        user_messages.append({
            'business': business,
            'last_message': last_message,
            'unread_count': len(unread_businesses),
        })

    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
            )

    selected_business = None
    messages = []
    if 'business_slug' in request.GET:
        business_slug = request.GET.get('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) |
            Q(sender=selected_business.seller, recipient=request.user)
        ).filter(business=selected_business).order_by('timestamp')

    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('', views.home, name="home"),
    path('message/<slug:business_slug>/', views.message_seller, name='message_seller'),
    path('messages/', views.user_messages_view, name='user_messages'),
    path('messages/?business_slug=<slug:business_slug>', views.user_messages_view, name='user_messages'),
]

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 message in user_messages %}
                    <a href="{% url 'user_messages' %}?business_slug={{ message.business.business_slug }}" 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 %}
                                <div class="small">{{ 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>
                {% if selected_business %}
                <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="{{ 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>

                    <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="{{ selected_business.banner_image.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 %}
                            {% endfor %}
                        </div>
                    </div>

                    {% if request.user.is_authenticated %}
                    <form method="post" action="{% url 'user_messages' %}?business_slug={{ selected_business.business_slug }}">
                        {% 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>
                {% endif %}
            </div>
        </div>
    </div>
</main>

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật