简体   繁体   中英

Django: Creating multiple class instances on a single webpage, with Foreign Key dependencies

I have the following code in my models.py :

class Application(models.Model):
    team_name = models.CharField(max_length=100)
    ...

class Participant(models.Model):
    name  = models.CharField(max_length=100)
    grade = models.SmallIntegerField(choices=GRADE_CHOICES, blank=True, null=True)
    application = models.ForeignKey(Application, related_name="participants")
    ...

ie There are multiple Participants , and each Participant will be on a single application. (It is defined that each Application will have exactly 8 Participants ).

The intended purpose of this code is that a user will be able to create a new application, on which he/she will name 8 Participants . When the Application is created, 8 new instances of Participants should also be created and linked such that each Participant has the newly created Application as its Foreign Key.

I am currently struggling to create a form/view that will handle this creation process. I want the user to be a presented a single webpage that presents input forms that allow the user to create a new Application (name, etc.), along with 8 new Participants (each having a name, grade, etc.)

My current forms.py has:

class ApplicationForm(forms.ModelForm):
    """
    A form that edits an application and all of its participants.
    """

    nationality = forms.CharField(disabled=True, required=False)

    class Meta:
        model = Application
        fields = '__all__'

But I realize that this does not display to the user what is needed to create 8 new Participants with the creation of this Application . How can I modify my forms.py to include space for the user to create 8 Participants with the creation of an Application ?

The only solution I can come up with is to manually list 8 Participant form calls in a single view, but I feel that there must be a better solution.

What you are looking for is django formsets

A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid. Let's say you have the following form:

There is also a ModelFormSet

Like regular formsets, Django provides a couple of enhanced formset classes that make it easy to work with Django models.

These can be used to create several instances of a given model in a single page. The only trouble is that it has a bit of a learning curve and the user experience isn't as great as what you might get with Angular or React.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM