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

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

问题描述

我遇到了一个找不到解决方案的问题.我在导航栏中有一个按钮,它在所有页面上都可用,它是一个负责创建一些内容的按钮.

I face a problem which I can't find a solution for. I have a button in navbar which is available on all pages and it is a button responsible for creating some content.

使用按钮查看链接:

def createadv(request):
    uw = getuw(request.user.username)
    if request.method =='POST':
    form = AdverForm(request.POST, request.FILES)
    if form.is_valid():
        form.instance.user = request.user
        form.save()
        return HttpResponseRedirect('/', {'username': request.user.username, 'uw': uw})
    args = {}
    args.update(csrf(request))
    args['username'] = request.user.username
    args['form'] = AdverForm()
    args['uw'] = uw
    return  render_to_response('createadv.html', args)

如果您现在可以看到,我总是在创建内容后重定向到主页/",但我想返回到我启动内容创建的页面.

If you can see now I always redirect to main page '/' after creating content but I want to go back to the page with which I launched the creation of content.

推荐答案

您可以在表单中添加 next 字段,并将其设置为 request.path.处理完表单后,您可以重定向到此路径的值.

You can add a next field to your form, and set it to request.path. After you processed your form you can redirect to the value of this path.

模板.html

<form method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="hidden" name="next" value="{{ request.path }}">
    <button type="submit">Let's Go</button>
</form>

views.py

next = request.POST.get('next', '/')
return HttpResponseRedirect(next)

如果我没记错的话,这大概是 django.contrib.auth 为登录表单所做的.

This is roughly what django.contrib.auth does for the login form if I remember well.

如果你通过一个中间页面,你可以通过查询字符串传递'next'值:

If you pass through an intermediate page, you can pass the 'next' value via the querystring:

some_page.html

some_page.html

<a href="{% url 'your_form_view' %}?next={{ request.path|urlencode }}">Go to my form!</a>

模板.html

<form method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="hidden" name="next" value="{{ request.GET.next }}">
    <button type="submit">Let's Go</button>
</form>

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆