python - 如何在 Django 中从一个 View 重定向到另一个 View

标签 python python-3.x django redirect django-views

这是在 Django 中为我的帖子应用编写的 View 。问题是在填写更新表单并成功提交后。但这会给用户带来困惑,因为存在相同的 HTML 页面,我如何才能重定向到更新后的对象?

def post_update(request,id=None):
    instance=get_object_or_404(Post,id=id)
    if instance.created_user != request.user.username :
        messages.success(request, "Post owned by another user, You are having read permission only")
        return render(request,"my_blog/denied.html",{})
    else :  
        form=PostForm(request.POST or None,request.FILES or None,instance=instance)
        if form.is_valid():
            instance=form.save(commit=False)
            instance.save()
        context={ "form":form,
                  "instance":instance }

        return render(request,"my_blog/post_create.html",context)

最佳答案

正如@mdegis 已经建议的那样,您可以使用 Django 重定向功能重定向到另一个 View 或 url。

from django.shortcuts import redirect

def view_to_redirect_to(request):
    #This could be the view that handles the display of created objects"
    ....
    perform action here
    return render(request, template, context)

def my_view(request):
    ....
    perform form action here
    return redirect(view_to_redirect_to)

阅读更多关于重定向的信息 herehere

您可以使用 reverse() 方法和您要重定向到的 View 的命名 url 将位置或关键字参数传递给重定向快捷方式。

在 urls.py 中

from news import views

url(r'^archive/$', views.archive, name='url_to_redirect_to')

在 views.py 中

from django.urls import reverse

def my_view(request):
    ....
    return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value}))

更多关于反向 Here

关于python - 如何在 Django 中从一个 View 重定向到另一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42614172/

相关文章:

python - Sklearn ROC AUC 分数 : ValueError: y should be a 1d array, 得到了一个形状数组 (15, 2)

python - 写入 csv 时如何保留空值

Django:将授权用户导入模型

python - django 日志记录 - 仅记录警告和错误

python paho mqtt 客户端连接通过 ssl/tls 给出错误

python - 限制 Atom 中的行长度

python-3.x - 每当从 PyQt5 迁移到 Pyside2 后调用 QFileDialog 时,QThread 关闭

algorithm - 对超集进行分区并获取每个分区的原始集列表

Django - 扩展 LogEntry

python - 计算Python程序的行数