Combine two models with OneToOne relationship into one form - Django

随声附和 提交于 2019-12-12 01:46:00

问题


I created two custom user models (AbstractBaseUser and a separate for extra information). Is there a way to combine the two models to create one form that the user can use to update all of their information between the two models?

For example, it would be ideal to have something like this (although I know not possible):

class ProfileChangeForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['username', 'email', first_name', 'last_name', 'bio', 'website']

Thank you in advance for your help! The models are below:

MyUser:

class MyUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=30, unique=True)
    email = models.EmailField(max_length=255, unique=True)
    first_name = models.CharField(max_length=120, null=True, blank=True)
    last_name = models.CharField(max_length=120, null=True, blank=True)

UserProfile:

class UserProfile(models.Model):
    user = models.OneToOneField(MyUser)
    bio = models.TextField(null=True, blank=True)
    website = models.CharField(max_length=120, null=True, blank=True)

回答1:


I think you can do something like :

class ProfileChangeForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['user__username', 'user__email', 'user__first_name', 'user__last_name', 'bio', 'website']


来源:https://stackoverflow.com/questions/31323497/combine-two-models-with-onetoone-relationship-into-one-form-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!