Home>

In Django, there was a point that cannot be solved by inserting a table into a DB using forms
I would like to hear from you

I'd like to use forms to enter values ​​and insert data, including related tables

When there is a model like the following models.py heading, the user wants to display the following form
・ Enter the name of Projects
・ Select names of members linked to Projects (multiple selection possible)

For example, if you select two members
Add 1 record to the Project table and
This is an image of adding two records to the ProjectMember table linked to Project

models.py
class Projects (models.Model):
    name = CharField (max_length = 255)
class ProjectMembers (models.Model):
    project = models.ForeignKey (Projects, on_delete = models.PROTECT)
    user = models.ForeignKey (Users, on_delete = models.PROTECT)
Environment

・ Python-3.6
・ Django-2.0.4
・ PostgreSQL-10.3

  • Answer # 1

    Self-solved

    By using inlineformset_factory (), relation destination data can be displayed in form and saved in DB

    from django import forms
    from .models import Projects, ProjectMembers
    class ProjectForm (forms.modelForm):
        class Meta:
            model = Projects
            fileds = ("name")
    ProjectMembersFormSet = forms.inlineformset_factory (
        parent_model = Projects,
        model = ProjectMembers,
        extra = 1,
        fields = ("user"),
        form = ProjectForm
    )
    from django.shortcuts import render
    from django.views import View
    from .forms import ProjectsForm, ProjectMembersFormSet
    class Projects (View):
        def get (self, request):
            project_form = ProjectsForm ()
            project_member_forms = ProjectMembersFormSet ()
            return render (request, 'index.html',
                          {"project_form": project_form,
                           "project_member_forms": project_member_forms})
    <form method = "POST">
      {{project_form.as_p}}
      {{project_member_forms.as_p}}
      <input type = "submit" value = "save">
    </form>