简体   繁体   中英

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 . 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? For example, the User Model contains fields such as first_name , last_name . How would I create a ModelForm that addresses first_name, last_name, age, quantity?

Simply create a model form with

class Meta: 
    model=User

And add any other Form fields you need like IntegerField , ChoiceField , CharField or other.

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