如何使用 pk 创建新模型

How to create new model using pk

我试图让用户加入房间(因此创建了一个新的 RoomMember),但这是我得到的错误: “无法分配“room_name”:“RoomMember.room”必须是“房间”实例。” (提前致谢)

*
Views.py:
def join_room(request, pk):
    RoomMember.objects.create(room=pk, user=request.user).save()
    return redirect('room_detail')

Urls.py:
    path("join/<int:pk>/room/", views.join_room, name="join_room"),

Models.py:
class Room(models.Model):
    name = models.CharField(max_length=100)
    about = models.TextField(max_length=500, null=True, blank=True)
    creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='room_creator')
    members = models.ManyToManyField(User, through="RoomMember")
    
    
class RoomMember(models.Model):
    approved = models.BooleanField(default=False, blank=False)
    room = models.ForeignKey(Room, related_name='memberships', on_delete=models.CASCADE)
    user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE)
    
        
class Messages(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False)
    text = models.CharField(max_length=10000, blank=False, null=False)
    date = models.DateTimeField(default=datetime.now)
    room = models.ForeignKey(Room, null=True, blank=False, on_delete=models.CASCADE)

Html:
                <a class="btn btn-dark" href="{% url 'join_room' pk=room.pk %}">Join</a>*

如下更改您的视图以首先查询房间对象。

Views.py:
def join_room(request, pk):
    myroom = Room.objects.get(id=pk)
    RoomMember.objects.create(room=myroom, user=request.user).save()
    return redirect('room_detail')

只需添加故障安全尝试。用亚古斯回答 Views.py:

from django.http import Http404
def join_room(request, pk):
    try:
        myroom = Room.objects.get(id=pk)
        RoomMember.objects.create(room=myroom, user=request.user).save()
        return redirect('room_detail')
    except Room.DoesNotExist:
        raise Http404("Content does not exist")