我有一些问题。我想以django形式提出请求但可能有一些问题。这是我的代码。 forms.py
class PostForm(forms.ModelForm):
CHOICES = request.user.fields()
receive_user = fields.MultipleChoiceField(choices=CHOICES)
content = forms.CharField(widget=PagedownWidget(show_preview=False))
publish = forms.DateField(widget=forms.SelectDateWidget)
class Meta:
model = Post
fields = [
"receive_user",
"content",
]
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(MyForm, self).__init__(*args, **kwargs)
和views.py
def post_create(request):
if not request.user.is_authenticated():
raise Http404
form = PostForm(request.POST or None, request=request)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
并且错误消息是
NameError:未定义名称“请求”
答案 0 :(得分:0)
request
传递给__init__
方法,因此仅在那里可用。你不能在模块级别使用它,因为它没有在那里定义;无论如何,你不会想要,因为模块级别的任何东西都是在首次导入类时运行一次,而不是在实例化表单时运行。
但是因为你在init中有它,你应该在那里使用它:
class PostForm(forms.ModelForm):
receive_user = fields.MultipleChoiceField(choices=())
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(MyForm, self).__init__(*args, **kwargs)
self.fields['receive_user'].choices = request.user.....
(注意,我怀疑.fields()
是你想要的,但没关系。)