DoesNotExist at /rooms/create_room/
Room matching query does not exist
在这一行中显示了一个错误,这是一个与我在当前模板中执行的视图函数不同的视图函数(它工作得很好
room = Room.objects.get(slug=slug)
所示功能
@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})
我尝试执行的用于创建房间模型示例的函数
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)
我的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)
在我的形态里
class RoomForm(forms.ModelForm):
class Meta:
model = Room
fields = [
'name',
]
labels = {
"name": "Room Name",
}
在我的URL中
urlpatterns = [
path('',views.rooms, name='rooms'),
path('<slug:slug>/',views.room, name='room'),
path('create_room/',views.room_form,name="create_room"),
]
我在一个最后期限和这个奇怪的错误出现在创建视图功能。请帮助我在这里。
1条答案
按热度按时间watbbzwu1#
看看你的网址:
Django在这里是从上到下的。路径
rooms/create_room
适合path('<slug:slug>/',views.room, name='room'),
,它正在尝试工作,但是我想你没有Room
和create_room
的slug,对吗?把create_room
视图放在room
视图上面,它会工作得更好。但是,事先声明,您的
room_form
视图无论如何都不会工作,您正在调用room
变量,而之前没有设置它。