[英]How to create single ModelForm for two models that are related by a Foreign Key?
I have two models: User
(defined by Django) and UserProfile
. 我有两个模型: User
(由Django定义)和UserProfile
。 The two are connected by a ForeignKey: 两者通过外键连接:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
age = forms.IntegerField(required=True)
quantity = forms.IntegerField(required=True)
How do I create a Form/ModelForm
that contains properties for fields from both models? 如何创建包含两个模型的字段属性的Form/ModelForm
? For example, the User Model contains fields such as first_name
, last_name
. 例如,用户模型包含诸如first_name
, last_name
字段。 How would I create a ModelForm
that addresses first_name, last_name, age, quantity? 我将如何创建一个用于处理ModelForm
, ModelForm
,年龄,数量的ModelForm
?
Simply create a model form with 只需使用以下命令创建模型表单
class Meta:
model=User
And add any other Form fields you need like IntegerField , ChoiceField , CharField or other. 并添加您需要的其他任何Form字段,例如IntegerField , ChoiceField , CharField或其他。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.