Здравствуйте! Помогите разобраться.
Есть модель Requirement с двумя полями (function, program) типа данных
ManyToManyField. Для поля
function в forms использовал
ModelChoiceField, а для поля
program использовал
ModelMultipleChoiceField. Другими словами пользователь может через форму добавить одну функцию и несколько программ. Не получается сохранить данные из формы. Что я упустил и почему метод
save_m2m() не срабатывает?
modals.py:class Requirement(models.Model):
group_requirement = models.ForeignKey(GroupRequirement, on_delete=models.CASCADE)
function = models.ManyToManyField("Function")
program = models.ManyToManyField('Program')
forms.py:class RequirementForm(forms.ModelForm):
function = forms.ModelChoiceField(widget=Select2Widget(), queryset=Function.objects.none())
program = forms.ModelMultipleChoiceField(widget=Select2MultipleWidget(), queryset=Program.objects.none())
class Meta:
model = Requirement
fields = ('function', 'program')
def __init__(self, all_functions, all_programs, *args, **kwargs):
super(RequirementForm, self).__init__(*args, **kwargs)
self.fields['function'].queryset = all_functions
self.fields['program'].queryset = all_programs
views.py:def requirement_add(request, project_id, group_requirement_id):
group_requirement = get_object_or_404(GroupRequirement, pk=group_requirement_id)
all_functions = Function.objects.filter(project=project_id)
all_programs = Program.objects.filter(project=project_id)
if request.method == 'POST':
requirement_form = RequirementForm(data=request.POST, all_functions=all_functions, all_programs=all_programs)
if requirement_form.is_valid():
requirement = requirement_form.save(commit=False)
requirement.group_requirement = group_requirement
requirement.save()
requirement_form.save_m2m()
ERROR:Traceback (most recent call last):
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 1397, in requirement_add
requirement_form.save_m2m()
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\models.py", line 436, in _save_m2m
f.save_form_data(self.instance, cleaned_data[f.name])
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\related.py", line 1573, in save_form_data
getattr(instance, self.attname).set(data)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 928, in set
objs = tuple(objs)
TypeError: 'Function' object is not iterable