How do I ensure any object I create is saved in my django project?

Question:

I’m working on a simple chat app that creates rooms for users to join. You enter your room name and it checks if the room exists already. If it does, you’re redirected to the room. If not, it creates a new room, saves the room and redirects you there. The issue I’m having is in saving the new room that is created.

I keep getting a "DoesNotExist" error. "Room matching query does not exist."
Here is the code:

def check_view(request):
    room_entity = request.POST['room_name']
    username = request.POST['username']

    if Room.objects.filter(name=room_entity).exists():
        return redirect('/' + str(room_entity) + '/?username=' + str(username))
    else:
        new_room = Room.objects.create(name=room_entity)
        new_room.save()
        Room.save(new_room)
        return redirect('/' + str(room_entity) + '/?username=' + str(username))


def room(request, room_info):
    username = request.GET.get('username')
    room_details = Room.objects.get(name=room_info)
    return render(request, 'room.html', {
        'username': username,
        'room': room_info,
        'room_details': room_details
    })
Asked By: Adeola Adekunle

||

Answers:

room_details = Room.objects.get(name=room_info)

If a Room object with name room_info does not exist in the database you will get this error.

Instead what you can do is:

try:
    room = Room.objects.get(name=room_info)
except Room.DoesNotExist:
    raise Http404("Given query not found....")
Answered By: Arif Rasim
room_details, created = Room.objects.get_or_create(name=room_info)

This will get the room if it exist or create it if its not found. The first variable in the returned tuple is the actual room object. The second is a bool to know if it was created(true) or if it already existed(false). Then you can create logic like:

room_details, created = Room.objects.get_or_create(name=room_info)
if created:
 enter code here to initiate a new room
else:
 enter code here to handle a room that already exists.
Answered By: Pat