DoesNotExist at /rooms/create_room/
Room matching query does not exist
error showing in this line which is a different view function(which is working perfectly) than the one I'm executing in the current template
room = Room.objects.get(slug=slug)
The indicated function
@login_required
def room(request, slug):
room = Room.objects.get(slug=slug)
messages = Message.objects.filter(room=room) [0:25]
return render(request, 'rooms/room.html', {'room': room, 'messages': messages})
The function I'm trying to execute for creating room model instance
def room_form(request, id):
if request.method == 'POST':
cf = RoomForm(request.POST or None)
if cf.is_valid():
name = request.POST.get('name')
room = Room.objects.create(room = room, user = request.user, name = name)
room.save()
return redirect(room.get_absolute_url())
else:
cf = RoomForm()
context ={
'room_form':cf,
}
return render(request, 'rooms/create_room.html', context)
My model.py
class Room(models.Model):
user = models.ForeignKey(User,models.CASCADE)
name = models.CharField(max_length=255)
slug = models.SlugField(unique=True,blank=True)
created = models.DateTimeField(auto_now_add=True, null=True)
# slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True)
def __str__(self):
return self.name " | " self.user.username
def save(self, *args, **kwargs):
self.slug = slugify(self.name self.created.day)
super(Room,self).save(*args, **kwargs)
In my forms
class RoomForm(forms.ModelForm):
class Meta:
model = Room
fields = [
'name',
]
labels = {
"name": "Room Name",
}
In my URLs
urlpatterns = [
path('',views.rooms, name='rooms'),
path('<slug:slug>/',views.room, name='room'),
path('create_room/',views.room_form,name="create_room"),
]
Im on a deadline and this weird error appeared while creating the create view function. Please help me out here.
CodePudding user response:
Look at your urls:
urlpatterns = [
path('',views.rooms, name='rooms'),
path('<slug:slug>/',views.room, name='room'),
path('create_room/',views.room_form,name="create_room"),
]
Django is going from top to bottom here. Path rooms/create_room
fits path('<slug:slug>/',views.room, name='room'),
and there it is trying to work, but you have no Room
with create_room
slug I suppose, right? Put create_room
view above the room
view and it's going to work better.
But, in advance, your room_form
view is not going to work anyway. You are calling room
variable without setting it before.