我是Django的新手,无法使用基于类的视图保存“注册”表单。我在模型中创建了Abstract用户,如下所示。
models.py
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
full_name = models.CharField(max_length=255, blank=True, null=True)
active = models.BooleanField(default=True) # can login
staff = models.BooleanField(default=False) # staff user non superuser
admin = models.BooleanField(default=False) # superuser
timestamp = models.DateTimeField(auto_now_add=True)
user_type = models.CharField(max_length= 120, choices=u_type)
# confirm = models.BooleanField(default=False)
# confirmed_date = models.DateTimeField(default=False)
USERNAME_FIELD = 'email' #username
# USERNAME_FIELD and password are required by default
REQUIRED_FIELDS = [] #['full_name'] #python manage.py createsuperuser
objects = UserManager()
def __str__(self):
return self.email
def get_full_name(self):
if self.full_name:
return self.full_name
return self.email
def get_short_name(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.staff
@property
def is_admin(self):
return self.admin
@property
def is_active(self):
return self.active
我已使用表格创建注册表格,如下所示 forms.py
class RegistrationForm(forms.Form):
password1 = forms.CharField(label='password')
password2 = forms.CharField(label='Confirm Password')
user_email = forms.CharField(label='Email')
full_name = forms.CharField(label='Full Name')
class Meta:
model = User
fields = ('full_name', 'email','user_type')
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('password does not match')
return password2
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user_mail = self.cleaned_data.get('user_email')
print(user_mail)
user.set_password(self.cleaned_data['password1'])
if(commit):
user.save()
return user
这是表单的视图文件
views.py
class RegisterView(FormView):
form_class = RegistrationForm
template_name = 'register.html'
success_url='/login'
def form_valid(self,form):
request = self.request
# f = JobForm(request.POST)
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
print(form)
instance = form.save(commit=False)
return redirect('/')
我面临的问题是,当我尝试保存注册表时,它给我的错误是“超级”对象没有属性“保存”。目前,我正在努力使用基于类的视图保存表单。