Home > Enterprise >  Delete a user from a room Django
Delete a user from a room Django

Time:01-09

In my app, I have created rooms where participants(users) can message.

In models.py

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Topic(models.Model):
    name = models.CharField(max_length=200)
    def __str__(self) :
        return self.name

class Room(models.Model):
    host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
    name = models.CharField(max_length=200)
    description = models.TextField(null=True, blank=True)
    participants = models.ManyToManyField(User, related_name='participants', blank=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-updated', '-created']
    
    def __str__(self):
        return self.name
    
class Message(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE) 
    room = models.ForeignKey(Room, on_delete=models.CASCADE)
    body = models.TextField()
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.body[0:50]

Now, in the participants section, I have added a user whenever the user sends a message sends a message for the first time in that room.

In views.py

def room(request, pk):
    room = Room.objects.get(id=pk)
    room_messages = room.message_set.all().order_by('-created')
    participants = room.participants.all()
    print(participants.all())

    if request.method == 'POST':
        message = Message.objects.create(
            user=request.user,
            room=room,
            body=request.POST.get('body')
        )
        room.participants.add(request.user)
        return redirect('room', pk=room.id)

    context = {'room':room, 'room_messages':room_messages,
        'participants':participants}
    return render(request, 'base/room.html', context)

Now I want to delete a user from participants when that user deletes all his messages from the room. I am not getting an idea how to proceed here.

In views.py

@login_required(login_url='login')
def deleteMessage(request, pk):
    message = Message.objects.get(id=pk)

    room = Room.objects.get(id=pk)
    room_messages = Message.objects.filter(room=room)

    if request.user != message.user:
        return HttpResponse('You are not allowed here!')

    if request.method == 'POST':
        message.delete()
        return redirect('home')

    return render(request, 'base/delete.html', {'obj':message})

How can I do this?

CodePudding user response:

participants = models.ManyToManyField(User, related_name='participants', blank=True)

The related_name here should be rooms, and not participants. This is a pretty common mistake. Although in this case it doesn't affect you.


Now for your problem, you have the Room instance and the User instance, so you can query the Message table and if there are no messages with that User and Room instance combo you can safely remove the user from the room.

messages = Message.objects.filter(room=room, user=request.user).count()
if not messages:
    room.participants.remove(request.user)
  • Related