简体   繁体   English

如何为由外键关联的两个模型创建单个ModelForm?

[英]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_namelast_name字段。 How would I create a ModelForm that addresses first_name, last_name, age, quantity? 我将如何创建一个用于处理ModelFormModelForm ,年龄,数量的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字段,例如IntegerFieldChoiceFieldCharField或其他。

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

相关问题 如何为通过外键关联的两个模型创建单个表单? - How to create single Form for two models that are related by a Foreign Key? Django ModelForm - 使用外键创建实例 - Django ModelForm - Create instance with foreign key 如何使用 Django 在 HTML 中显示外键相关模型字段值? - How to display Foreign Key related models fields values in HTML with Django? 如何在单个模板中呈现两个模型的内容,其中一个模型由外键通过 django 中的另一个模型链接? - How to render contents of two models in a single template where one model is linked by Foreign Key through another in django? 两种模式的外键可能性 - Foreign Key Possibility of Two Models Django如何将外键传递到ModelForm字段 - Django how to pass foreign key into ModelForm field 带有外键的 Django ModelForm - Django ModelForm with foreign key 如何建立一个具有不同模型的两个外键关系的模型 - How to make a model having two foreign Key relations with the different models 使用ModelForm从模型创建表单,模型有许多外键(一个类是另一个的外键。) - Make a form from models using ModelForm, Models have many Foreignkeys( one class is the foreign key for the other.) 在单个get()请求中显示两个相关模型 - Displaying two related models in a single get() request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM