AndrewIngram/django-extra-views

Using ManyToMany connections for inlines

BedirT opened this issue · 4 comments

Is there any way to use ManytoMany model relations to create inline connected forms? I did achieve using the foreign key but didn't find anything about ManytoMany, if it is not implemented how can I do it manually?

i.e.

models.py

class QLevel(models.Model):
    questions = models.ManyToManyField(Question)
    # qID = models.ForeignKey(Question, on_delete=models.CASCADE)
    level = models.CharField(max_length=16)

views.py

class QLevelInline(LoginRequiredMixin, InlineFormSetFactory):
	model = QLevel
	form_class = questionLevelForm
	factory_kwargs = {'extra': 1, 'max_num': None,
					'can_order': False, 'can_delete': False}

class QuestionCreateView(LoginRequiredMixin, CreateWithInlinesView):
	model = Question
	form_class = questionForm
	inlines = [QLevelInline, QSubjectInline, QMethodInline] 
        #other methods are also there but did not include due to simplicity

	def forms_valid(self, form, inlines):
		form.instance.author = self.request.user
		self.object = form.save()
		for inline in inlines:
			inline.save()
		return super().form_valid(form)

	def get_success_url(self):
		return self.object.get_absolute_url()

Basically it works if I use the fk connected version, but I get error

ValueError at /question/new/
'file.QLevel' has no ForeignKey to 'file.Question'.

I have also this issue...

It's been so long that I don't even remember which project I used this on ;) Otherwise, I would try to help @Manoel8485

@Manoel8485 Have you tried using django.forms.forms.ModelMultipleChoiceField in your regular form? I just used that in a project and it worked well.

Did someone ever figure this out?