这是在 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)
您可以使用 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/