Я получил ту же ошибку при написании кода.
Я начал создавать этот проект, используя видеоурок на YouTube. Я думаю, что проблема в URLConf, но сам не могу найти эту проблему.
По сути проблема в том, что когда я захожу на сайт и нажимаю определенную кнопку, появляется эта ошибка и не находит эту страницу, почему?
В моем urls.py
может быть ошибка это точно.
from django.urls import path
from . import views
urlpatterns = [
path('login/', views.loginPage, name = "login"),
path('logout/', views.logoutUser, name = "logout"),
path('register/', views.registerPage, name = "register"),
path('', views.home, name='home'),
path('room/<str:pk>/', views.room, name = "room"),
path('profile/<str:pk>',views.userProfile,name = "user-profile"),
path('create-room/', views.createRoom, name = "create-room"),
path('update-room/<str:pk>/', views.updateRoom, name = "update-room"),
path('delete-room/<str:pk>/', views.deleteRoom, name = "delete-room"),
path('delete-message/<str:pk>/', views.deleteMessage, name = "delete-message"),
]
мой views.py
from django.shortcuts import render, redirect
from django.db.models import Q
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login,logout
from .models import Room, Topic, Message
from django.contrib.auth.forms import UserCreationForm
from .forms import RoomForm
#rooms = [
# {'id': 1, 'name': 'Lets learn python!' },
# {'id': 2, 'name': 'Design with me' },
# {'id': 3, 'name': 'Frontend developers' },
#]
def loginPage(request):
page = 'login'
if request.user.is_authenticated:
return redirect('home')
if request.method == 'POST':
username = request.POST.get('username').lower()
password = request.POST.get('password')
try:
user = User.objects.get(username=username)
except:
messages.error(request,'User does not exist')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request,'Username OR password does not exit')
context = {'page': page}
return render(request, 'base/login_register.html', context)
def logoutUser(request):
logout(request)
return redirect('home')
def registerPage(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.username = user.username.lower()
user.save()
login(request, user)
return redirect('home')
else:
messages.error(request,'An error occurred during registration')
return render(request, 'base/login_register.html',{'form':form})
def home(request):
q=request.GET.get('q') if request.GET.get('q')!= None else ''
rooms = Room.objects.filter(
Q(topic__name__icontains=q) |
Q(name__icontains=q) |
Q(description__icontains=q)
)
topics = Topic.objects.all()
room_count = rooms.count()
room_messages = Message.objects.all()
context = {'rooms': rooms, 'topics' : topics,
'room_count' : room_count,'room_messages': room_messages}
return render(request, 'base/home.html', context)
def room(request,pk):
room = Room.objects.get(id=pk)
room_messages = room.message_set.all()
participants = room.participants.all(
)
if request.method == 'POST':
message = Message.objects.create(
user = request.user,
room=room,
body=request.POST.get('body')
)
room.participants.add(request.user)
return redirect('room',pk=room.id)
context = {'room': room,'room_messages':room_messages,
'participants': participants}
return render(request, 'base/room.html', context)
def userProfile(request, pk):
user = User.objects.get(id=pk)
context = {'user':user}
return render(request,'base/room.html',context)
@login_required(login_url='login')
def createRoom(requset):
form = RoomForm
if requset.method == 'POST':
form = RoomForm(requset.POST)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form}
return render(requset, 'base/room_form.html',context)
@login_required(login_url='login')
def updateRoom(request,pk):
room = Room.objects.get(id=pk)
form = RoomForm(instance=room)
if request.user != room.host:
return HttpResponse('Your are not allowed here!!!')
if request.method == 'POST':
form = RoomForm(request.POST, instance=room)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form}
return render(request,'base/room_form.html', context)
@login_required(login_url='login')
def deleteRoom(request, pk):
room = Room.objects.get(id=pk)
if request.user != room.host:
return HttpResponse('Your are not allowed here!!!')
if request.method == 'POST':
room.delete()
return redirect('home')
return render(request,'base/delete.html',{'obj': room})
@login_required(login_url='login')
def deleteMessage(request, pk):
message = Room.objects.get(id=pk)
if request.user != message.host:
return HttpResponse('Your are not allowed here!!!')
if request.method == 'POST':
message.delete()
return redirect('home')
return render(request,'base/delete.html',{'obj': message})
Если этой информации недостаточно для устранения этой ошибки, я могу предоставить другие файлы с кодом.
🤔 А знаете ли вы, что...
В Python есть множество библиотек и фреймворков для разработки веб-приложений.
URL-адрес вашего представления удаления сообщения — «delete-message». Вам также необходимо передать идентификатор, чтобы django знал, какой из них удалить.
{% url 'delete-message' message.id %}"
Источник: https://docs.djangoproject.com/en/5.0/topics/http/urls/#reverse-solve-of-urls