从房间中删除用户Django

gjmwrych  于 2023-01-10  发布在  Go
关注(0)|答案(1)|浏览(101)

在我的应用程序中,我创建了参与者(用户)可以发消息的房间。
模型. 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]

现在,在"参与者"部分中,我添加了一个用户,每当该用户在该房间中第一次发送消息时。
视图中. 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)

现在,我想在用户从会议室删除所有消息时从参与者中删除该用户。我不知道如何继续。
视图中. 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})

我该怎么做呢?

t3psigkw

t3psigkw1#

第一个月
这里的related_name应该是rooms,而不是participants。这是一个很常见的错误。尽管在本例中它不会影响您。
现在解决您的问题,您有了Room示例和User示例,因此可以查询Message表,如果没有包含UserRoom示例组合的消息,则可以安全地将用户从会议室中删除。

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

相关问题