如何在Django中从视图重定向 [英] How can I redirect from view In Django

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

问题描述

这是为我的Django应用发布的视图。问题在于,填写更新表格并提交后,会成功完成。但这会给用户造成混乱,因为那里有相同的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拥有另一个用户的权限,您仅具有读取权限)
return render(request, my_blog / denied.html,{})
else:
form = PostForm(request.POST或None,request.FILES或None,instance = instance)
如果form.is_valid():
instance = form.save(commit = False)
instance.save()
context = { form:form,
instance:instance}

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

谢谢。

解决方案

您可以通过http快捷方式使用重定向



<$来自django.shortcuts的p $ p> 导入重定向

def my_view(request):
...
object = MyModel.objects.get(。 ..)
返回重定向(对象)#或返回重定向('/ some / url /')

这是链接到官方文档。


This is a view written for my posts app in Django. The problem is that after filling the update form and submitting it happens successfully. But it creates confusion for the user because the same HTML page is there and how can I redirect into the updated object?

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)

ThankYou.

解决方案

You can use redirect from http shortcuts.

from django.shortcuts import redirect

def my_view(request):
    ...
    object = MyModel.objects.get(...)
    return redirect(object) #or return redirect('/some/url/')

Here is the link to official docs.

这篇关于如何在Django中从视图重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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