首页 > 解决方案 > POST请求后如何在Django中返回重定向到上一页

问题描述

我正在编写一个新闻网站,在详细新闻页面中,有一个评论喷泉,如果人们想发表评论,他们需要先登录。我想让他们登录成功后,页面可以返回到上一个新闻页面。

这是我的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
    })

这是我的 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 %}

这是我的登录视图:

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

我有一个 login.html 和 register.html。它们工作得很好。

有人知道如何在我的特殊情况下做到这一点吗?非常感谢!

标签: djangodjango-modelsdjango-formsdjango-templatesdjango-views

解决方案


第一的:

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

第二:

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

推荐阅读