我在模型中使用ManyToManyField
。但是,当我在字段上使用自定义queryset
时,会出现验证错误
Select a valid choice. 2 is not one of the available choices.
因为这一行:
self.fields['user_groups'].queryset = Groups.objects.filter(group_company=self.user_company)
但是当我在没有上面一行的情况下使用它时,它工作得很好。
Forms.py
class ManagerProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['user_company', 'user_groups']
def __init__(self, *args, **kwargs):
self.user_company = kwargs.pop('user_company', None)
super().__init__(*args, **kwargs)
self.fields['user_groups'].queryset = Groups.objects.filter(group_company=self.user_company)
Model.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
user_company = models.ForeignKey(Company, on_delete=models.CASCADE)
user_groups = models.ManyToManyField(Groups,related_name='user_groups')
Views.py
@login_required
def ManagerAddView(request):
if request.method == 'POST':
random_password = User.objects.make_random_password() # generate password here
ur_form = ManagerRegisterForm(request.POST, pwd=random_password)
pr_form = ManagerProfileForm(request.POST, request.FILES)
user_role = ACLRoles.objects.get(acl_role_title='Manager')
if ur_form.is_valid() and pr_form.is_valid():
new_user = ur_form.save(commit=False)
new_user.username = new_user.email
new_user.set_password(random_password)
new_user.save()
profile = pr_form.save(commit=False)
if profile.user_id is None:
profile.user_id = new_user.id
profile.user_role_id = user_role.id
profile.user_company_id = request.user.userprofile.user_company.id
profile.save()
# this is where i am saving groups in my model
for group in request.POST.getlist('user_groups'): # For many to many field
profile.user_groups.add(group)
email= ur_form.cleaned_data.get('email')
messages.success(request, 'Your Account has been created for %s!' % email)
return redirect('admin_managers')
else:
ur_form = ManagerRegisterForm()
pr_form = ManagerProfileForm(user_company=request.user.userprofile.user_company.id)
return render(request, 'admin/manager/managers_form.html', {'ur_form': ur_form, 'pr_form': pr_form})