模型.py:
class Profile(models.Model):
user = models.OneToOneField(User, related_name='profile')
code = models.CharField('Invitation Code', max_length=32)
def __unicode__(self):
return self.user.first_name
表格.py:
from app.models import Profile
class RegistrationForm(forms.Form):
login = forms.CharField(label='Login', max_length=10, required=True)
name = forms.CharField(label='First name', max_length=10, required=True)
password0 = forms.CharField(label='Pass', max_length=32, required=True)
password1 = forms.CharField(label='Pass', max_length=32, required=True)
codeword = forms.CharField(label='Invitation code', max_length=32, required=True)
在我使用的模板中:
<form action="{% url 'registration' %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
视图.py:
def registration(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid() and form.cleaned_data['password0']==form.cleaned_data['password1'] and form.cleaned_data['rules_agree']:
try:
user = User.objects.create_user(form.cleaned_data['login'], password=form.cleaned_data['password0'])
user.first_name = form.cleaned_data['name']
user.code = form.cleaned_data['codeword']
user.save()
except IntegrityError:
error = 'Duplicate user'
return render(request, 'registration.html', {'form': form, 'error': error})
return HttpResponseRedirect('/thanks')
else:
form = RegistrationForm()
return render(request, 'registration.html', {'form': form,})
因此,用户保存在 db 中,但配置文件模型为空。我尝试user.profile.code
,但结果是一样的。如何解决?谢谢。