我想在django中創建一個用戶註冊表單。
我瀏覽了很多鏈接,但我仍然感到困惑。我正在犯一些基石錯誤,請指出。 這裏是我的代碼:在django字段不存儲值的custome用戶創建
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
表正確地插入數據,但在用戶配置表中只有id
和user_id
coloumns充滿,mobile
和address
都保持爲空。
我在做什麼錯?還有什麼必須做的? 謝謝。
您的表單不正確。您已將兩個字段添加到連接到'User'模型的表單。所以它會保存'User'的所有字段並忽略其他字段。在'save'過程中,手動添加一個'UserProfile'實例和表單的'cleaned_data'。 – arocks