如何在 POST 请求后返回重定向到 Django 中的上一页 [英] how to return redirect to previous page in Django after POST request

查看:27
本文介绍了如何在 POST 请求后返回重定向到 Django 中的上一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的views.py:

def newsDetailView(request, news_pk):新闻 = News.objects.get(id=news_pk)标题 = 新闻.标题作者 = news.author_nameadd_time = news.add_time内容 = 新闻.内容类别 = 新闻.类别标签 = news.tag.annotate(news_count=Count('news'))all_comments = NewsComments.objects.filter(news=news)comment_form = CommentForm(request.POST or None)如果 request.method == 'POST' 和 comment_form.is_valid():评论 = comment_form.cleaned_data.get("评论")评论=新闻评论(用户=request.user,评论=评论,新闻=新闻)评论.保存()返回渲染(请求,news_detail.html",{'标题':标题,'作者':作者,'添加时间':添加时间,'内容':内容,标签":标签,类别":类别,'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><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"></输入>

</表单>{% 别的 %}<span>请先登录或注册</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>{% 万一 %}

这是我的登录视图:

class LoginView(View):def get(self, request):返回渲染(请求,login.html",{})def post(self, request):login_form = LoginForm(request.POST)如果 login_form.is_valid():user_name = request.POST.get("用户名", "")pass_word = request.POST.get("密码", "")用户 = 认证(用户名=用户名,密码=密码)如果用户不是无:如果 user.is_active:登录(请求,用户)返回 HttpResponseRedirect(request.META.get('HTTP_REFERER'))别的:return render(request, "login.html", {"msg": "用户未激活!"})别的:return render(request, "login.html", {"msg": "用户名或密码错误!"})别的:返回渲染(请求,login.html",{login_form":login_form})

我有一个 login.html 和 register.html.它们运行良好.

有人知道如何在我的特定情况下制作吗?非常感谢!

解决方案

第一:

def 登录(请求):如果 request.method == 'GET':request.session['login_from'] = request.META.get('HTTP_REFERER', '/')

第二:

if request.method == 'POST':#去做:#重定向到上一个网址返回 HttpResponseRedirect(request.session['login_from'])

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!

解决方案

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'])

这篇关于如何在 POST 请求后返回重定向到 Django 中的上一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆