我有一个模型以及基于该模型的ModelForm . ModelForm包含一个ModelMultipleChoice字段,我在ModelForm的子类中指定:
class TransactionForm(ModelForm):
class Meta:
model = Transaction
def __init__(self, *args, **kwargs):
super(TransactionForm, self).__init__(*args, **kwargs)
self.fields['category'] = forms.ModelChoiceField(queryset=Category.objects.filter(user=user))
如您所见,我需要按用户过滤Category queryset . 换句话说,用户应该只在下拉列表中看到自己的类别 . 但是,当用户,或者更具体地说,request.user在Model实例中不可用时,我该怎么做呢?
Edit: 添加我的CBV子类:
class TransUpdateView(UpdateView):
form_class = TransactionForm
model = Transaction
template_name = 'trans_form.html'
success_url='/view_trans/'
def get_context_data(self, **kwargs):
context = super(TransUpdateView, self).get_context_data(**kwargs)
context['action'] = 'update'
return context
我尝试了 form_class = TransactionForm(user=request.user)
并且我收到一个NameError,说没有找到请求 .
1 回答
您可以在视图中传递
request.user
以形成init:并添加
user
参数以形成__init__
方法(或从表单中的kwargs
弹出):update: 在基于类的视图中,您可以在
get_form_kwargs
中添加额外的参数以形成init: