如何在Django中使用return redirect作为回调函数



我一整天都在努力让我的代码正常工作。我有一个视图函数,但它太冗长了,而且我正试图在另一个视图上使用它的实现,所以我正试图重构代码,使该函数能够在另一种视图中运行。除了函数中有一个具有配置文件名称的return redirect(它只是一个普通函数,而不是视图函数(之外,我已经能够使函数工作。每次我试图通过将重定向作为回调函数传递来运行代码时,它总是会产生HttpRedirectError,并显示对象在内存中的位置,我如何使用返回重定向作为回调,或者以任何方式让它与我的代码一起工作。功能代码:

def foo(filter,images,request,redirector):
#do something
return redirect(redirector)

视图代码:

if something:  
foo(filter,images,request,'home')

对于视图也尝试过:

def redirector():
return 'home'
foo(property,images,request,redirector)

有什么方法可以让它工作吗?如果我不能让它工作,就必须为另一个函数重复不必要的代码。

在提出解决方案之前,我必须说,您似乎对这里的基本python缺乏了解,并发明了一些奇怪的方法来构建Django视图。您需要回顾函数是如何操作的,return语句的含义等等

首先,Django视图只是一个接受请求对象并返回响应对象的函数。在其中运行一个辅助函数是完全可以的,您可以将它放在helpers.py或任何对您有意义的文件中。但你为什么让它返回重定向?你似乎只是把自己的任务复杂化了。

让我们举一个非常简单的例子。假设您希望视图使用助手从自己的图库中找到用户最喜欢的图片


# picture model
class Picture(models.Model):
# correct way to refer user model for your project
owner = models.ForeignKey(settings.AUTH_USER_MODEL)  
rating = models.PositiveSmallIntegerField(default=5)
# image file field
img = models.ImageField()  
# helper function - find a picture with highest rating from a queryset
def get_favourite_picture(picture_qs):
# order queryset by rating descending
picture_qs = picture_qs.oreder_by('-rating') 
# select first item 
picture = picture_qs.first()  
# return from function only the picture object as result
return picture  
# view
def redirect_to_favourite(request):
# it's how you get pictures where owner is current user
picture_qs = request.user.picture_set.all()
# let function handle just getting a pic
picture = get_favourite_picture(picture_qs)
# and let the view handle the redirect (return redirect response)
# to the view that shows a single image by it's PK (Primary Key - an id)
return redirect("picture_detail", kwargs={'pk': picture.pk})  

最新更新