Reputation: 68
Is it possible to have 2 redirect() in the same django view. so when the like button is in the home page, i want it to redirect back to home page, if like button is in detail page, i want to redirect back to detail page?
For instance:
def LikeView(request, slug):
context = {}
post = get_object_or_404(BlogPost, slug=slug)
post.likes.add(request.user)
if in homepage:
return redirect('HomeFeed:detail', slug=slug)
else:
return redirect('HomeFeed:main')
def delete_blog_view(request,slug):
context = {}
user = request.user
#YOU WANT to check if user is authenticated. if not, you need to authenticate! redirect you to that page
if not user.is_authenticated:
return redirect("must_authenticate")
account = Account.objects.get(pk=user_id)
blog_post = get_object_or_404(BlogPost, slug=slug)
blog_post.delete()
return redirect(request.META.get('HTTP_REFERER', 'account:view', kwargs={'user_id': account.pk }))
Upvotes: 1
Views: 472
Reputation: 1230
Pass the redirect URL in a next
URL param. Like so:
<!-- In homepage template -->
<a href="{% url 'link-to-like-view' %}?next=/home/">Like</a>
<!-- in Detail template -->
<a href="{% url 'link-to-like-view' %}?next=/detail/">Like</a>
or simply:
<a href="{% url 'link-to-like-view' %}?next={{ request.path }}">Like</a>
To always pass the current URL as the redirect URL.
And then in your LikeView
:
def LikeView(request, slug):
...
next = request.GET.get("next", None)
if next and next != '':
return HttpResponseRedirect(redirect_to=next)
# Then have a default redirect URL in case `next` wasn't passed in URL (Home for Example):
return HttpResponseRedirect(redirect_to="/home")
As mentioned in the Django Docs, this isn't safe (for most apps), so you have to check if URL is safe then redirect to next
otherwise just return a default safe in-app URL.
Read on the url_has_allowed_host_and_scheme
function to check if URL is safe on this Docs page
Upvotes: 2