有UpdateView和ModelForm,你需要将一个变量从视图传递到表单,这里是视图:
class EditBranchView(UpdateView):
model = Branches
template_name = 'branches/edit.html'
form_class=EditBranchForm
def get_context_data(self, *args, **kwargs):
context = super(EditBranchView, self).get_context_data(**kwargs)
if self.request.POST:
context['form'] = EditBranchForm(self.request.POST, instance=self.object, request=self.request, pk = self.kwargs['pk'])
context['phones_form'] = BranchPhonesFormSet(self.request.POST, instance=self.object)
else:
context['form'] = EditBranchForm(instance=self.object, request=self.request, pk = self.kwargs['pk'])
context['phones_form'] = BranchPhonesFormSet(instance=self.object)
return context
和我的表格:
class EditBranchForm(forms.ModelForm):
regions=forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
owner = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Profiles.objects.all())
def __init__(self, request, pk, *args, **kwargs):
super(EditBranchForm, self).__init__(*args, **kwargs)
self.pk = pk
self.request = request
self.fields['owner'].queryset = Profiles.objects.filter(pid=self.request.user.id)
self.fields['regions'].choices = self.request.user.organization.organizationtoregion_set.all().values_list('region__id', 'region__region_name')
但它给出了错误:
init ()至少需要3个参数(给定1个)
我该怎么办?感谢
答案 0 :(得分:0)
您在EditBranchForm.__init__
中处理的参数是错误的。它应该是这样的:
def __init__(self, *args, **kwargs):
self.pk = kwargs.pop('pk', None)
self.request = kwargs.pop('request')
super(EditBranchForm, self).__init__(*args, **kwargs)
user = request.user
self.fields['owner'].queryset = Profiles.objects.filter(pid=user.id)
self.fields['regions'].choices = user.organization \
.organizationtoregion_set.all() \
.values_list('region__id',
'region__region_name')