how to return redirect to previous page in Django

2020-07-30 06:31发布

问题:

I'm coding a news website,in the detail news page ,there is a comment fountain,if people want to post comment they need to login first.And I want to make it that,after they login in successfully ,the page can return to previous news page.

Here is my views.py:

def newsDetailView(request, news_pk):
    news = News.objects.get(id=news_pk)
    title = news.title
    author = news.author_name
    add_time = news.add_time
    content = news.content
    category = news.category
    tags = news.tag.annotate(news_count=Count('news'))

    all_comments = NewsComments.objects.filter(news=news)

    comment_form = CommentForm(request.POST or None)

    if request.method == 'POST' and comment_form.is_valid():
        comments = comment_form.cleaned_data.get("comment")
        comment = NewsComments(user=request.user, comments=comments, news=news)
        comment.save()

    return render(request, "news_detail.html", {
        'title': title,
        'author': author,
        'add_time': add_time,
        'content': content,
        'tags': tags,
        'category': category,
        'all_comments': all_comments,
        'comment_form': comment_form
    })

Here is my news_detail.html:

                    {% if user.is_authenticated %}
                        <form method="POST" action="">{% csrf_token %}
                            <div class="form-group">
                                <label for="exampleFormControlTextarea1"><h5>评论 <i class="fa fa-comments"></i></h5>
                                </label>
                                <textarea id="js-pl-textarea" class="form-control" rows="4"
                                          placeholder="我就想说..." name="comment"></textarea>
                                <div class="text-center mt-3">
                                    <input type="submit" id='js-pl-submit' class="btn btn-danger comment-submit-button" value="Submit Comemmt">
                                    </input>
                                </div>
                            </div>
                        </form>


                    {% else %}   
                   <span>Please Login or register first</span>                         
                            <a class="btn btn-primary mb-5"
                                                         href="{% url 'login' %}?next={{ request.path }}">登录</a>
                        <a class="btn btn-danger mb-5" href="{% url 'register' %}?next={{ request.path }}">注册</a>

                    {% endif %}

Here is my LoginView:

class LoginView(View):

def get(self, request):
    return render(request, "login.html", {})

def post(self, request):
    login_form = LoginForm(request.POST)
    if login_form.is_valid():
        user_name = request.POST.get("username", "")
        pass_word = request.POST.get("password", "")
        user = authenticate(username=user_name, password=pass_word)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
            else:
                return render(request, "login.html", {"msg": "用户未激活!"})
        else:
            return render(request, "login.html", {"msg": "用户名或密码错误!"})
    else:
        return render(request, "login.html", {"login_form": login_form})

And I have a login.html and register.html.They works very well.

Anybody know how to make it in my particular case?Thank you so much!

回答1:

return HttpResponseRedirect(request.META.get('HTTP_REFERER')) will return you to the page that called the current function.



回答2:

You send the the current path via next parameter

<span>Please Login or register first</span>                         
    <a class="btn btn-primary mb-5" href="{% url 'login' %}?next={{ request.path }}">登录</a>
    <a class="btn btn-danger mb-5" href="{% url 'register' %}?next={{ request.path }}">注册</a>
</span>

so in your loginView or RegisterView;

retrieve the parameter next once you're done with all the processes, and you are ready to redirect the user, for instance it can be after submitting a form.

from django.core.urlresolvers import resolve, Resolver404
from django.http import HttpResponseRedirect
from django.shortcuts import redirect

url = request.GET.get("next")
try:
    resolve(url)
    return HttpResponseRedirect(url)
except Resolver404: # Make sure the url comes from your project
    return redirect("default_view") # A default view


回答3:

First:

def login(request):
    if request.method == 'GET':
    request.session['login_from'] = request.META.get('HTTP_REFERER', '/')

Second:

if request.method == 'POST':
    #TODO: 
    #Redirect to previous url
    return HttpResponseRedirect(request.session['login_from'])