How to extend UserCreationForm with fields from UserProfile

前端 未结 1 893
野的像风
野的像风 2020-12-20 07:05

I found this post on how to extend the UserCreationForm with extra fields such as \"email.\" However, the email field is already defined in the pre-built user model.

<
相关标签:
1条回答
  • 2020-12-20 07:38

    Add fields as appropriate for your UserProfile model (it's not too easy to use a ModelForm to avoid Repeating Yourself, unfortunately), then create and save a new UserProfile instance in the over-ridden save() function. Adapted from the post you linked to:

    from django import forms
    from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserCreationForm
    
    
    class UserCreateForm(UserCreationForm):
        job_title = forms.CharField(max_length=100, required=True)
        age = forms.IntegerField(required=True)
    
        class Meta:
            model = User
    
        def save(self, commit=True):
            if not commit:
                raise NotImplementedError("Can't create User and UserProfile without database save")
            user = super(UserCreateForm, self).save(commit=True)
            user_profile = UserProfile(user=user, job_title=self.cleaned_data['job_title'], 
                age=self.cleaned_data['age'])
            user_profile.save()
            return user, user_profile
    
    0 讨论(0)
提交回复
热议问题