扩展django UserCreationForm

时间:2018-04-25 15:46:19

标签: django forms customization

好吧,我扩展了用户:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    sheba = models.DecimalField(max_digits= SHEBA_LENGTH, decimal_places = 0)
    mellicode = models.DecimalField(max_digits=11, decimal_places = 0)

但问题是我们有UserCreationForm用户注册。现在我需要一个新表单来处理添加的字段。我喜欢使用ModelForm从模型创建表单。现在问题是UserCreationForm本身使用ModelFormUser模型创建字段。 ModelForm有一个名为Meta的内部类,它有一个名为model的字段,用于指定应为所需字段读取的模型。我认为应该有办法这样做,因为这是一件普通的事情。

我现在所拥有的不明显原因是:

class SignUpForm(UserCreationForm, ModelForm):
    class Meta(UserCreationForm.Meta):
        model = UserProfile
        fields = ['user','mellicode', 
        'birthdate','residentialaddress','postalcode','sheba','idpic'] 

1 个答案:

答案 0 :(得分:0)

根据这个聪明的you were a bot中的文章,您可以使新的UserProfile模型在使用以下扩展模型创建新用户实例或更新现有实例时自动创建/更新:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    sheba = models.DecimalField(max_digits= SHEBA_LENGTH, decimal_places = 0)
    mellicode = models.DecimalField(max_digits=11, decimal_places = 0)

    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            UserProfile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.user_profile.save()

因为Django允许您在视图中一次处理两个表单,所以您可以使用以下方法解决问题:

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('sheba', 'mellicode')

然后在你的views.py中:

@login_required
@transaction.atomic
def create_user_profile(request):
    if request.method == 'POST':
         user_form = UserForm(request.POST, instance=request.user)
         user_profile_form = UserProfileForm(request.POST, instance=request.user.profile)
         if user_form.is_valid() and user_profile_form.is_valid():
             user_form.save()
             user_profile_form.save()
             messages.success(request, "User successfully created")
         else:
             messages.error(request, "Correct errors")
    else:
        user_form = UserForm(instance=request.user)
        user_profile_form = UserProfileForm(instance=request.user.user_profile)
    return render(request, 'create_profile.html', {
        'user_form': user_form,
        'user_profile_form': user_profile_form
    })

在您的模板中,您将呈现两种形式:

<form method="post">
  {% csrf_token %}
  {{ user_form.as_p }}
  {{ profile_form.as_p }}
  <button type="submit">Save changes</button>
</form>