• Django user to user chat(message) System

    models.py class Message(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE,null = True) sender = models.ForeignKey(Account,on_delete=models.CASCADE,related_name=”sender”) receiver = models.ForeignKey(Account,on_delete=models.CASCADE,related_name=”receiver”) text = models.TextField(max_length=500) created_at = models.DateTimeField(auto_now=True) is_readed = models.BooleanField(default=False) def __str__(self): mstr = str(self.sender)+”>”+str(self.receiver)+”: “#+ str(self.product.title)+” “+str(self.created_at) return mstr view.py class MessageSend(CreateView):#Start conversation message model = Message template_name = “sendMessage.html” fields = [‘text’] success_url = reverse_lazy(‘home’) def get(self, request, *args, **kwargs):…

Django user to user chat(message) System

models.py

class Message(models.Model):
    product = models.ForeignKey(Product,on_delete=models.CASCADE,null = True)
    sender = models.ForeignKey(Account,on_delete=models.CASCADE,related_name="sender")
    receiver = models.ForeignKey(Account,on_delete=models.CASCADE,related_name="receiver")
    text = models.TextField(max_length=500)
    created_at = models.DateTimeField(auto_now=True)
    is_readed = models.BooleanField(default=False)
    def __str__(self):
        mstr = str(self.sender)+">"+str(self.receiver)+": "#+ str(self.product.title)+" "+str(self.created_at) 
        return mstr

view.py

class MessageSend(CreateView):#Start conversation message
    model = Message
    template_name = "sendMessage.html"
    fields = ['text']
    success_url = reverse_lazy('home')

    def get(self, request, *args, **kwargs):
        if not request.user.is_authenticated:       
            return HttpResponseRedirect(reverse('home'))#giriş yapılmamışsa anasayfaya yönlendirir
        if self.request.user == Account.objects.get(id=int(self.kwargs["receiver"])):
            return HttpResponseRedirect(reverse('home'))#kendine mesaj atmışsa anasayfaya yönlendirir
        return super().get(request, *args, **kwargs)

    def form_valid(self, form):#message objesini setle
        form.instance.sender = self.request.user #gönderici user
        form.instance.receiver = Account.objects.get(id=int(self.kwargs["receiver"])) #find receiver
        form.instance.product = Product.objects.get(product_id=int(self.kwargs["product"]))#which product
        return super().form_valid(form)

class MessageDetail(CreateView):#user-user message
    model = Message
    template_name = "detailMessage.html"
    fields = ['text']
    success_url = reverse_lazy('home')

    def get_context_data(self, **kwargs):
        kwargs['object_list'] = Message.objects.filter(
                receiver=self.request.user, sender=int(self.kwargs["receiver"])) | Message.objects.filter(
                    receiver=int(self.kwargs["receiver"]),sender=self.request.user).order_by('created_at')
        return super().get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        if not request.user.is_authenticated:       
            return HttpResponseRedirect(reverse('home'))
        return super().get(request, *args, **kwargs)

    def form_valid(self, form):#message objesini setle
        form.instance.sender = self.request.user #gönderici user
        form.instance.receiver = Account.objects.get(id=int(self.kwargs["receiver"])) #find receiver
        return super().form_valid(form)

class MessageBox(ListView): #bu viewde mesajları listeliyoruz 
    model = Message         #sender-receiverleri ayırt ediyoruz
    template_name = "messageBox.html"
    ordering = "created_at"
    def get_queryset(self):
        allMessages = Message.objects.filter(sender = self.request.user) | Message.objects.filter(receiver = self.request.user)
        allMessages = allMessages.order_by('-created_at')#ilgili tüm mesajları al ve sırala
        queryset = Message.objects.none()#yeni bir queryset oluştur
        users=[]
        for mObject in allMessages:
            if mObject.receiver.id == self.request.user.id:#en son mesajı tespit etmek amaçlı
                if mObject.sender.id not in users:#tekrar eden kullanıcıları geç
                    users.append(mObject.sender.id)
                    queryset |= allMessages.filter(id = mObject.id)#query'e ekle
            else:#eger user receiver değilse sender olur
                if mObject.receiver.id not in users:
                    users.append(mObject.receiver.id)
                    queryset |= allMessages.filter(id = mObject.id)
        return queryset

detail message template:

{% for message in object_list %}
        {% if message.sender.id == user.id %}
            <div class="float-right">{{ message.text }}<i> {{ message.created_at|date:"m/d/y H:i" }}</i></div><br>
        {% else %}
            <div class="float-left">{{ message.text }}<i> {{ message.created_at|date:"m/d/y H:i" }}</i></div><br>
        {% endif %}
    {% endfor %}
    <form method="post">
        {% csrf_token %}
        {{ form|crispy }}
        <input type="submit" value="SEND">
    </form>

send message template:

<form method="post">
    {% csrf_token %}
    {{ form|crispy }}
    <input type="submit" value="SEND">
</form>

message box template:

    {% for message in object_list %}
        {% if message.sender.id == user.id %}
        <!--- Mesaj gönderen kullanıcı ise alıcı ismini göster self.user.id ile de kullanıcının adına ulaşıyoruz -->
        <a href={% url 'detail-message' receiver=message.receiver.id %}>
          <h1>{{ message.receiver }}</h1></a>
          <h4>{{ message.text }}</h4>
        {% else %}
        <!-- eğer alıcı user ise göndereni yazdır  -->
        <a href={% url 'detail-message' receiver=message.sender.id %}>
          <h1>{{ message.sender }}</h1></a>
          <h4>{{ message.text }}</h4>
        {% endif %}
    {% endfor %}

 


Yorumlar

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir