Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

python - Django Views, having 2 redirects in 1 view

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 }))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...