I am creating a function of adding friend to a user's friend list. After a user click the button, the friendship will be created and the page should be redirected to where the user was. For instance, I want to add another user in the first page in the forum, I should stay in the same page after I click the "add friend" button.
This is how I design it: When I redirect to any page of the forum, I pass the path of the current page as a variable in the page:
def to_post_page(request, post_id, page_nr):
post = get_object_or_404(Post, id=post_id)
form = CommentForm()
comments = Comment.objects.filter(post=post)
return render(request, 'post/post.html', {
'post': post,
'form': form,
'comments': comments,
'page_nr': int(page_nr),
'user': request.user,
'path': request.path,
})
And in the template:
<input type="button" class="btn btn-info" value="Add Friend" onclick="location.href='{% url 'user:add_friend' to_friend_id=post.poster.id path=path %}';">
@login_required(login_url='user:login')
def friend_add(request, to_friend_id, path):
friend = get_object_or_404(User, id=to_friend_id)
if friend == request.user:
return HttpResponseRedirect(request.path)
friendship = FriendShip(
from_friend=request.user,
to_friend=friend
)
try:
friendship.save()
except IntegrityError:
return path
finally:
return path
My url looks like this:
url(r'^add_friend/(?P<to_friend_id>[0-9]+/)/(?P<path>[\w\-]+)/$', views.friend_add, name="add_friend"),
It raises an exception:
Reverse for 'add_friend' with keyword arguments '{'to_friend_id': 1, 'path': '/forum/1/0/post'}' not found. 1 pattern(s) tried: ['users/add_friend/(?P[0-9]+/)/(?P[\w\-]+)$']
Can any body explain me why the exception is raised and what is the solution? Isn't \w designed for string parameter?
And I think my way to redirect to the previous page is not very smart. Does any one have a better way?
Really thanks a lot!
The question is not duplicated to this question because he is using a form but I am not. I have no way to get a POST