I am developing a website watching a video course and sometimes I don't agree with mentor decisions about solving some tasks. And while i am trying to figure this out, the problem has already taken really much time and i haven't still found how to solve this.
At first I show the necessary source code.
- urls.py and the the error url:
path('delete-message/<str:pk>/', views.delete_message, name='delete-message')
- views.py and function where error happens:
@login_required
def delete_message(request, pk):
message = Message.objects.get(id=pk)
room_id = message.room.id
if request.method == 'POST':
message.delete()
return redirect(f'room/{room_id}') ### WHAT DO I HAVE TO DO ???
return render(request, 'delete-message.html')
- delete-message.html and error form:
<form method="POST">
{% csrf_token %}
<h2>
<p>Are you sure you want to delete this message ?</p>
</h2>
<a href="{{request.META.HTTP_REFERER}}">Go Back</a>
<input type="submit" value="Confirm">
</form>
After redirect()
works it sends me to the unexisted url: 127.0.0.1:8000/delete-message/10/room/5
but it had to be http://127.0.0.1:8000/room/5
...
Why is it not as such result as I've expected?
Also I've tried to do this:
- In the views.py I change function where except of redirect I transfer room_id to the template:
@login_required
def delete_message(request, pk):
message = Message.objects.get(id=pk)
room_id = message.room.id
if request.method == 'POST':
message.delete()
return render(request, 'delete-message.html', {'id': room_id})
- In the template delete-message.html I try to redirect back to the room by the "action" attribute:
<form method="POST" action="{% url 'room' id %}">
And this method also return an error:
IntegrityError at /room/5/
NOT NULL constraint failed: BaseApp_message.body
CodePudding user response:
You can use reverse
with url name space init like below :-
urls.py
path('room/<str:pk>/', views.room_message, name='room')
Then in your view will be :-
@login_required
def delete_message(request, pk):
message = Message.objects.get(id=pk)
room_id = message.room.id
if request.method == 'POST':
message.delete()
url = reverse('room', kwargs={'id': room_id})
return HttpResponseRedirect(url)
CodePudding user response:
To redirect to a root-relative URL, add a leading forward slash:
# return redirect(f'room/{room_id}')
return redirect(f'/room/{room_id}')