简体   繁体   中英

How to add child field to ModelForm in Django?

I'll try to describe the problem as much fast. I have 2 models:

class ParentModel(models.Model):
    name = models.CharField(max_length = 30)
    surname = models.CharField(max_length = 30)
class ChildModel(models.Model):
    pid = models.ForeignKey(ParentModel)
    phone = models.CharField(max_length=10, validators=[RegexValidator(r'[0-9]{10}', 'invalid number',)],)

I'm trying to create CreateView with ModelForm:

class NewBranchForm(forms.ModelForm):
    def __init__(self, request, *args, **kwargs):
    self.request = request
    super(NewBranchForm, self).__init__(*args, **kwargs)
    class Meta:
        model = ParentModel
        fields = ['name', 'surname']
     def save(self):
         ...

How can i put to template fields for phone from ChildModel, if my template looks so:

<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}<br>
<input type="submit" value="Create new branch" />

Thanks and sorry for my English, it's not my native language

您应该为电话创建一个ModelFormset

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