1

我正在使用 UserProfile 来保存我创建的一些字段。它工作正常。但我想创建一个新视图让用户更改(更新)这些字段值。但是,这些价值观并没有以形式表现出来。有人知道如何解决吗?

视图.py

@login_required

    def atualizar_cadastro_usuario(request):    
        if request.method == 'POST':       
            form = cadastrousuarioForm(request.POST,instance=request.user.get_profile())


            if form.is_valid():            
                new_user = form.save()            
                return render_to_response("registration/cadastro_concluido.html",{})
        else:    
            form = cadastrousuarioForm(request.POST,instance=request.user.get_profile())
        return render_to_response("registration/registration.html", {'form': form})

表格.py

class cadastrousuarioForm(UserCreationForm):   
    username = forms.EmailField(label = "Email",widget=forms.TextInput(attrs={'size':'60','maxlength':'75'}))
    email = forms.EmailField(label = "Digite o Email novamente",widget=forms.TextInput(attrs={'size':'60','maxlength':'75'}))
    nome = forms.CharField(label = 'Nome',widget=forms.TextInput(attrs={'size':'30','maxlength':'100'}))
    cpf = BRCPFField(label='CPF')
    data_nascimento=forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=('%d/%m/%Y',))    
    endereco = forms.CharField(label = 'Endereço',widget=forms.TextInput(attrs={'size':'30','maxlength':'100'}))
    cidade = forms.CharField(label = 'Cidade')
    estado = forms.CharField(widget=BRStateSelect(), label='Estado', initial = 'SP') 
    telefone = forms.CharField(label = "Telefone",widget=forms.TextInput(attrs={'size':'12','maxlength':'12'}))
    escolaridade = forms.ChoiceField(choices=UserProfile.ESCOLARIDADE_ESCOLHAS)    
    profissao = forms.CharField(label = 'Profissão')
    empresa = forms.CharField(label = 'Empresa',required=False) 
    receber_emails = forms.ChoiceField(choices=UserProfile.QUESTIONARIO_ESCOLHAS)     
    #captcha = CaptchaField(label = 'Digite as letras a seguir')

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


    def save(self, commit=True):
        user = super(cadastrousuarioForm, self).save(commit=False)  
... 

在 bash 中,它工作正常:

>>> from django.contrib.auth.models import User
>>> from cadastro.models import UserProfile
>>> u = User.objects.get(username='user@gmail.com')
>>> u.get_profile().telefone
u'123123455'
4

1 回答 1

3

您需要将表格中的模型从 更改UserUserProfile。表单还需要子类化ModelForm而不是UserCreationForm. 此外,您似乎只使用了 ModelForm (usernameemail) 中的一部分字段。最后,由于您使用的是 ModelForm,因此您不需要在表单中定义所有模型的字段。尝试将您的更改cadastrousuarioForm为以下内容:

class cadastrousuarioForm(ModelForm):   
    class Meta:
        model = UserProfile
        fields = ('username','email')
    def save(self, commit=True):
        user = super(cadastrousuarioForm, self).save(commit=False)  
于 2011-07-17T01:59:44.257 回答