Home > OS >  How to create new model using pk
How to create new model using pk

Time:11-19

I am trying to make user join the room ( so creating a new RoomMember) but this is the error that I get : "Cannot assign "room_name": "RoomMember.room" must be a "Room" instance." (thanks in advance)

*
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>*

CodePudding user response:

Change your view as follows to first query the room object.

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')

CodePudding user response:

Just add try for fail safe. with yagus answer 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")
  • Related