There are 2 models - "RelationType" and "RelationRequest" . The second model is connected with the first through MTM .

Is there форма мультиселекта select форма мультиселекта based on a list of “relationship types”. Do you need to create several models when submitting, depending on the selected items of the multi-select?

Those. If "husband / wife / son" is chosen, 3 models must be created accordingly. Distinctive in them will be only the types of relationships.

The form is valid, the correct values ​​come.

But so far only one model is being created, with lists of all selected relationship types.

Also in my code there is a bug . The model is created immediately when the page is loaded, not when it is submitted.

Thank you in advance.

models.py

 class RelationType(models.Model): title = models.CharField(max_length=40) def __unicode__(self): return self.title class RelationRequest(models.Model): creator = models.ForeignKey(User, related_name='creator') #инициатор relation = models.ForeignKey(User, related_name='relation') #с кем установлена связь type_of_relation = models.ManyToManyField(RelationType, related_name='type_relation', verbose_name=_('type_relation')) status = models.BooleanField(_('status'), default=False) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) 

html

 <form action="" method="POST" multiple="multiple"> {% csrf_token %} {{ relation_form.type_of_relation }} <input type='submit' value='ok'> </form> 

forms.py

 class RelationRequestForm(forms.ModelForm): '''Forming relations request''' class Meta: model = RelationRequest fields = ('type_of_relation',) widgets = { 'type_of_relation': forms.SelectMultiple( attrs={ 'class': 'select2', 'style': 'width: 235px', } ), } def __init__(self, *args, **kwargs): super(RelationRequestForm, self).__init__(*args, **kwargs) self.fields['type_of_relation'].empty_label = None self.fields['type_of_relation'] = forms.ModelMultipleChoiceField(queryset=RelationType.objects.all()) def clean(self): type_of_relation = self.cleaned_data.get('type_of_relation') 

views.py

 def post(self, request, *args, **kwargs): self.object = self.get_object() relation_form = RelationRequestForm(request.POST) if relation_form.is_valid(): req_rel = relation_form.save(commit=False) req_rel.creator = request.user relation_user_id = int(filter(lambda x: x.isdigit(), request.path)) req_rel.relation = User.objects.get(id = relation_user_id) req_rel.save() relation_form.save_m2m() context = self.get_context_data(relation_form = relation_form) return self.render_to_response(context) 

Or tell me which way to dig at least, otherwise I stay in a small stupor.

There is a thought to do through an intermediate model, and from it already pull out. But it seems to me that there is a better option.

    0