简体   繁体   English

如何在Django中将子字段添加到ModelForm?

[英]How to add child field to ModelForm in Django?

I'll try to describe the problem as much fast. 我将尽速描述问题。 I have 2 models: 我有2个型号:

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: 我正在尝试使用ModelForm创建CreateView:

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: 如果我的模板看起来像这样,如何从ChildModel放入电话的模板字段:

<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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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