Django表单向导:done()方法中未定义全局名称'request

3 投票
1 回答
2213 浏览
提问于 2025-04-18 11:57

我正在使用 Django 的表单向导,这个向导需要一个叫做 done 的方法。

def done(self, form_list, **kwargs):
    #Making an instance of Location
    location = Location(    
        manager = User.objects.get(username=request.user.username)
        #more stuff
    )

但是我遇到了以下错误:

global name 'request' is not defined on line (the line with manager assignment)

我不太确定该怎么解决这个问题。我是不是应该把请求(request)放进 done 方法里?这样做有意义吗?其他人是怎么处理这个的呢?

1 个回答

4

在基于类的视图和表单向导中,你可以把request当作self.request来使用。你可以把你的代码改成这样:

location = Location(             #-------v
    manager = User.objects.get(username=self.request.user.username)
    #more stuff
)

撰写回答