I am a new for Django and need some help. I want to make a 'delete' function regarding comments, but when I clicked the deletion button, I got the error
Reverse for 'delete_reply' with arguments '(7, '')' not found. 1 pattern(s) tried: ['boards/(?P<board_pk>[0-9] )/reply/(?P<reply_pk>[0-9] )/delete/\Z']
I guess that there is no pk for the reply_pk, so I tried to give the pk into the url. However, I couldn't get the answer what I want. I spend lots of time to find solutions on google and here, but all wonderful answers couldn't help me to fix it.
I attached my code here and please help me
model.py
class ReplyBoard(core_models.TimeStampedModel):
reply = models.TextField(default="")
user = models.ForeignKey(user_models.User, related_name = "reply", on_delete = models.CASCADE)
board = models.ForeignKey("Board", related_name = "reply", on_delete = models.CASCADE, null = True)
view.py
class Board_detail(View):
def get(self, *args, **kwargs):
pk = kwargs.get("pk")
try:
form = forms.ReplyForm()
board = board_models.Board.objects.get(pk=pk)
return render(self.request, "boards/board_detail.html", {"board": board, "form": form})
except board_models.Board.DoesNotExist:
raise Http404()
def create_reply(request, board_pk):
form = forms.ReplyForm(request.POST)
if request.method =="POST":
board = board_models.Board.objects.get(pk=board_pk)
if form.is_valid():
reply = form.save()
reply.board = board
reply.user = request.user
reply.save()
messages.success(request, "creted the comment.")
return redirect(reverse("boards:board_detail", kwargs={"pk": board.pk}))
@login_required()
def delete_reply(request, board_pk, reply_pk):
try:
reply = board_models.ReplyBoard.objects.get(pk=reply_pk)
if request.user != reply.user.pk:
messages.error(request, "cannot delete the comment..")
else:
reply.delete()
except board_models.ReplyBoard.DoesNotExist:
pass
return redirect(reverse("boards:board_detail", kwargs={"pk": board_pk}))
urls.py
path("", views.BoardView.as_view(), name="ask_view"),
path("<int:pk>/", views.Board_detail.as_view(), name="board_detail"),
path("<int:pk>/edit/", views.EditBoardView.as_view(), name="board_edit"),
path("<int:board_pk>/delete/", views.Delete_Board, name="board_delete"),
path("create-board/", views.CreateBoardView.as_view(), name="create-board"),
path("reply/<int:board_pk>/", views.create_reply, name="create_reply"),
path("<int:board_pk>/reply/<int:reply_pk>/delete/", views.delete_reply, name="delete_reply")
html
<a href="{% url 'boards:delete_reply' board.pk reply.pk %}" >Delete</a>
CodePudding user response:
You can try with this way
(r'^reply/(?P<board_pk>\d )(?:/(?P<reply_pk>\d ))?',views.delete_reply, name="delete_reply"),