Также в моём коде есть баг. Модель создаётся сразу при загрузке страницы, а не при сабмите. Заранее спасибо.
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)