我有一个包含许多字段的Modelformset。 M2M字段呈现为ModelMultipleChoiceField。
填写所有表格后,整个程序运行正常。
简而言之,我收到的唯一用户输入来自表单集每种形式上的复选框。还有其他字段,但它们预先填充了用户数据。
我想保存选中复选框的表单,而忽略没有选择的表单。
我能够获取部分填写的表单以通过验证,因此所有表单都得以保存,但是我很难编写一个测试以放弃部分填写的表单(我们没有选择任何复选框的表单) 。
Models.py
customer_id = models.ForeignKey(CustomerDB, on_delete=models.CASCADE, default=None)
services_manytomany = models.ManyToManyField(ContractorServices, blank=True)
class ContractorServices(models.Model):
service_parent = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
service_name = models.CharField(max_length=150, null=True, blank=True)
archive = models.BooleanField(default=False, null=True)
def __str__(self):
return self.service_name
forms.py
services_manytomany = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
queryset=ContractorServices.objects.all()
)
def __init__(self, user, *args, **kwargs):
super(AddJob, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_show_labels = False
self.helper.form_show_errors = True
self.helper.form_tag = False
self.fields['services_manytomany'].required = False
if user is not None:
self.fields['services_manytomany'].queryset = ContractorServices.objects.filter(service_parent=user)
class Meta:
model = Jobs_DB
fields = {'services_manytomany', 'frequency'}
相关的view.py代码
formset = job_formset(queryset=Jobs_DB.objects.none(), form_kwargs={'user': request.user})
if request.method == 'POST':
form_a = AddJob(request.user, request.POST)
formset = job_formset(request.POST, form_kwargs={'user': request.user})
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances:
instance.customer_id = CustomerDB.objects.get(pk=customer_id)
instance.save()
formset.save_m2m()