AndrewIngram / django-extra-views

Django's class-based generic views are awesome, let's have more of them.
MIT License
1.38k stars 172 forks source link

Using ManyToMany connections for inlines #188

Open BedirT opened 5 years ago

BedirT commented 5 years ago

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'.
Manoel8485 commented 4 years ago

I have also this issue...

BedirT commented 3 years ago

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

sdolemelipone commented 3 years ago

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

jkaeske commented 6 months ago

Did someone ever figure this out?