既根据当前登录人,动态显示对象相关的的select的选项,例如 A登录,只显示A的客户,B登录,只显示B自己的客户
先了解form的ModelChoiceField字段(这个表格没意义,就是引出参数queryset)
class BookForm(forms.Form): title=forms.CharField(max_length=32) price=forms.IntegerField() pub_date=forms.DateField(widget=widgets.TextInput(attrs={"type":"date"})) #publish=forms.ChoiceField(choices=[(1,"AAA"),(2,"BBB")]) publish=forms.ModelChoiceField(queryset=Publish.objects.all()) #单选 authors=forms.ModelMultipleChoiceField(queryset=Author.objects.all()) #多选
默认是显示外键关联表的所有字段,queryset=objects.all()
然后大多数用的是modelform,可以利用field.queryset,动态限制显示对象
class ConsultRecordModel(forms.ModelForm): class Meta: model=ConsultRecord exclude=['delete_status'] def __init__(self,request,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['consultant'].queryset = UserInfo.objects.filter(pk=request.user.pk) self.fields['customer'].queryset = Customer.objects.filter(consultant=request.user) for field in self.fields.values(): field.widget.attrs.update({'class':'form-control'})
把想展示出来的用户,或者顾客,利用request.user,过滤出来 , 然后在赋值给相关字段的queryset( self.fields['consultant'].queryset ),这样,select展示出来的对象就是自己相关的对象了
view视图一定要把request传过来,不然会飘红~~
form = ConsultRecordModel(request, instance=obj)