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='user@gmail.com')
>>> u.get_profile().telefone
u'123123455'
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)
精彩评论