更具体地说,我需要访问表单对象的 init 方法中的请求对象。这是我的代码:
class TagNamesField(forms.CharField):
def __init__(self, user=None, *args, **kwargs):
super (TagNamesField,self).__init__(*args,**kwargs)
self.required = True
self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
self.max_length = 255
self.label = _('tags')
#self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
self.help_text = _('Tags are short keywords, with no spaces within. At least %(min)s and up to %(max)s tags can be used.') % {
'min': settings.FORM_MIN_NUMBER_OF_TAGS, 'max': settings.FORM_MAX_NUMBER_OF_TAGS
}
self.initial = self.request.session['previous_url']
self.user = user
基本上,我想初始化此表单:self.initial = self.request.session['previous_url']
有什么想法吗?谢谢!
答案 0 :(得分:1)
表单和小部件与请求信息按设计分离。做你想做的事的简单方法是以这种方式在视图中实例化一个表单:
form = SomeForm(initial={'tags': self.request.session['whatever']})
但是,创建自定义表单接受request
作为额外参数(给表单类访问)可能更合适:
form = SomeForm(request=request)