我正在尝试在django中制作用户注册表 我浏览了许多链接,但我仍然感到困惑。我正在制作一些基石错误,请指出。 这是我的代码:
models.py
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
class UserProfile(models.Model):
mobile = models.CharField(max_length = 20, null=False)
address = models.CharField(max_length = 200)
user = models.OneToOneField(User, unique=True)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CustomerRegistrationForm(UserCreationForm):
mobile = forms.CharField(max_length = 20)
address = forms.CharField(max_length = 200)
class Meta:
model = User
fields = ('username','email','mobile','address','password1','password2')
view.py
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from neededform.forms import CustomerRegistrationForm
def register(request):
print "I am in register function"
if request.method == 'POST':
if request.method == 'POST':
form = CustomerRegistrationForm(request.POST)
if form.is_valid():
f = form.save()
return HttpResponseRedirect('/registered/')
else:
args = {}
args.update(csrf(request))
args['form'] = CustomerRegistrationForm()
return render_to_response('User_Registration.html', args ,context_instance = RequestContext(request))
我在想的是,当我在views.py中执行form.save()
时,django应该在auth_user
表中创建用户并且必须插入值(即移动 UserProfile
表中还有地址)。
但是发生的事情是它正在auth_user
表中正确插入数据但在UserProfile表中只填充id
和user_id
颜色,mobile
和address
仍然是空的。
我究竟做错了什么 ?还有什么必须做的?
谢谢。
答案 0 :(得分:2)
看看以下内容:
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
您创建的UserProfile
对象仅设置了user
属性!
我不认为使用signal
是解决问题的最佳方法,因为将mobile
和address
从表单传递到配置文件创建点并不容易。相反,您可以覆盖首先保存用户的save()
CustomerRegistrationForm
方法,然后创建配置文件。像这样:
class CustomerRegistrationForm(UserCreationForm):
# rest code ommited
def save(self, commit=True):
user = super(CustomerRegistrationForm, self).save()
p = UserProfile.objects.get_or_create(user=user )
p[0].mobile = self.cleaned_data['mobile']
p[0].address = self.cleaned_data['address']
p[0].save()
return user