Django:通过表单更改用户配置文件

发布于 2024-11-24 20:08:35 字数 2613 浏览 0 评论 0原文

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

view.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})

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='[email protected]')
>>> u.get_profile().telefone
u'123123455'

I am using UserProfile to save some fields that I created. Its working fine. But I would like to create a new view to let user change (update) theses fields values. But, theses values arent being showing in form. Anyone have any idea how to fix it?

view.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})

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)  
... 

In bash, it works fine:

>>> from django.contrib.auth.models import User
>>> from cadastro.models import UserProfile
>>> u = User.objects.get(username='[email protected]')
>>> u.get_profile().telefone
u'123123455'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

有深☉意 2024-12-01 20:08:35

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

class cadastrousuarioForm(ModelForm):   
    class Meta:
        model = UserProfile
        fields = ('username','email')
    def save(self, commit=True):
        user = super(cadastrousuarioForm, self).save(commit=False)  

You need to change your model in the form from User to UserProfile. The form also needs to subclass ModelForm rather than UserCreationForm. Also, it looks like you're only using a subset of fields in your ModelForm (username and email). Finally, since you're using a ModelForm you don't need to define all of the model's fields in your form. Try changing your cadastrousuarioForm to the following:

class cadastrousuarioForm(ModelForm):   
    class Meta:
        model = UserProfile
        fields = ('username','email')
    def save(self, commit=True):
        user = super(cadastrousuarioForm, self).save(commit=False)  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文