我想在用户个人资料中添加新字段。它在管理方面工作,但它没有在前端保存......它非常好奇,因为没有显示错误,它只是保存。
在下面的代码中,我将字段“CPF”添加到了 userprofile。它在前端表单中正确显示,然后我尝试保存它(这里发生了一些问题)
我很感激任何帮助。
模型.py
from django.db import models
from django.contrib.auth.models import User
...
cpf = models.CharField('CPF',max_length=14)
...
def __unicode__(self):
return self.cpf
表格.py
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from usuario.models import UserProfile
class cadastroForm(UserCreationForm):
...
cpf = forms.CharField(label='CPF')
class Meta:
model = User
fields = ("username", "cpf")
def save(self, commit=True):
...
user.cpf = self.cleaned_data["cpf"]
if commit:
user.save()
return user
视图.py
def cadastro(request):
if request.method == 'POST':
form = cadastroForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/")
else:
form = cadastroForm()
return render_to_response("registration/registration.html", {
'form': form,
})
admin.py(它工作正常,不需要任何更改)
from django.contrib import admin
from usuario.models import UserProfile
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
class UserProfileInline(admin.StackedInline):
model = UserProfile
max_num = 1
can_delete = False
class UserAdmin(AuthUserAdmin):
inlines = [UserProfileInline]
admin.site.unregister(User)
admin.site.register(User, UserAdmin)