1
我製作了自己的自定義用戶模型,並製作了一個表單,然後將其擴展到一些額外的字段(我這樣做,因爲我將有兩個註冊表單)。第二種形式與用戶模型有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'
你需要分享您的視圖代碼,但它看起來像你需要做的'form_user.cleaned_data [「電子郵件」 ]' – karthikr
嗨Karthikr,視圖代碼在那裏。但是我會提出你的建議嗎? –
是的,請檢查答案。 – karthikr