我正在研究django项目中的注册模块。注册用户我使用auth_user表来扩展这个表我已经创建了另一个模型Profile
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
start_date = models.DateField()
phone_number = models.CharField(max_length=12)
address = models.CharField(max_length=225)
subscription = models.BooleanField(default=False)
已成功创建配置文件表。现在我要做的是当我提交注册表单时,在插入与auth_user模型相关的字段后,应自动插入与注册表单中的Profile模型相关的字段。 意味着我不想先在auth_user模型中插入数据,然后在获取它的id后再次在Profile表中插入数据。 我想在一个查询中插入完整记录。有可能吗?
答案 0 :(得分:0)
我认为您可以定义注册表单并覆盖表单save
方法,以便在创建用户模型时保存Profile
。示例代码供您参考:
class RegistrationForm(forms.ModelForm):
start_date = forms.DateField()
phone_number = forms.CharField()
address = forms.CharField()
subscription = forms.BooleanField()
class Meta:
model = User
def save(self, commit=True):
instance = super(RegistrationForm, self).save(commit=commit)
profile = Profile(user=instance, start_date=self.cleaned_data['start_date'], phone_number=self.cleaned_data['phone_number'], address=self.cleaned_data['address'], subscription=self.cleaned_data['subscription'])
profile.save()
return instance
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save()
# do anything after user created
else:
raise Error('form validate failed')
else:
# handling the GET method