我已经创建了自己的自定义用户模型并制作了一个表单,然后用一些额外的字段扩展它(我这样做,因为我将有两个注册表单)。第二种形式有一个用户模型的onetoonefield,但我想出如何告诉onetoonefield应该设置哪个用户。谁能告诉我怎么做?感谢
模特 -
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('email address', unique=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
is_staff = models.BooleanField('staff status', default=False,
help_text='Designates whether the user can log into this admin site.')
is_active = models.BooleanField('active', default=True,
help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.')
date_joined = models.DateTimeField('date joined', default=timezone.now)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email])
#https://www.lasolution.be/blog/creating-custom-user-model-django-16-part-1.html
class StudentModel(models.Model):
email = models.OneToOneField(User, unique=True)
birth_date = models.DateField()
contact_number = models.CharField(max_length=20, blank=True, null=True)
area_code = models.CharField(max_length=5, choices=area_code_choice, blank=True)
referral = models.CharField(max_length=100, choices=referral_choices)
表格 -
class UserForm(forms.ModelForm):
email = forms.EmailField()
password1 = forms.CharField(
label=("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(
label=("Password confirmation"),
widget=forms.PasswordInput,
help_text=("Enter the same password as above, for verification."))
class Meta:
model = User
fields = ['first_name', 'last_name', 'email', 'password1', 'password2']
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise ValidationError("Both Passwords must match!")
return password2
class StudentForm(forms.ModelForm):
class Meta:
model = StudentModel
fields = ['birth_date', 'area_code', 'contact_number', 'referral']
查看 -
def register_student(request):
if request.method == "POST":
form_user = UserForm(request.POST)
form_student = StudentForm(request.POST)
if form_user.is_valid() and form_student.is_valid():
form_student.email = form_user.email
profile = form_student.save(commit=False)
profile.save()
return redirect('listing', profile.pk)
else:
form_user = UserForm()
form_student = StudentForm()
context_dict = {
'form_user': form_user,
'form_student': form_student,
}
return render(request, 'register_student.html', context_dict)
目前我正在尝试通过此form_student.email = form_user.email
进行设置,但这会返回以下错误
错误 -
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/users/register-student/
Django Version: 1.9.1
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'main',
'listings',
'profiles',
'opus_login')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python27\Lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\Lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Other folders\Desktop\Student Job Search\code\opus_jobs_project\opus_login\views.py" in register_student
13. form_student.email = form_user.email
Exception Type: AttributeError at /users/register-student/
Exception Value: 'UserForm' object has no attribute 'email'
答案 0 :(得分:1)
您可以参考我放在这里的例子:
def user_registration(request):
if request.method == 'POST':
form = UserForm(request.POST)
form1 = StudentForm(request.POST)
if form.is_valid() and form1.is_valid():
cd = form.cleaned_data
cd1 = form1.cleaned_data
user = form.save()
user.username = user.email # if u want username as email u can do like this (optional)
user.set_password(user.password)
user.save()
profile = form1.save(commit=False)
profile.user = user
# Now we save the StudentForm model instance.
profile.save()
return HttpResponseRedirect('/user-login/')
else:
error = form.errors
error1 = form1.errors
return render(request, 'registration.html', locals())
else:
form = UserForm
form1 = StudentForm
return render(request, 'registration.html', locals())