1

我是 Django 和 Python 的新手...我正在尝试制作自己的注册表单以添加一些额外的字段(按照关于 Profiles 的文档)...我测试时一切正常,但保存后,附加字段不'不保存,没有错误,只是不保存,只创建用户......但是如果我在 create_profile 函数上手动编写一些值,它会正确保存.. 我如何将字段从我的 UserCreateForms 传递到 create_profile 例程?

对不起我的英语,谢谢你的帮助,我参与了一个小项目来学习,我因为这个细节而停下来..:S

楷模

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    cedula_de_identidad = models.CharField(max_length=9)

    def create_profile(sender, instance, created, **kwargs):
        if created:
            UserProfile.objects.create(user=instance, cedula_de_identidad='If I write here it's saved correctly')

    post_save.connect(create_profile, sender=User)

形式

class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True)
    cedula_de_identidad = forms.CharField(required=True)

    class Meta:
        model = User
        fields = ("email", "username", "password1", "password2")

    def clean_username(self):
        username = self.cleaned_data['username']
         # if not re.search(r'^\w+$', username):
         # raise forms.ValidationError('Username can contain only alphanumeric characters')
        try:
            User.objects.get(username=username)
        except ObjectDoesNotExist:
            return username
        raise forms.ValidationError('Username is already taken')

    def save(self, *args, **kwargs):
        user = super(UserCreateForm, self).save(*args, **kwargs)
        profile = UserProfile()
        profile.user = user
        profile.cedula_de_identidad = self.cleaned_data['cedula_de_identidad']
        profile.save
        return profile

意见

def nuevo_usuario(request):
    if request.method == 'POST':
        formulario = UserCreateForm(request.POST)
        if formulario.is_valid():
            formulario.save()
            return HttpResponseRedirect('/')
    else:
        formulario = UserCreateForm()
    return render_to_response('nuevousuario.html', {'formulario': formulario}, context_instance=RequestContext(request))

我正在使用 Python 2.7 和 Django 1.4 .. 问候,

4

0 回答 0