当我创建一个新公司时,我可以添加用户而不会出现任何错误。但是,当我尝试更新公司时,我选择了默认用户已经使用initial
with 字段(我不确定这是一个好方法)。我收到此错误
选择一个有效的选项。3 不是可用的选择之一
我认为我的默认选择方法不好。
模型.py
class CustomUser(models.Model):
username = models.CharField(max_length=20)
...<fields>....
firm = models.ForeignKey(
'Firm',
null = True,
blank = True,
on_delete = models.Set_NULL,
related_name = 'users'
)
class Firm(models.Model):
firm_name = models.CharField(max_length=20)
.....<fields>.....
表格.py
class FirmAdminForm(forms.ModelForm):
users = forms.ModelMultipleChoiceField(
widget = FilteredSelectMultiple('username', is_stacked=False),
queryset=User.objects.exclude(is_staff=True).filter(firm=None),
required=False,
)
class Meta:
model = Firm,
fields = [...<other fields>, 'users']
def save(self, commit=True):
# Save the provided password in hashed format
firm = super().save(commit=False)
users = self.cleaned_data['users']
firm.users.set(users)
return firm
管理员.py
class FirmAdmin(admin.ModelAdmin):
form = FirmAdminform
...other codes .....
def render_change_form(self, request, context, add, change, form_url, obj):
users = SalesToolUser.objects.exclude(is_staff=True).filter(partner_firm=None)
if obj:
partner_agents = obj.users.all()
users = User.objects.exclude(is_staff=True).filter(Q(firm=None)|Q(firm=obj))
context['adminform'].form.fields['users'].initial = partner_agents
context['adminform'].form.fields['users'].queryset = users
return super().render_change_form(request, context, add=add, change=change, form_url=form_url, obj=obj)